repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278 values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15 values |
|---|---|---|---|---|---|
dev-osrose/osIROSE-new | scripts/mobs/fields/JZ01_2.lua | 2 | 4146 |
--[[ MOB SPAWN LIST
mob(<mob_spawner_alias>, <mob_id>, <mob_count>, <spawner_limit>, <spawn_interval>, <spawner_range>, <map_id>, <x_pos>, <y_pos>, <z_pos>);
--]]
mob("", 276, 1, 1, 25, 5, 32, 5053.38, 5511.8, -2.06);
mob("", 276, 1, 1, 25, 5, 32, 5057.36, 5470.59, 0.05);
mob("", 275, 1, 1, 25, 5, 32, 5116.98, 5513.81, -7.53);
mob("", 284, 1, 1, 25, 5, 32, 5116.98, 5513.81, -7.53);
mob("", 275, 1, 1, 25, 5, 32, 5098.8, 5470.99, -4.89);
mob("", 275, 1, 1, 25, 5, 32, 5107.32, 5558.22, -2.12);
mob("", 278, 1, 2, 20, 5, 32, 5097.83, 5514.18, -6.25);
mob("", 278, 1, 2, 20, 5, 32, 5097.83, 5514.18, -6.25);
mob("", 278, 1, 2, 20, 5, 32, 5097.83, 5514.18, -6.25);
mob("", 278, 1, 2, 20, 5, 32, 5097.83, 5514.18, -6.25);
mob("", 760, 1, 2, 20, 5, 32, 5097.83, 5514.18, -6.25);
mob("", 278, 1, 1, 25, 5, 32, 5071.07, 5486.95, -2.03);
mob("", 276, 1, 1, 25, 5, 32, 5204.01, 5500.27, -0.91);
mob("", 276, 1, 1, 25, 5, 32, 5158.84, 5518.4, -3.83);
mob("", 276, 1, 1, 25, 5, 32, 5159.34, 5482.1, -3.76);
mob("", 275, 1, 1, 25, 5, 32, 5152.59, 5457.1, -2.26);
mob("", 278, 1, 1, 25, 5, 32, 5140.9, 5547.77, -1.68);
mob("", 258, 1, 1, 20, 5, 32, 5246.17, 5497.98, -1.44);
mob("", 276, 1, 1, 25, 5, 32, 5396.29, 5534.8, -6.2);
mob("", 276, 1, 1, 25, 5, 32, 5339.92, 5489.22, -2.36);
mob("", 276, 1, 1, 25, 5, 32, 5342.23, 5513.92, -2.29);
mob("", 276, 1, 1, 25, 5, 32, 5356.42, 5440.78, 0.59);
mob("", 276, 1, 1, 25, 5, 32, 5385.05, 5557.39, -0.6);
mob("", 258, 1, 1, 20, 5, 32, 5285.36, 5499.93, -1.93);
mob("", 276, 1, 1, 25, 5, 32, 5437.53, 5543, 1.83);
mob("", 276, 1, 1, 25, 5, 32, 5330.72, 5548.11, 0.22);
mob("", 275, 1, 1, 25, 5, 32, 5398.12, 5485.89, -3.47);
mob("", 275, 1, 1, 25, 5, 32, 5374.96, 5522.29, -4.64);
mob("", 275, 1, 1, 25, 5, 32, 5353.99, 5457.07, -0.24);
mob("", 275, 1, 1, 25, 5, 32, 5388.83, 5475.13, -2.72);
mob("", 257, 1, 1, 21, 5, 32, 5523.77, 5487.05, -1.27);
mob("", 257, 1, 1, 24, 5, 32, 5499.01, 5498.46, -1.88);
mob("", 276, 1, 1, 25, 5, 32, 5445.35, 5477.28, -0.34);
mob("", 275, 1, 1, 25, 5, 32, 5446.57, 5513.03, -2.71);
mob("", 276, 1, 1, 25, 5, 32, 5524.81, 5447.19, -0.24);
mob("", 1, 0, 1, 25, 5, 32, 5524.81, 5447.19, -0.24);
mob("", 276, 1, 1, 25, 5, 32, 5107.84, 5426.68, 0.89);
mob("", 276, 1, 1, 25, 5, 32, 5412.26, 5429.64, 1.69);
mob("", 275, 1, 1, 25, 5, 32, 5546.51, 5421.42, -1.29);
mob("", 275, 1, 1, 25, 5, 32, 5501.09, 5427.81, -0.59);
mob("", 276, 1, 1, 25, 5, 32, 5118.23, 5211.41, 1.61);
mob("", 276, 1, 1, 25, 5, 32, 5052.43, 5126.42, 0.45);
mob("", 273, 1, 1, 25, 5, 32, 5111.42, 5164.9, -4.01);
mob("", 278, 1, 1, 25, 5, 32, 5085.44, 5189.05, -1.4);
mob("", 278, 1, 1, 25, 5, 32, 5070.95, 5148.69, -3);
mob("", 273, 1, 1, 25, 5, 32, 5232.65, 5243.96, -1.27);
mob("", 276, 1, 1, 25, 5, 32, 5190.03, 5151.03, 0.05);
mob("", 276, 1, 1, 25, 5, 32, 5189.33, 5130.65, -0.28);
mob("", 273, 1, 1, 25, 5, 32, 5271.81, 5241.72, -1.16);
mob("", 278, 1, 1, 25, 5, 32, 5233.43, 5206.49, 0.99);
mob("", 257, 1, 1, 25, 5, 32, 5263.61, 5139.61, -0.61);
mob("", 258, 1, 1, 25, 5, 32, 5263.61, 5139.61, -0.61);
mob("", 276, 1, 1, 25, 5, 32, 5156.98, 5192.99, -0.5);
mob("", 273, 1, 1, 25, 5, 32, 5120.56, 5139.45, -4.9);
mob("", 273, 1, 1, 25, 5, 32, 5175.82, 5176.39, 0.15);
mob("", 273, 1, 1, 25, 5, 32, 5127.72, 5216.83, 2.2);
mob("", 278, 1, 1, 20, 5, 32, 5147.2, 5149.24, -3.8);
mob("", 278, 1, 1, 20, 5, 32, 5147.2, 5149.24, -3.8);
mob("", 278, 1, 1, 20, 5, 32, 5147.2, 5149.24, -3.8);
mob("", 760, 1, 1, 20, 5, 32, 5147.2, 5149.24, -3.8);
mob("", 276, 1, 1, 25, 5, 32, 5384.17, 5230.49, 0);
mob("", 258, 1, 1, 15, 5, 32, 5341.51, 5148.47, -1.16);
mob("", 258, 1, 1, 15, 5, 32, 5345.14, 5209.23, 0);
mob("", 273, 1, 1, 25, 5, 32, 5284.07, 5233.27, -1.74);
mob("", 273, 1, 1, 25, 5, 32, 5460.52, 5223.87, -1.76);
mob("", 276, 1, 1, 25, 5, 32, 5108.14, 5102.72, -2.96);
mob("", 278, 1, 1, 20, 5, 32, 5081.58, 5112.72, -3.14);
mob("", 278, 1, 1, 20, 5, 32, 5081.58, 5112.72, -3.14);
mob("", 278, 1, 1, 20, 5, 32, 5081.58, 5112.72, -3.14);
mob("", 760, 1, 1, 20, 5, 32, 5081.58, 5112.72, -3.14);
mob("", 276, 1, 1, 25, 5, 32, 5133.72, 5102.65, -3.12);
mob("", 276, 1, 1, 25, 5, 32, 5164.84, 5091.8, -0.92);
| apache-2.0 |
eskibars/domoticz | dzVents/runtime/integration-tests/testIntegration.lua | 6 | 23274 | package.path = package.path ..
";../?.lua;../device-adapters/?.lua;./data/?.lua;../../../scripts/dzVents/generated_scripts/?.lua;" ..
"../../../scripts/lua/?.lua"
local TestTools = require('domoticzTestTools')('8080', true)
local socket = require("socket")
local _ = require 'lodash'
local DUMMY_HW = 15
local SWITCH_TYPES = {
BLINDS = 3,
BLINDS_INVERTED= 6,
BLINDS_PERCENTAGE= 13,
BLINDS_PERCENTAGE_INVERTED= 16,
CONTACT= 2,
DIMMER= 7,
DOOR_CONTACT= 11,
DOOR_LOCK= 19,
DOORBELL= 1,
DUSK_SENSOR= 12,
MEDIA_PLAYER= 17,
MOTION_SENSOR= 8,
ON_OFF= 0,
PUSH_OFF_BUTTON= 10,
PUSH_ON_BUTTON= 9,
SELECTOR= 18,
SMOKE_DETECTOR= 5,
VENETIAN_BLINDS_EU= 15,
VENETIAN_BLINDS_US= 14,
X10_SIREN= 4
}
local VIRTUAL_DEVICES = {
AIR_QUALITY = {249, 'vdAirQuality'},
ALERT = {7, 'vdAlert'},
AMPERE_3_PHASE = {9, 'vdAmpere3'},
AMPERE_1_PHASE = {19, 'vdAmpere1'},
BAROMETER = {11, 'vdBarometer'},
COUNTER = {113, 'vdCounter'},
COUNTER_INCREMENTAL = {14, 'vdCounterIncremental'},
CUSTOM_SENSOR = {1004, 'vdCustomSensor'},
DISTANCE = {13, 'vdDistance'},
ELECTRIC_INSTANT_COUNTER = {18, 'vdElectricInstanceCounter'},
GAS = {3, 'vdGas'},
HUMIDITY = {81, 'vdHumidity'},
LEAF_WETNESS = {16, 'vdLeafWetness'},
LUX = {246, 'vdLux'},
P1_SMART_METER_ELECTRIC = {250, 'vdP1SmartMeterElectric'},
PERCENTAGE = {2, 'vdPercentage'},
PRESSURE_BAR = {1, 'vdPressureBar'},
RAIN = {85, 'vdRain'},
RGB_SWITCH = {241, 'vdRGBSwitch'},
RGBW_SWITCH = {1003, 'vdRGBWSwitch'},
SCALE_WEIGHT = {93, 'vdScaleWeight'},
SELECTOR_SWITCH = {1002, 'vdSelectorSwitch'},
SOIL_MOISTURE = {15, 'vdSoilMoisture'},
SOLAR_RADIATION = {20, 'vdSolarRadiation'},
SOUND_LEVEL = {10, 'vdSoundLevel'},
SWITCH = {6, 'vdSwitch'},
TEMPERATURE = {80, 'vdTemperature'},
TEMP_HUM = {82, 'vdTempHum'},
TEMP_HUM_BARO = {84, 'vdTempHumBaro'},
TEXT = {5, 'vdText'},
THERMOSTAT_SETPOINT = {8, 'vdThermostatSetpoint'},
USAGE_ELECTRIC = {248, 'vdUsageElectric'},
UV = {87, 'vdUV'},
VISIBILITY = {12, 'vdVisibility'},
VOLTAGE = {4, 'vdVoltage'},
WATERFLOW = {1000, 'vdWaterflow'},
WIND = {86, 'vdWind'},
WIND_TEMP_CHILL = {1001, 'vdWindTempChill'},
TEMP_BARO = { 247, 'vdTempBaro' },
SILENT_SWITCH = { 6, 'vdSilentSwitch' },
API_TEMP = { 80, 'vdAPITemperature' },
REPEAT_SWITCH = { 6, 'vdRepeatSwitch' },
CANCELLED_REPEAT_SWITCH = { 6, 'vdCancelledRepeatSwitch' },
HTTP_SWITCH = { 6, 'vdHTTPSwitch' },
-- increment SECPANEL_INDEX when adding a new one !!!!!!!!!!
}
local SECPANEL_INDEX = 51
local VAR_TYPES = {
INT = {0, 'varInteger', 42},
FLOAT = {1, 'varFloat', 42.11},
STRING = {2, 'varString', 'Somestring'},
DATE = {3, 'varDate', '31/12/2017'},
TIME = {4, 'varTime', '23:59'},
SILENT = { 0, 'varSilent', 1 },
CANCELLED = { 0, 'varCancelled', 0}
}
describe('Integration test', function ()
setup(function()
assert.is_true(TestTools.deleteAllDevices())
assert.is_true(TestTools.deleteAllVariables())
assert.is_true(TestTools.deleteAllHardware())
assert.is_true(TestTools.deleteAllScripts())
end)
teardown(function()
TestTools.removeGUIScript('stage1.lua')
TestTools.removeFSScript('stage2.lua')
TestTools.removeFSScript('silent.lua')
TestTools.removeFSScript('vdSwitchDimmer.lua')
TestTools.removeFSScript('vdRepeatSwitch.lua')
TestTools.removeFSScript('vdCancelledRepeatSwitch.lua')
TestTools.removeFSScript('secArmedAway.lua')
TestTools.removeFSScript('varString.lua')
TestTools.removeFSScript('varCancelled.lua')
TestTools.removeFSScript('scScene.lua')
TestTools.removeFSScript('scCancelledScene.lua')
TestTools.removeFSScript('some_module.lua')
TestTools.removeFSScript('global_data.lua')
TestTools.removeFSScript('httpResponseScript.lua')
TestTools.removeDataFile('__data_global_data.lua')
TestTools.removeDataFile('__data_secArmedAway.lua')
end)
before_each(function()
end)
after_each(function() end)
local dummyIdx
local stage1TriggerIdx
local endResultsIdx
local switchDimmerResultsIdx
local varStringResultsIdx
local secArmedAwayIdx
local scSceneResultsIdx
local switchSilentResultsIdx
-- it('a', function() end)
--
describe('Settings', function()
it('Should initialize settings', function()
local ok, result, respcode, respheaders, respstatus = TestTools.initSettings()
assert.is_true(ok)
end)
end)
describe('Hardware', function()
it('should create dummy hardware', function()
local ok
ok, dummyIdx = TestTools.createHardware('dummy', DUMMY_HW)
assert.is_true(ok)
end)
end)
describe('Devices', function()
it('should create a virtual switch', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.SWITCH[2], VIRTUAL_DEVICES.SWITCH[1])
assert.is_true(ok)
ok = TestTools.updateSwitch(idx, VIRTUAL_DEVICES.SWITCH[2], 'desc%20' .. VIRTUAL_DEVICES.SWITCH[2], SWITCH_TYPES.ON_OFF)
assert.is_true(ok)
end)
it('should create a air quality device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.AIR_QUALITY[2], VIRTUAL_DEVICES.AIR_QUALITY[1])
assert.is_true(ok)
end)
it('should create an alert device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.ALERT[2], VIRTUAL_DEVICES.ALERT[1])
assert.is_true(ok)
end)
it('should create an AMPERE_3_PHASE device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.AMPERE_3_PHASE[2], VIRTUAL_DEVICES.AMPERE_3_PHASE[1])
assert.is_true(ok)
end)
it('should create an AMPERE_1_PHASE device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.AMPERE_1_PHASE[2], VIRTUAL_DEVICES.AMPERE_1_PHASE[1])
assert.is_true(ok)
end)
it('should create an BAROMETER device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.BAROMETER[2], VIRTUAL_DEVICES.BAROMETER[1])
assert.is_true(ok)
end)
it('should create an COUNTER device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.COUNTER[2], VIRTUAL_DEVICES.COUNTER[1])
assert.is_true(ok)
end)
it('should create an COUNTER_INCREMENTAL device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.COUNTER_INCREMENTAL[2], VIRTUAL_DEVICES.COUNTER_INCREMENTAL[1])
assert.is_true(ok)
end)
it('should create an CUSTOM_SENSOR device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.CUSTOM_SENSOR[2], VIRTUAL_DEVICES.CUSTOM_SENSOR[1], 'axis')
assert.is_true(ok)
end)
it('should create an DISTANCE device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.DISTANCE[2], VIRTUAL_DEVICES.DISTANCE[1])
assert.is_true(ok)
end)
it('should create an ELECTRIC_INSTANT_COUNTER device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.ELECTRIC_INSTANT_COUNTER[2], VIRTUAL_DEVICES.ELECTRIC_INSTANT_COUNTER[1])
assert.is_true(ok)
end)
it('should create an GAS device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.GAS[2], VIRTUAL_DEVICES.GAS[1])
assert.is_true(ok)
end)
it('should create an HUMIDITY device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.HUMIDITY[2], VIRTUAL_DEVICES.HUMIDITY[1])
assert.is_true(ok)
end)
it('should create an LEAF_WETNESS device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.LEAF_WETNESS[2], VIRTUAL_DEVICES.LEAF_WETNESS[1])
assert.is_true(ok)
end)
it('should create an LUX device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.LUX[2], VIRTUAL_DEVICES.LUX[1])
assert.is_true(ok)
end)
it('should create an P1_SMART_METER_ELECTRIC device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.P1_SMART_METER_ELECTRIC[2], VIRTUAL_DEVICES.P1_SMART_METER_ELECTRIC[1])
assert.is_true(ok)
end)
it('should create an PERCENTAGE device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.PERCENTAGE[2], VIRTUAL_DEVICES.PERCENTAGE[1])
assert.is_true(ok)
end)
it('should create an PRESSURE_BAR device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.PRESSURE_BAR[2], VIRTUAL_DEVICES.PRESSURE_BAR[1])
assert.is_true(ok)
end)
it('should create an RAIN device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.RAIN[2], VIRTUAL_DEVICES.RAIN[1])
assert.is_true(ok)
end)
it('should create an RGB_SWITCH device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.RGB_SWITCH[2], VIRTUAL_DEVICES.RGB_SWITCH[1])
assert.is_true(ok)
end)
it('should create an RGBW_SWITCH device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.RGBW_SWITCH[2], VIRTUAL_DEVICES.RGBW_SWITCH[1])
assert.is_true(ok)
end)
it('should create an SCALE_WEIGHT device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.SCALE_WEIGHT[2], VIRTUAL_DEVICES.SCALE_WEIGHT[1])
assert.is_true(ok)
end)
it('should create an SELECTOR_SWITCH device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.SELECTOR_SWITCH[2], VIRTUAL_DEVICES.SELECTOR_SWITCH[1])
assert.is_true(ok)
end)
it('should create an SOIL_MOISTURE device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.SOIL_MOISTURE[2], VIRTUAL_DEVICES.SOIL_MOISTURE[1])
assert.is_true(ok)
end)
it('should create an SOLAR_RADIATION device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.SOLAR_RADIATION[2], VIRTUAL_DEVICES.SOLAR_RADIATION[1])
assert.is_true(ok)
end)
it('should create an SOUND_LEVEL device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.SOUND_LEVEL[2], VIRTUAL_DEVICES.SOUND_LEVEL[1])
assert.is_true(ok)
end)
it('should create an TEMPERATURE device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.TEMPERATURE[2], VIRTUAL_DEVICES.TEMPERATURE[1])
assert.is_true(ok)
end)
it('should create an TEMP_HUM device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.TEMP_HUM[2], VIRTUAL_DEVICES.TEMP_HUM[1])
assert.is_true(ok)
end)
it('should create an TEMP_HUM_BARO device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.TEMP_HUM_BARO[2], VIRTUAL_DEVICES.TEMP_HUM_BARO[1])
assert.is_true(ok)
end)
it('should create an TEXT device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.TEXT[2], VIRTUAL_DEVICES.TEXT[1])
assert.is_true(ok)
end)
it('should create an THERMOSTAT_SETPOINT device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.THERMOSTAT_SETPOINT[2], VIRTUAL_DEVICES.THERMOSTAT_SETPOINT[1])
assert.is_true(ok)
end)
it('should create an USAGE_ELECTRIC device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.USAGE_ELECTRIC[2], VIRTUAL_DEVICES.USAGE_ELECTRIC[1])
assert.is_true(ok)
end)
it('should create an UV device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.UV[2], VIRTUAL_DEVICES.UV[1])
assert.is_true(ok)
end)
it('should create an VISIBILITY device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.VISIBILITY[2], VIRTUAL_DEVICES.VISIBILITY[1])
assert.is_true(ok)
end)
it('should create an VOLTAGE device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.VOLTAGE[2], VIRTUAL_DEVICES.VOLTAGE[1])
assert.is_true(ok)
end)
it('should create an WATERFLOW device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.WATERFLOW[2], VIRTUAL_DEVICES.WATERFLOW[1])
assert.is_true(ok)
end)
it('should create an WIND device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.WIND[2], VIRTUAL_DEVICES.WIND[1])
assert.is_true(ok)
end)
it('should create an WIND_TEMP_CHILL device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.WIND_TEMP_CHILL[2], VIRTUAL_DEVICES.WIND_TEMP_CHILL[1])
assert.is_true(ok)
end)
it('should create a dimmer', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, 'vdSwitchDimmer', VIRTUAL_DEVICES.SWITCH[1])
assert.is_true(ok)
ok = TestTools.updateSwitch(idx, 'vdSwitchDimmer', 'desc%20vdSwitchDimmer', SWITCH_TYPES.DIMMER)
assert.is_true(ok)
ok = TestTools.dimTo(idx, 'Set%20Level', 34) -- will end up like 33% for some weird reason
assert.is_true(ok)
end)
it('should create an TEMP_BARO device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.TEMP_BARO[2], VIRTUAL_DEVICES.TEMP_BARO[1])
assert.is_true(ok)
end)
it('should create an silent device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.SILENT_SWITCH[2], VIRTUAL_DEVICES.SILENT_SWITCH[1])
assert.is_true(ok)
end)
it('should create an temp sensor device that will be update via the API', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.API_TEMP[2], VIRTUAL_DEVICES.API_TEMP[1])
assert.is_true(ok)
end)
it('should create an repeat device', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.REPEAT_SWITCH[2], VIRTUAL_DEVICES.REPEAT_SWITCH[1])
assert.is_true(ok)
end)
it('should create an repeat device that will be canceled', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.CANCELLED_REPEAT_SWITCH[2], VIRTUAL_DEVICES.CANCELLED_REPEAT_SWITCH[1])
assert.is_true(ok)
end)
it('should create a http switch to trigger http requests', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, VIRTUAL_DEVICES.HTTP_SWITCH[2], VIRTUAL_DEVICES.HTTP_SWITCH[1])
assert.is_true(ok)
end)
end)
describe('Groups and scenes', function()
it('should create a scene', function()
-- first create switch to be put in the scene
local ok
local switchIdx
local sceneIdx = 1 -- api doesn't return the idx so we assume this is 1
ok, switchIdx = TestTools.createVirtualDevice(dummyIdx, 'sceneSwitch1', 6)
assert.is_true(ok)
ok = TestTools.createScene('scScene')
assert.is_true(ok)
ok = TestTools.addSceneDevice(sceneIdx, switchIdx)
assert.is_true(ok)
end)
it('should create a group', function()
local ok
local switchIdx
local groupIdx = 2
-- first create switch to be put in the group
ok, switchIdx = TestTools.createVirtualDevice(dummyIdx, 'groupSwitch1', 6)
assert.is_true(ok)
ok = TestTools.createGroup('gpGroup')
assert.is_true(ok)
ok = TestTools.addSceneDevice(groupIdx, switchIdx)
assert.is_true(ok)
end)
it('should create a silent scene', function()
-- scene that will be switched on with .silent()
-- it should not trigger a script
local ok
local switchIdx
local sceneIdx = 3 -- api doesn't return the idx so we assume this is 1
ok, switchIdx = TestTools.createVirtualDevice(dummyIdx, 'sceneSilentSwitch1', 6)
assert.is_true(ok)
ok = TestTools.createScene('scSilentScene')
assert.is_true(ok)
ok = TestTools.addSceneDevice(sceneIdx, switchIdx)
assert.is_true(ok)
end)
it('should create a silent group', function()
local ok
local switchIdx
local groupIdx = 4
-- first create switch to be put in the group
ok, switchIdx = TestTools.createVirtualDevice(dummyIdx, 'groupSilentSwitch1', 6)
assert.is_true(ok)
ok = TestTools.createGroup('gpSilentGroup')
assert.is_true(ok)
ok = TestTools.addSceneDevice(groupIdx, switchIdx)
assert.is_true(ok)
end)
it('should create a scene which update will be cancelled', function()
local ok
local switchIdx
local sceneIdx = 4 -- api doesn't return the idx so we assume this is 1
ok, switchIdx = TestTools.createVirtualDevice(dummyIdx, 'sceneCancelledSwitch1', 6)
assert.is_true(ok)
ok = TestTools.createScene('scCancelledScene')
assert.is_true(ok)
ok = TestTools.addSceneDevice(sceneIdx, switchIdx)
assert.is_true(ok)
end)
end)
describe('Variables', function()
it('should create an integer variable', function()
local ok, idx = TestTools.createVariable(VAR_TYPES.INT[2], VAR_TYPES.INT[1], VAR_TYPES.INT[3])
assert.is_true(ok)
end)
it('should create an FLOAT variable', function()
local ok, idx = TestTools.createVariable(VAR_TYPES.FLOAT[2], VAR_TYPES.FLOAT[1], VAR_TYPES.FLOAT[3])
assert.is_true(ok)
end)
it('should create an STRING variable', function()
local ok, idx = TestTools.createVariable(VAR_TYPES.STRING[2], VAR_TYPES.STRING[1], VAR_TYPES.STRING[3])
assert.is_true(ok)
end)
it('should create an DATE variable', function()
local ok, idx = TestTools.createVariable(VAR_TYPES.DATE[2], VAR_TYPES.DATE[1], VAR_TYPES.DATE[3])
assert.is_true(ok)
end)
it('should create an TIME variable', function()
local ok, idx = TestTools.createVariable(VAR_TYPES.TIME[2], VAR_TYPES.TIME[1], VAR_TYPES.TIME[3])
assert.is_true(ok)
end)
it('should create an silent variable', function()
-- doesn't create an event when changed
local ok, idx = TestTools.createVariable(VAR_TYPES.SILENT[2], VAR_TYPES.SILENT[1], VAR_TYPES.SILENT[3])
assert.is_true(ok)
end)
it('should create an variable which after-update will be cancelled', function()
-- doesn't create an event when changed
local ok, idx = TestTools.createVariable(VAR_TYPES.CANCELLED[2], VAR_TYPES.CANCELLED[1], VAR_TYPES.CANCELLED[3])
assert.is_true(ok)
end)
end)
describe('Preparing security panel', function ()
it('Should create a security panel', function()
local ok = TestTools.setDisarmed()
assert.is_true(ok)
ok = TestTools.addSecurityPanel(SECPANEL_INDEX)
assert.is_true(ok)
end)
end)
describe('Preparing scripts and triggers', function()
it('Should create a dzVents script', function()
assert.is_true(TestTools.createGUIScriptFromFile('./stage1.lua'))
end)
it('Should move stage2 script in place', function()
TestTools.createFSScript('stage2.lua')
end)
it('Should move vdSwitchDimmer script in place', function()
TestTools.createFSScript('vdSwitchDimmer.lua')
end)
it('Should move vdRepeatSwitch script in place', function()
TestTools.createFSScript('vdRepeatSwitch.lua')
end)
it('Should move vdCancelledRepeatSwitch script in place', function()
TestTools.createFSScript('vdCancelledRepeatSwitch.lua')
end)
it('Should move varString script in place', function()
TestTools.createFSScript('varString.lua')
end)
it('Should move varCancelled script in place', function()
TestTools.createFSScript('varCancelled.lua')
end)
it('Should move scScene script in place', function()
TestTools.createFSScript('scScene.lua')
end)
it('Should move scCancelledScene script in place', function()
TestTools.createFSScript('scCancelledScene.lua')
end)
it('Should move secArmedAway script in place', function()
TestTools.createFSScript('secArmedAway.lua')
end)
it('Should move globaldata script in place', function()
TestTools.createFSScript('global_data.lua')
end)
it('Should move silent script in place', function()
TestTools.createFSScript('silent.lua')
end)
it('Should move a module in place', function()
TestTools.createFSScript('some_module.lua')
end)
it('Should move a httpResponse event script in place', function()
TestTools.createFSScript('httpResponseScript.lua')
end)
it('Should create the stage1 trigger switch', function()
local ok
ok, stage1TriggerIdx = TestTools.createVirtualDevice(dummyIdx, 'stage1Trigger', VIRTUAL_DEVICES.SWITCH[1])
assert.is_true(ok)
end)
it('Should create the stage2 trigger switch', function()
local ok, idx = TestTools.createVirtualDevice(dummyIdx, 'stage2Trigger', VIRTUAL_DEVICES.SWITCH[1])
assert.is_true(ok)
end)
it('Should create results for vdSwitchDimmer script ', function()
ok, switchDimmerResultsIdx = TestTools.createVirtualDevice(dummyIdx, 'switchDimmerResults', VIRTUAL_DEVICES.TEXT[1])
assert.is_true(ok)
end)
it('Should create results for varString script ', function()
ok, varStringResultsIdx = TestTools.createVirtualDevice(dummyIdx, 'varStringResults', VIRTUAL_DEVICES.TEXT[1])
assert.is_true(ok)
end)
it('Should create results for secArmedAway script ', function()
ok, secArmedAwayIdx = TestTools.createVirtualDevice(dummyIdx, 'secArmedAwayResults', VIRTUAL_DEVICES.TEXT[1])
assert.is_true(ok)
end)
it('Should create results for scScene script ', function()
ok, scSceneResultsIdx = TestTools.createVirtualDevice(dummyIdx, 'scSceneResults', VIRTUAL_DEVICES.TEXT[1])
assert.is_true(ok)
end)
it('Should create results for silent script', function()
ok, switchSilentResultsIdx = TestTools.createVirtualDevice(dummyIdx, 'switchSilentResults', VIRTUAL_DEVICES.SWITCH[1])
assert.is_true(ok)
end)
it('Should create the final results text device', function()
local ok
ok, endResultsIdx = TestTools.createVirtualDevice(dummyIdx, 'endResult', VIRTUAL_DEVICES.TEXT[1])
assert.is_true(ok)
end)
end)
describe('Start the tests', function()
it('Should all just work fine', function()
socket.sleep(1)
local ok = TestTools.switch(stage1TriggerIdx, 'On')
assert.is_true(ok)
end)
it('Should have succeeded', function()
socket.sleep(25) -- the trigger for stage 2 has a delay set to 4 seconds (afterSec(4))
local switchDimmerResultsDevice
local varStringResultsDevice
local secArmedAwayDevice
local scSceneResultsDevice
local switchSilentResultsDevice
local ok = false
local endResultsDevice
ok, endResultsDevice = TestTools.getDevice(endResultsIdx)
assert.is_true(ok)
ok = false
ok, switchDimmerResultsDevice = TestTools.getDevice(switchDimmerResultsIdx)
assert.is_true(ok)
ok = false
ok, varStringResultsDevice = TestTools.getDevice(varStringResultsIdx)
assert.is_true(ok)
ok = false
ok, secArmedAwayDevice = TestTools.getDevice(secArmedAwayIdx)
assert.is_true(ok)
ok = false
ok, scSceneResultsDevice = TestTools.getDevice(scSceneResultsIdx)
assert.is_true(ok)
ok = false
ok, switchSilentResultsDevice = TestTools.getDevice(switchSilentResultsIdx)
assert.is_true(ok)
assert.is_same('ENDRESULT SUCCEEDED', endResultsDevice['Data'])
assert.is_same('DIMMER SUCCEEDED', switchDimmerResultsDevice['Data'])
assert.is_same('STRING VARIABLE SUCCEEDED', varStringResultsDevice['Data'])
assert.is_same('SECURITY SUCCEEDED', secArmedAwayDevice['Data'])
assert.is_same('SCENE SUCCEEDED', scSceneResultsDevice['Data'])
assert.is_same('Off', switchSilentResultsDevice['Status'])
end)
-- it('NOTE', function()
-- print('DONT FORGET TO SWITCH OFF TESTMODE IN dVents.lua !!!!!')
-- end)
end)
end);
| gpl-3.0 |
dev-osrose/osIROSE-new | scripts/mobs/ai/ruper_wizard.lua | 2 | 1953 | registerNpc(347, {
walk_speed = 210,
run_speed = 700,
scale = 150,
r_weapon = 1064,
l_weapon = 0,
level = 98,
hp = 27,
attack = 413,
hit = 219,
def = 313,
res = 359,
avoid = 148,
attack_spd = 95,
is_magic_damage = 1,
ai_type = 129,
give_exp = 79,
drop_type = 379,
drop_money = 0,
drop_item = 49,
union_number = 49,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 1500,
npc_type = 7,
hit_material_type = 1,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
registerNpc(349, {
walk_speed = 210,
run_speed = 700,
scale = 150,
r_weapon = 1064,
l_weapon = 0,
level = 98,
hp = 27,
attack = 413,
hit = 219,
def = 313,
res = 359,
avoid = 148,
attack_spd = 100,
is_magic_damage = 1,
ai_type = 138,
give_exp = 79,
drop_type = 379,
drop_money = 0,
drop_item = 48,
union_number = 48,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 1500,
npc_type = 7,
hit_material_type = 1,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end | apache-2.0 |
Wohlhabend-Networks/PGE-Project | Engine/_resources/script/maincore_level.lua | 1 | 1661 |
-- We need to reference all placed objects with lua or the garbage collector will hit it
local __refs = {}
__refs.players = {}
__refs.npcs = {}
-- Debug stuff
local deb_i = 0
local function temp_count(t) local i = 0 for _,__ in pairs(t) do i = i + 1 end return i end
-- Debug stuff end
function onLoop()
if(Settings.isDebugInfoShown())then
deb_i = deb_i + 1
Renderer.printText("Ticks passed: "..deb_i, 100, 130, FontType.DefaultRaster, 15, 0xFFFF0055)
if(npc_class_table)then
Renderer.printText(temp_count(npc_class_table).." Npc registered!", 100, 160, FontType.DefaultRaster, 15, 0xFFFF0055)
else
Renderer.printText("No Npc registered!", 100, 160, FontType.DefaultRaster, 15, 0xFFFF0055)
end
end
end
function __native_event(eventObj, ...)
local eventFuncToFind = "on"..eventObj.eventName:sub(0, 1):upper()..eventObj.eventName:sub(2)
-- Logger.debug(eventFuncToFind)
if(type(_G[eventFuncToFind]) == "function")then
_G[eventFuncToFind](...)
end
end
function __create_luaplayer()
local newPlayer = bases.player()
__refs.players[newPlayer] = true --Be sure that the garbage collector doesn't destory our object
return newPlayer
end
function __create_luanpc()
local newNPC = bases.npc()
__refs.npcs[newNPC] = true --Be sure that the garbage collector doesn't destory our object
return newNPC
end
function __destroy_luanpc(theNPC)
__refs.npcs[theNPC] = nil --Let the garbage collector destory our object
end
function __destroy_luaplayer(thePlayer)
__refs.players[thePlayer] = nil --Let the garbage collector destory our object
end
| gpl-3.0 |
fire855/android_external_skia | tools/lua/scrape.lua | 145 | 2246 | function tostr(t)
local str = ""
for k, v in next, t do
if #str > 0 then
str = str .. ", "
end
if type(k) == "number" then
str = str .. "[" .. k .. "] = "
else
str = str .. tostring(k) .. " = "
end
if type(v) == "table" then
str = str .. "{ " .. tostr(v) .. " }"
else
str = str .. tostring(v)
end
end
return str
end
local total = {} -- accumulate() stores its data in here
local canvas -- holds the current canvas (from startcanvas())
--[[
startcanvas() is called at the start of each picture file, passing the
canvas that we will be drawing into, and the name of the file.
Following this call, there will be some number of calls to accumulate(t)
where t is a table of parameters that were passed to that draw-op.
t.verb is a string holding the name of the draw-op (e.g. "drawRect")
when a given picture is done, we call endcanvas(canvas, fileName)
]]
function sk_scrape_startcanvas(c, fileName)
canvas = c
end
--[[
Called when the current canvas is done drawing.
]]
function sk_scrape_endcanvas(c, fileName)
canvas = nil
end
--[[
Called with the parameters to each canvas.draw call, where canvas is the
current canvas as set by startcanvas()
]]
function sk_scrape_accumulate(t)
local n = total[t.verb] or 0
total[t.verb] = n + 1
if false and t.verb == "drawRect" and t.paint:isAntiAlias() then
local r = t.rect;
local p = t.paint;
local c = p:getColor();
print("drawRect ", tostr(r), tostr(c), "\n")
end
if false and t.verb == "drawPath" then
local pred, r1, r2, d1, d2 = t.path:isNestedRects()
if pred then
print("drawRect_Nested", tostr(r1), tostr(r2), d1, d2)
else
print("drawPath", "isEmpty", tostring(t.path:isEmpty()),
"isRect", tostring(t.path:isRect()), tostr(t.path:getBounds()))
end
end
end
--[[
lua_pictures will call this function after all of the pictures have been
"accumulated".
]]
function sk_scrape_summarize()
io.write("\n{ ", tostr(total), " }\n")
end
| bsd-3-clause |
MinetestForFun/minetest-minetestforfun-server | mods/3d_armor/3d_armor_ui/init.lua | 3 | 1819 | -- support for i18n
local S = armor_i18n.gettext
local F = minetest.formspec_escape
local has_technic = minetest.get_modpath("technic") ~= nil
if not minetest.global_exists("unified_inventory") then
minetest.log("warning", S("3d_armor_ui: Mod loaded but unused."))
return
end
if unified_inventory.sfinv_compat_layer then
return
end
armor:register_on_update(function(player)
local name = player:get_player_name()
if unified_inventory.current_page[name] == "armor" then
unified_inventory.set_inventory_formspec(player, "armor")
end
end)
unified_inventory.register_button("armor", {
type = "image",
image = "inventory_plus_armor.png",
tooltip = S("3d Armor")
})
unified_inventory.register_page("armor", {
get_formspec = function(player, perplayer_formspec)
local fy = perplayer_formspec.formspec_y
local name = player:get_player_name()
if armor.def[name].init_time == 0 then
return {formspec="label[0,0;"..F(S("Armor not initialized!")).."]"}
end
local formspec = "background[0.06,"..fy..";7.92,7.52;3d_armor_ui_form.png]"..
"label[0,0;"..F(S("Armor")).."]"..
"list[detached:"..name.."_armor;armor;0,"..fy..";2,3;]"..
"image[2.5,"..(fy - 0.25)..";2,4;"..armor.textures[name].preview.."]"..
"label[5.0,"..(fy + 0.0)..";"..F(S("Level"))..": "..armor.def[name].level.."]"..
"label[5.0,"..(fy + 0.5)..";"..F(S("Heal"))..": "..armor.def[name].heal.."]"..
"listring[current_player;main]"..
"listring[detached:"..name.."_armor;armor]"
if armor.config.fire_protect then
formspec = formspec.."label[5.0,"..(fy + 1.0)..";"..
F(S("Fire"))..": "..armor.def[name].fire.."]"
end
if has_technic then
formspec = formspec.."label[5.0,"..(fy + 1.5)..";"..
F(S("Radiation"))..": "..armor.def[name].groups["radiation"].."]"
end
return {formspec=formspec}
end,
})
| unlicense |
alikingambav/archer3 | bot/utils.lua | 11 | 26466 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires Sudo users'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Group ban list :\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
-- vardump(user_info)
if user_info then
if user_info.username then
user = '@'..user_info.username
elseif user_info.print_name and not user_info.username then
user = string.gsub(user_info.print_name, "_", " ")
else
user = ''
end
text = text..k.." - "..user.." ["..v.."]\n"
end
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans :\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
-- vardump(user_info)
if user_info then
if user_info.username then
user = '@'..user_info.username
elseif user_info.print_name and not user_info.username then
user = string.gsub(user_info.print_name, "_", " ")
else
user = ''
end
text = text..k.." - "..user.." ["..v.."]\n"
end
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.."\nBanned from group!\n\nName : "..result.from.print_name.."\nUsername : @"..result.from.username)
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.."\nBanned from group!\nUsername : @"..result.from.username)
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.."\nUnbanned from all of my Groups!\n\nusername : @"..result.from.username)
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User Banned From all of my groups!\n\nName : "..name.."\n\nID : "..result.from.id.."\n\nUsername : @"..result.from.username)
else
return 'Use This in Your Groups'
end
end
-- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
--
--
-- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
-- ||\\ //|| //\\ || //|| //\\ // || || //
-- || \\ // || // \\ || // || // \\ // || || //
-- || \\ // || // \\ || // || // \\ || || || //
-- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || //
-- || \\ // || // \\ || // || // \\ || || || || \\
-- || \\ // || // \\ || // || // \\ \\ || || || \\
-- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\
--
--
-- ||-_-_-_- || || || //-_-_-_-_-_-
-- || || || || || //
-- ||_-_-_|| || || || //
-- || || || || \\
-- || || \\ // \\
-- || || \\ // //
-- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-//
--
--By @ali_ghoghnoos
--@telemanager_ch
| gpl-2.0 |
npge/lua-npge | spec/algo/PrimaryHits_spec.lua | 2 | 1842 | -- lua-npge, Nucleotide PanGenome explorer (Lua module)
-- Copyright (C) 2014-2016 Boris Nagaev
-- See the LICENSE file for terms of use.
describe("npge.algo.PrimaryHits", function()
it("finds hits using blast+ combining groups of sequences",
function()
local Sequence = require 'npge.model.Sequence'
local s1 = Sequence('s1', string.rep('ATGC', 100))
local s2 = Sequence('s2', string.rep('ATGC', 100))
local s3 = Sequence('s3', string.rep('ATGC', 100))
local s4 = Sequence('s4', string.rep('ATGC', 100))
local BlockSet = require 'npge.model.BlockSet'
local bs_with_seqs = BlockSet({s1, s2, s3, s4}, {})
local PrimaryHits = require 'npge.algo.PrimaryHits'
local hits = PrimaryHits(bs_with_seqs)
assert.truthy(#hits:blocks() > 0)
local max_size = 0
for block in hits:iterBlocks() do
max_size = math.max(max_size, block:size())
end
assert.truthy(max_size >= 4)
end)
it("finds hits using blast+ combining groups of genomes",
function()
local Sequence = require 'npge.model.Sequence'
local s1 = Sequence('g1&c1&c', string.rep('ATGC', 100))
local s2 = Sequence('g1&c2&c', string.rep('CCAA', 100))
local s3 = Sequence('g2&c1&c', string.rep('ATGC', 100))
local s4 = Sequence('g2&c2&c', string.rep('CCAA', 100))
local BlockSet = require 'npge.model.BlockSet'
local bs_with_seqs = BlockSet({s1, s2, s3, s4}, {})
local PrimaryHits = require 'npge.algo.PrimaryHits'
local hits = PrimaryHits(bs_with_seqs)
assert.truthy(#hits:blocks() > 0)
local max_size = 0
for block in hits:iterBlocks() do
max_size = math.max(max_size, block:size())
end
assert.truthy(max_size >= 2)
end)
end)
| mit |
motangish/OpenComputers | MGOS/lib/BIMAGE.lua | 1 | 4662 | local bimage = {}
local gpu = require("BGPU")
local comp = require("computer")
local serial = require("serialization")
local fs = require("filesystem")
local unicode = require("unicode")
function bimage.getPattern(x, y, w, h, color)
local pattern = {}
pattern.w, pattern.h = w, h
for i = 1, h do
pattern[i] = {}
for d = 1, w do
local symbol, bColor, tColor = gpu.getPixel(x + d - 1, y + i - 1)
if color and bColor == color then symbol, bColor, tColor = nil, nil, nil end
pattern[i][d] = {}
pattern[i][d][1] = symbol
pattern[i][d][2] = bColor
pattern[i][d][3] = tColor
end
end
return pattern
end
function bimage.getPixelsOfPattern(x, y, w, h, patternOfPixels)
local pattern = {}
pattern.w = w
pattern.h = h
for i = 1, h do
pattern[i] = {}
for d = 1, w do
pattern[i][d] = {}
pattern[i][d][1] = patternOfPixels[y + i - 1][x + d - 1][1]
pattern[i][d][2] = patternOfPixels[y + i - 1][x + d - 1][2]
pattern[i][d][3] = patternOfPixels[y + i - 1][x + d - 1][3]
end
end
return pattern
end
function bimage.invertPattern(pattern)
for i = 1, pattern.h do
for d = 1, pattern.w do
pattern[i][d][2] = gpu.invertColor(pattern[i][d][2])
pattern[i][d][3] = gpu.invertColor(pattern[i][d][3])
end
end
return pattern
end
function bimage.setPixel(x, y, symbol, bColor, tColor, pattern)
pattern[y][x][1] = symbol
pattern[y][x][2] = bColor
pattern[y][x][3] = tColor
end
function bimage.setColors()
local color = 0xFFFFFF
for i = 1, 50 do
for d = 1, 160 do
gpu.setPixel(d, i, math.floor(color), 0xFFFFFF, " ")
color = color - 2097.151875
end
end
end
function bimage.screenshot()
if comp.freeMemory() >= 1024 then
local w, h = gpu.getResolution()
return bimage.getPattern(1, 1, w, h)
else
error("Free Memory < 1024, not enough memory.")
end
end
function bimage.compress(pattern)
local lines = {}
local num = 0
local lnum = ""
local state = true
local function check(value)
if value then return value else return " " end
end
local function set(y, x, bColor, tColor, symbol, line)
num = num + 1
lnum = check(symbol)
lines[num] = {}
lines[num][1] = y
lines[num][2] = x
lines[num][3] = lnum
lines[num][4] = bColor
lines[num][5] = tColor
state = true
end
for i = 1, pattern.h do
state = true
for d = 1, pattern.w - 1 do
if pattern[i][d][2] == pattern[i][d + 1][2] and pattern[i][d][3] == pattern[i][d + 1][3] then
if state then
set(i, d, pattern[i][d][2], pattern[i][d][3], pattern[i][d][1], true)
end
lnum = lnum .. check(pattern[i][d + 1][1])
lines[num][3] = lnum
state = false
else
if d + 2 <= pattern.w - 1 then
if pattern[i][d + 1][2] == pattern[i][d + 2][2] and pattern[i][d + 1][3] == pattern[i][d + 2][3] then
if d > 1 then
if pattern[i][d - 1][2] == pattern[i][d][2] and pattern[i][d - 1][3] == pattern[i][d][3] then
state = true
else
set(i, d, pattern[i][d][2], pattern[i][d][3], pattern[i][d][1])
end
else
set(i, d, pattern[i][d][2], pattern[i][d][3], pattern[i][d][1])
end
else
if d > 1 then
if pattern[i][d - 1][2] == pattern[i][d][2] and pattern[i][d - 1][3] == pattern[i][d][3] then
state = true
else
set(i, d, pattern[i][d][2], pattern[i][d][3], pattern[i][d][1])
end
else
set(i, d, pattern[i][d][2], pattern[i][d][3], pattern[i][d][1])
end
end
else
set(i, d, pattern[i][d][2], pattern[i][d][3], pattern[i][d][1])
set(i, d + 1, pattern[i][d + 1][2], pattern[i][d + 1][3], pattern[i][d + 1][1])
end
end
end
end
return lines
end
function bimage.open(fileName)
if fs.exists(fileName) then
local f = io.open(fileName, "r")
local result = serial.unserialize(f:read("*a"))
f:close()
return result
end
result = nil
end
function bimage.save(fileName, pattern)
if fs.exists(fileName) then fs.remove(fileName) end
local f = io.open(fileName, "w")
f:write(serial.serialize(pattern))
f:close()
end
function bimage.draw(x, y, pattern)
for num, data in pairs(bimage.compress(pattern)) do
if data[4] then
gpu.setBackground(data[4])
if data[5] then gpu.setForeground(data[5]) end
gpu.set(x + data[2] - 1, y + data[1] - 1, data[3])
end
end
pattern = nil
end
return bimage
| gpl-3.0 |
lipengyu/lsyncd | tests/l4rsyncdata.lua | 17 | 1554 | #!/usr/bin/lua
require("posix")
dofile("tests/testlib.lua")
cwriteln("****************************************************************")
cwriteln(" Testing layer 4 default rsync with simulated data activity ")
cwriteln("****************************************************************")
local tdir, srcdir, trgdir = mktemps()
local logfile = tdir .. "log"
local range = 5
local log = {"-log", "all"}
posix.mkdir(srcdir .. "d")
posix.mkdir(srcdir .. "d/e")
if not writefile(srcdir .. "d/e/f1", 'test') then
os.exit(1)
end
cwriteln("starting Lsyncd")
logs = {}
local pid = spawn("./lsyncd", "-logfile", logfile, "-nodaemon", "-delay", "5",
"-rsync", srcdir, trgdir, unpack(logs))
cwriteln("waiting for lsyncd to start")
posix.sleep(2)
cwriteln("* making some data")
cwriteln("* creating d[x]/e/f2")
for i = 1, range do
cwriteln("[cp -r "..srcdir.."d "..srcdir.."d"..i.."]")
os.execute("cp -r "..srcdir.."d "..srcdir.."d"..i)
end
-- mkdir -p "$S"/m/n
-- echo 'test3' > "$S"/m/n/file
-- for i in $RANGE; do
-- cp -r "$S"/m "$S"/m$i
-- echo 'test4' > "$S"/m${i}/n/another
-- done
cwriteln("* waiting for Lsyncd to do its job.")
posix.sleep(10)
cwriteln("* killing Lsyncd")
posix.kill(pid)
local _, exitmsg, lexitcode = posix.wait(lpid)
cwriteln("Exitcode of Lsyncd = ", exitmsg, " ", lexitcode)
posix.sleep(1)
cwriteln("* differences:")
exitcode = os.execute("diff -urN "..srcdir.." "..trgdir)
cwriteln("Exitcode of diff = '", exitcode, "'")
if exitcode ~= 0 then
os.exit(1)
else
os.exit(0)
end
-- TODO remove temp
| gpl-2.0 |
halmani/Lua | scripts/douguya.lua | 1 | 2302 | -- 店員タイプごとの会話データ
talk_data = {
-- 店員
default = {
welcome = "いらっしゃいませ!道具屋「ルア」へようこそ!",
select = "何にするかい?",
error = "え?何だって?",
nomoney = "%s だね。でもお金が %d円足りないみたいだね。" ..
"またおいで\n",
success = "%s だね。じゃあ %d円いただくよ。\n",
bye = "またいらっしゃい!",
},
-- 女性店員
woman = {
welcome = "こんにちわ!道具屋「ルア」へようこそ!",
select = "何にいたしますか?",
error = "え?何でしょう?",
nomoney = "%s ですね。でもお金が %d円足りないみたいです。" ..
"またいらしてください\n",
success = "%s ですね。それでは %d円いただきます。\n",
bye = "またどうぞ!",
}
}
-- お店のやり取りを行う
function Shop()
print("--------------------------------------------")
-- ランダムで店員を選択
local person = "default"
math.randomseed(os.time())
local rand = math.random()
if rand < 0.5 then
person = "woman"
end
local talk = talk_data[person]
-- お店のやり取りを始める
print(talk.welcome)
while true do
print(talk.select);
local money = GetMoney();
print(string.format("所持金:%d円", money))
-- 商品リスト表示
for i = 0, MAX_SHOP_ITEMS-1 do
local name = GetItemName(i);
local price = GetItemPrice(i);
if price ~= -1 then
print(string.format("%2d. %-10s, %6d円", i+1, name, price))
end
end
print(" 0, 帰る")
local num = GetSelection("どうする?")
if (num == 0) then
break
end
local is_success = false
local name, price
if num < 0 or num > MAX_SHOP_ITEMS or GetItemPrice(num -1) == -1 then
print (talk.error)
else
-- 選択したアイテムの情報
local index = num -1
name = GetItemName(index);
price = GetItemPrice(index);
-- 所持金チェック
if money < price then
print(string.format(talk.nomoney, name, price - money))
else
is_success = true
end
end
if is_success then
-- 購入成功!
print(string.format(talk.success, name, price))
SetMoney(money - price)
end
end
print(talk.bye)
print("--------------------------------------------")
end
| apache-2.0 |
notcake/gooey | lua/gooey/ui/controls/gcomboboxitem.lua | 1 | 3640 | local self = {}
Gooey.ComboBoxItem = Gooey.MakeConstructor (self)
--[[
Events:
Deselected ()
Fired when this item has been deselected.
EnabledChanged (enabled)
Fired when this item has been enabled or disabled.
IconChanged (string icon)
Fired when this item's icon has changed.
Selected ()
Fired when this item has been selected.
TextChanged (string text)
Fired when this item's text has changed.
VisibleChanged (bool visible)
Fired when this item's visibility has changed.
]]
function self:ctor (comboBox, id, text)
-- Identity
self.ComboBox = comboBox
self.Id = id
-- Appearance
self.Enabled = true
self.Visible = true
self.Text = text
self.Icon = nil
-- Menu item
self.MenuItem = nil
Gooey.EventProvider (self)
self:AddEventListener ("Deselected",
function ()
if not self.MenuItem then return end
self.MenuItem:SetChecked (false)
end
)
self:AddEventListener ("Selected",
function ()
if not self.MenuItem then return end
self.MenuItem:SetChecked (true)
end
)
end
-- Identity
function self:GetComboBox ()
return self.ComboBox
end
function self:GetId ()
return self.Id or self:GetHashCode ()
end
function self:SetId (id)
self.Id = id
end
-- Appearance
function self:GetIcon ()
return self.Icon
end
function self:GetText ()
return self.Text
end
function self:IsEnabled ()
return self.Enabled
end
function self:IsVisible ()
return self.Visible
end
function self:SetIcon (icon)
if self.Icon == icon then return self end
self.Icon = icon
if self.MenuItem then
self.MenuItem:SetIcon (self.Icon)
end
self:DispatchEvent ("IconChanged", self.Icon)
return self
end
function self:SetText (text)
if self.Text == text then return self end
self.Text = text
if self.MenuItem then
self.MenuItem:SetText (self.Text)
end
self:DispatchEvent ("TextChanged", text)
return self
end
function self:SetEnabled (enabled)
if self.Enabled == enabled then return self end
self.Enabled = enabled
if self.MenuItem then
self.MenuItem:SetEnabled (self.Enabled)
end
self:DispatchEvent ("EnabledChanged", enabled)
return self
end
function self:SetVisible (visible)
if self.Visible == visible then return self end
self.Visible = visible
if self.MenuItem then
self.MenuItem:SetVisible (self.Visible)
end
self:DispatchEvent ("VisibleChanged", visible)
return self
end
-- State
function self:IsSelected ()
return self == self.ComboBox:GetSelectedItem ()
end
function self:Select ()
self.ComboBox:SetSelectedItem (self)
end
-- Menu item
function self:GetMenuItem ()
return self.MenuItem
end
function self:SetMenuItem (menuItem)
if self.MenuItem == menuItem then return self end
self:UnhookMenuItem (self.MenuItem)
self.MenuItem = menuItem
self:HookMenuItem (self.MenuItem)
if self.MenuItem then
self.MenuItem:SetEnabled (self:IsEnabled ())
self.MenuItem:SetVisible (self:IsVisible ())
self.MenuItem:SetText (self:GetText ())
self.MenuItem:SetChecked (self:IsSelected ())
end
return self
end
-- Internal, do not call
function self:HookMenuItem (menuItem)
if not menuItem then return end
menuItem:AddEventListener ("Click", "Gooey.ComboBoxItem." .. self:GetHashCode (),
function ()
self:Select ()
end
)
end
function self:UnhookMenuItem (menuItem)
if not menuItem then return end
menuItem:RemoveEventListener ("Click", "Gooey.ComboBoxItem." .. self:GetHashCode ())
end | gpl-3.0 |
oregamikiller/cocos2dPod | cocos/scripting/lua-bindings/auto/api/UserDefault.lua | 9 | 4601 |
--------------------------------
-- @module UserDefault
-- @parent_module cc
--------------------------------
-- Set integer value by key.<br>
-- param key The key to set.<br>
-- param value A integer value to set to the key.<br>
-- js NA
-- @function [parent=#UserDefault] setIntegerForKey
-- @param self
-- @param #char key
-- @param #int value
-- @return UserDefault#UserDefault self (return value: cc.UserDefault)
--------------------------------
-- delete any value by key,<br>
-- param key The key to delete value.<br>
-- js NA
-- @function [parent=#UserDefault] deleteValueForKey
-- @param self
-- @param #char key
-- @return UserDefault#UserDefault self (return value: cc.UserDefault)
--------------------------------
-- @overload self, char, float
-- @overload self, char
-- @function [parent=#UserDefault] getFloatForKey
-- @param self
-- @param #char key
-- @param #float defaultValue
-- @return float#float ret (return value: float)
--------------------------------
-- @overload self, char, bool
-- @overload self, char
-- @function [parent=#UserDefault] getBoolForKey
-- @param self
-- @param #char key
-- @param #bool defaultValue
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Set double value by key.<br>
-- param key The key to set.<br>
-- param value A double value to set to the key.<br>
-- js NA
-- @function [parent=#UserDefault] setDoubleForKey
-- @param self
-- @param #char key
-- @param #double value
-- @return UserDefault#UserDefault self (return value: cc.UserDefault)
--------------------------------
-- Set float value by key.<br>
-- param key The key to set.<br>
-- param value A float value to set to the key.<br>
-- js NA
-- @function [parent=#UserDefault] setFloatForKey
-- @param self
-- @param #char key
-- @param #float value
-- @return UserDefault#UserDefault self (return value: cc.UserDefault)
--------------------------------
-- @overload self, char, string
-- @overload self, char
-- @function [parent=#UserDefault] getStringForKey
-- @param self
-- @param #char key
-- @param #string defaultValue
-- @return string#string ret (return value: string)
--------------------------------
-- Set string value by key.<br>
-- param key The key to set.<br>
-- param value A string value to set to the key.<br>
-- js NA
-- @function [parent=#UserDefault] setStringForKey
-- @param self
-- @param #char key
-- @param #string value
-- @return UserDefault#UserDefault self (return value: cc.UserDefault)
--------------------------------
-- You should invoke this function to save values set by setXXXForKey().<br>
-- js NA
-- @function [parent=#UserDefault] flush
-- @param self
-- @return UserDefault#UserDefault self (return value: cc.UserDefault)
--------------------------------
-- @overload self, char, int
-- @overload self, char
-- @function [parent=#UserDefault] getIntegerForKey
-- @param self
-- @param #char key
-- @param #int defaultValue
-- @return int#int ret (return value: int)
--------------------------------
-- @overload self, char, double
-- @overload self, char
-- @function [parent=#UserDefault] getDoubleForKey
-- @param self
-- @param #char key
-- @param #double defaultValue
-- @return double#double ret (return value: double)
--------------------------------
-- Set bool value by key.<br>
-- param key The key to set.<br>
-- param value A bool value to set to the key.<br>
-- js NA
-- @function [parent=#UserDefault] setBoolForKey
-- @param self
-- @param #char key
-- @param #bool value
-- @return UserDefault#UserDefault self (return value: cc.UserDefault)
--------------------------------
-- js NA
-- @function [parent=#UserDefault] destroyInstance
-- @param self
-- @return UserDefault#UserDefault self (return value: cc.UserDefault)
--------------------------------
-- All supported platforms other iOS & Android use xml file to save values. This function is return the file path of the xml path.<br>
-- js NA
-- @function [parent=#UserDefault] getXMLFilePath
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- All supported platforms other iOS & Android and CC_PLATFORM_WINRT use xml file to save values. This function checks whether the xml file exists or not.<br>
-- return True if the xml file exists, false if not.<br>
-- js NA
-- @function [parent=#UserDefault] isXMLFileExist
-- @param self
-- @return bool#bool ret (return value: bool)
return nil
| mit |
PurgePJ/VouchBot | deps/discordia/utils/Deque.lua | 3 | 1978 | local Deque, property, method = class('Deque')
Deque.__description = "Implementation of a double-ended queue."
function Deque:__init()
self._objects = {}
self._first = 0
self._last = -1
end
local function getCount(self)
return self._last - self._first + 1
end
local function pushLeft(self, obj)
self._first = self._first - 1
self._objects[self._first] = obj
end
local function pushRight(self, obj)
self._last = self._last + 1
self._objects[self._last] = obj
end
local function popLeft(self)
if self._first > self._last then return nil end
local obj = self._objects[self._first]
self._objects[self._first] = nil
self._first = self._first + 1
return obj
end
local function popRight(self)
if self._first > self._last then return nil end
local obj = self._objects[self._last]
self._objects[self._last] = nil
self._last = self._last - 1
return obj
end
local function peekLeft(self)
return self._objects[self._first]
end
local function peekRight(self)
return self._objects[self._last]
end
local function iter(self)
local t = self._objects
local i, n = self._first, self._last
return function()
if i > n then return end
local v = t[i]; i = i + 1
return v
end
end
property('count', getCount, nil, 'number', "How many objects are in the deque")
method('pushLeft', pushLeft, 'obj', "Push an object to the left side of the deque.")
method('pushRight', pushRight, 'obj', "Push an object to the right side of the deque.")
method('popLeft', popLeft, nil, "Pop an object from the left side of the deque and return it.")
method('popRight', popRight, nil, "Pop and object from the right side of the deque and return it.")
method('peekLeft', peekLeft, nil, "Returns the object at the left side of the deque, but does not pop it.")
method('peekRight', peekRight, nil, "Returns the object at the right side of the deque, but does not pop it.")
method('iter', iter, nil, "Returns an iterator for the objects in the deque, from left to right.")
return Deque
| gpl-3.0 |
thejonwong/huginenfuse | huginenfuse.lrplugin/helper.lua | 1 | 3643 | --[[----------------------------------------------------------------------------
Copyright (c) 2015, Jonathan Wong
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------]]
--- Helper Functions
local LrDialogs = import 'LrDialogs'
local LrFileUtils = import 'LrFileUtils'
-- check if the folder exists already - if it does suggest an alternate
function checkResultingFolder (HuginEnfuseOptions, value, fromModel)
local suggestedPath = string.format("%s%s",
HuginEnfuseOptions.parentFolder,value)
if LrFileUtils.exists(suggestedPath) then
--[[ check if path exists
-if it does, create a yes-no-dialog to ask if the person wants to keep the same name
or create a new folder
-if no, use uniquePath to propose one ]]
local result = LrDialogs.confirm(string.format("The path %s already exists. Do you want to build this panorama in the same location?", suggestedPath),
"Alternatively, you can select to have an auto-generated unique path by selecting \"Generate Unique\"",
"Yes",
"No",
"Generate Unique")
if result == "ok" then
return value
elseif result == "cancel" then
return ""
else
local uniquePath = LrFileUtils.chooseUniqueFileName(suggestedPath)
local uniqueFolder = uniquePath:sub(string.find(uniquePath, "\\[^\\]*$")+1)
return uniqueFolder
end
else
return value
end
end
-- check for folder - if it doesn't exist produce an error
function checkForProjectFolder (HuginEnfuseOptions, value, fromModel)
local suggestedPath = string.format("%s%s",
HuginEnfuseOptions.parentFolder,value)
if LrFileUtils.exists(suggestedPath) then
return value
else
LrDialogs.message(string.format("The directory %s does not exist. Please set the prefix name pointing to the subfolder properly",
suggestedPath))
return ""
end
end
-- helper function to generate shell commands
function execString(HuginEnfuseOptions, Path, executable, options)
return string.format("\"%s%s%s%s\" %s", Path, HuginEnfuseOptions.dirSeparator, executable, HuginEnfuseOptions.exe, options)
end
function constructPath(HuginEnfuseOptions, Path, file)
return string.format("%s%s%s", Path, HuginEnfuseOptions.dirSeparator, file)
end | bsd-3-clause |
holyscroll/holyscroll | plugins/lock_sticker.lua | 1 | 19839 | -- data saved to data/moderation.json
do
local administrators_only = 'For administrator only!'
local moderators_only = 'For moderators only!'
local function create_group(msg)
if not is_admin(msg) then return administrators_only end
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.'
end
local function addgroup(msg)
if not is_admin(msg) then return administrators_only end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
moderators ={},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_bots = 'no',
lock_name = 'no',
lock_photo = 'no',
lock_member = 'no',
anti_flood = 'no',
welcome = 'no',
sticker = 'ok'
}
}
save_data(_config.moderation.data, data)
return 'Group has been added.'
end
local function remgroup(msg)
if not is_admin(msg) then return administrators_only end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return 'Group has been removed'
end
local function export_chat_link_callback(extra, success, result)
local msg = extra.msg
local group_name = msg.to.title
local data = extra.data
local receiver = get_receiver(msg)
if success == 0 then
return send_large_msg(receiver, 'Cannot generate invite link for this group.\nMake sure you are an admin or a sudoer.')
end
data[tostring(msg.to.id)]['link'] = result
save_data(_config.moderation.data, data)
return send_large_msg(receiver,'Newest generated invite link for '..group_name..' is:\n'..result)
end
local function set_description(msg, data)
if not is_mod(msg) then return moderators_only end
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = deskripsi
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..deskripsi
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
return string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
end
local function set_rules(msg, data)
if not is_mod(msg) then return moderators_only end
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules
return rules
end
-- dis/allow APIs bots to enter group. Spam prevention.
local function allow_api_bots(msg, data)
if not is_mod(msg) then return moderators_only end
local group_bot_lock = data[tostring(msg.to.id)]['settings']['lock_bots']
if group_bot_lock == 'no' then
return 'Bots are allowed to enter group.'
else
data[tostring(msg.to.id)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is open for bots.'
end
end
local function disallow_api_bots(msg, data)
if not is_mod(msg) then return moderators_only end
local group_bot_lock = data[tostring(msg.to.id)]['settings']['lock_bots']
if group_bot_lock == 'yes' then
return 'Group is already locked from bots.'
else
data[tostring(msg.to.id)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group is locked from bots.'
end
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data)
if not is_mod(msg) then return moderators_only end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data)
if not is_mod(msg) then return moderators_only end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data)
if not is_mod(msg) then return moderators_only end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data)
if not is_mod(msg) then return moderators_only end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data)
if not is_mod(msg) then return moderators_only end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data)
if not is_mod(msg) then return moderators_only end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-- show group settings
local function show_group_settings(msg, data)
if not is_mod(msg) then return moderators_only end
local settings = data[tostring(msg.to.id)]['settings']
if settings.lock_bots == 'yes' then
lock_bots_state = 'ًں”’'
elseif settings.lock_bots == 'no' then
lock_bots_state = 'ًں”“'
end
if settings.lock_name == 'yes' then
lock_name_state = 'ًں”’'
elseif settings.lock_name == 'no' then
lock_name_state = 'ًں”“'
end
if settings.lock_photo == 'yes' then
lock_photo_state = 'ًں”’'
elseif settings.lock_photo == 'no' then
lock_photo_state = 'ًں”“'
end
if settings.lock_member == 'yes' then
lock_member_state = 'ًں”’'
elseif settings.lock_member == 'no' then
lock_member_state = 'ًں”“'
end
if settings.anti_flood ~= 'no' then
antiflood_state = 'ًں”’'
elseif settings.anti_flood == 'no' then
antiflood_state = 'ًں”“'
end
if settings.welcome ~= 'no' then
greeting_state = 'ًں”’'
elseif settings.welcome == 'no' then
greeting_state = 'ًں”“'
end
if settings.sticker ~= 'ok' then
sticker_state = 'ًں”’'
elseif settings.sticker == 'ok' then
sticker_state = 'ًں”“'
end
local text = 'Group settings:\n'
..'\n'..lock_bots_state..' Lock group from bot : '..settings.lock_bots
..'\n'..lock_name_state..' Lock group name : '..settings.lock_name
..'\n'..lock_photo_state..' Lock group photo : '..settings.lock_photo
..'\n'..lock_member_state..' Lock group member : '..settings.lock_member
..'\n'..antiflood_state..' Flood protection : '..settings.anti_flood
..'\n'..greeting_state..' Welcome message : '..settings.welcome
..'\n'..sticker_state..' Sticker policy : '..settings.sticker
return text
end
-- media handler. needed by group_photo_lock
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
function run(msg, matches)
if not is_chat_msg(msg) then
return "This is not a group chat."
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
-- create a group
if matches[1] == 'mkgroup' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
-- add a group to be moderated
if matches[1] == 'addgroup' then
return addgroup(msg)
end
-- remove group from moderation
if matches[1] == 'remgroup' then
return remgroup(msg)
end
if msg.media and is_chat_msg(msg) and is_momod(msg) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'setabout' and matches[2] then
deskripsi = matches[2]
return set_description(msg, data)
end
if matches[1] == 'about' then
return get_description(msg, data)
end
if matches[1] == 'setrules' then
rules = matches[2]
return set_rules(msg, data)
end
if matches[1] == 'rules' then
return get_rules(msg, data)
end
-- group link {get|set}
if matches[1] == 'link' then
if matches[2] == 'get' then
if data[tostring(msg.to.id)]['link'] then
local about = get_description(msg, data)
local link = data[tostring(msg.to.id)]['link']
return about.."\n\n"..link
else
return 'Invite link does not exist.\nTry !link set to generate it.'
end
end
if matches[2] == 'set' and is_mod(msg) then
msgr = export_chat_link(receiver, export_chat_link_callback, {data=data, msg=msg})
end
end
if matches[1] == 'group' then
-- lock {bot|name|member|photo|sticker}
if matches[2] == 'lock' then
if matches[3] == 'bot' then
return disallow_api_bots(msg, data)
end
if matches[3] == 'name' then
return lock_group_name(msg, data)
end
if matches[3] == 'member' then
return lock_group_member(msg, data)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data)
end
-- unlock {bot|name|member|photo|sticker}
elseif matches[2] == 'unlock' then
if matches[3] == 'bot' then
return allow_api_bots(msg, data)
end
if matches[3] == 'name' then
return unlock_group_name(msg, data)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data)
end
-- view group settings
elseif matches[2] == 'settings' then
return show_group_settings(msg, data)
end
end
if matches[1] == 'sticker' then
if matches[2] == 'warn' then
if is_momod(msg) then
if welcome_stat ~= 'warn' then
data[tostring(msg.to.id)]['settings']['sticker'] = 'warn'
save_data(_config.moderation.data, data)
end
return 'فعال شد\nدر صورت ارسال استیکر،ابتدا اخطار داده شده\nدر صورت ارسال مجدد از گروه حذف خواهد شد'
end
end
if matches[2] == 'kick' then
if is_momod(msg) then
if welcome_stat ~= 'kick' then
data[tostring(msg.to.id)]['settings']['sticker'] = 'kick'
save_data(_config.moderation.data, data)
end
return 'فعال شد!\nدر صورت ارسال استیکر،فرد ارسال کننده حذف خواهد شد'
end
end
if matches[2] == 'ok' then
if is_momod(msg) then
if welcome_stat == 'ok' then
return 'قفل استیکر غیرفعال شد'
else
data[tostring(msg.to.id)]['settings']['sticker'] = 'ok'
save_data(_config.moderation.data, data)
return 'قفل استیکر غیر فعال میباشد '
end
end
end
end
-- if group name is renamed
if matches[1] == 'chat_rename' then
if not msg.service then
return 'Are you trying to troll me?'
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
-- set group name
if matches[1] == 'setname' and is_mod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
end
-- set group photo
if matches[1] == 'setphoto' and is_mod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
-- if a user is added to group
if matches[1] == 'chat_add_user' then
if not msg.service then
return 'Are you trying to troll me?'
end
local group_member_lock = settings.lock_member
local group_bot_lock = settings.lock_bots
local user = 'user#id'..msg.action.user.id
if group_member_lock == 'yes' then
chat_del_user(receiver, user, ok_cb, true)
-- no APIs bot are allowed to enter chat group.
elseif group_bot_lock == 'yes' and msg.action.user.flags == 4352 then
chat_del_user(receiver, user, ok_cb, true)
elseif group_bot_lock == 'no' or group_member_lock == 'no' then
return nil
end
end
-- if sticker is sent
if msg.media and msg.media.caption == 'sticker.webp' and not is_momod(msg) then
local user_id = msg.from.id
local chat_id = msg.to.id
local sticker_hash = 'mer_sticker:'..chat_id..':'..user_id
local is_sticker_offender = redis:get(sticker_hash)
if settings.sticker == 'warn' then
if is_sticker_offender then
chat_del_user(receiver, 'user#id'..user_id, ok_cb, true)
redis:del(sticker_hash)
return 'به دلیل ارسال استیکر از ادامه چت محروم میشوید'
elseif not is_sticker_offender then
redis:set(sticker_hash, true)
return ' استیکر ارسال نکنید!\nاین یک اخطار میباشد\n\nدر صورت رعایت نکردن از گروه حذف خواهید شد'
end
elseif settings.sticker == 'kick' then
chat_del_user(receiver, 'user#id'..user_id, ok_cb, true)
return 'به دلیل استفاده از استیکر از گروه حذف میشوید'
elseif settings.sticker == 'ok' then
return nil
end
end
-- if group photo is deleted
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return 'Are you trying to troll me?'
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
-- if group photo is changed
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return 'Are you trying to troll me?'
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
end
end
return {
description = 'Plugin to manage group chat.',
usage = {
admin = {
'!mkgroup <group_name> : Make/create a new group.',
'!addgroup : Add group to moderation list.',
'!remgroup : Remove group from moderation list.'
},
moderator = {
'!group <lock|unlock> bot : {Dis}allow APIs bots.',
'!group <lock|unlock> member : Lock/unlock group member.',
'!group <lock|unlock> name : Lock/unlock group name.',
'!group <lock|unlock> photo : Lock/unlock group photo.',
'!group settings : Show group settings.',
'!link <set> : Generate/revoke invite link.',
'!setabout <description> : Set group description.',
'!setname <new_name> : Set group name.',
'!setphoto : Set group photo.',
'!setrules <rules> : Set group rules.',
'!sticker warn : Sticker restriction, sender will be warned for the first violation.',
'!sticker kick : Sticker restriction, sender will be kick.',
'!sticker ok : Disable sticker restriction.'
},
user = {
'!about : Read group description',
'!rules : Read group rules',
'!link <get> : Print invite link'
},
},
patterns = {
--"^!(about)$",
--"^!(addgroup)$",
"%[(audio)%]",
"%[(document)%]",
--"^!(group) (lock) (.*)$",
--"^!(group) (settings)$",
--"^!(group) (unlock) (.*)$",
--"^!(link) (.*)$",
--"^!(mkgroup) (.*)$",
--"%[(photo)%]",
--"^!(remgroup)$",
--"^!(rules)$",
-- "^!(setabout) (.*)$",
-- "^!(setname) (.*)$",
--"^!(setphoto)$",
--"^!(setrules) (.*)$",
"^[!/](sticker) (.*)$",
"^!!tgservice (.+)$",
"%[(video)%]"
},
run = run,
pre_process = pre_process
}
end
--dg entezare bishtar azin nadashte bashid :|
--namosan hal nadaram baqiasho hazf konam :|
--hamino estefade konid okeye moshkeli nadare :|
--negarane speed plug ham nabashid chon pattern ha bastas,okeye ;)
| gpl-2.0 |
icebreaker/premake-dev | tests/actions/codelite/codelite_files.lua | 8 | 1140 | --
-- tests/actions/codelite/codelite_files.lua
-- Validate generation of files block in CodeLite C/C++ projects.
-- Copyright (c) 2011 Jason Perkins and the Premake project
--
T.codelite_files = { }
local suite = T.codelite_files
local codelite = premake.codelite
--
-- Setup
--
local sln, prj
function suite.setup()
sln = test.createsolution()
end
local function prepare()
io.indent = " "
premake.bake.buildconfigs()
prj = premake.solution.getproject(sln, 1)
codelite.files(prj)
end
--
-- Test grouping and nesting
--
function suite.SimpleSourceFile()
files { "hello.c" }
prepare()
test.capture [[
<File Name="hello.c"/>
]]
end
function suite.SingleFolderLevel()
files { "src/hello.c" }
prepare()
test.capture [[
<VirtualDirectory Name="src">
<File Name="src/hello.c"/>
</VirtualDirectory>
]]
end
function suite.MultipleFolderLevels()
files { "src/greetings/hello.c" }
prepare()
test.capture [[
<VirtualDirectory Name="src">
<VirtualDirectory Name="greetings">
<File Name="src/greetings/hello.c"/>
</VirtualDirectory>
</VirtualDirectory>
]]
end
| bsd-3-clause |
i-z/cocos2d-x-samples | samples/KillBug/src/cocos/framework/components/event.lua | 62 | 4752 |
local Event = class("Event")
local EXPORTED_METHODS = {
"addEventListener",
"dispatchEvent",
"removeEventListener",
"removeEventListenersByTag",
"removeEventListenersByEvent",
"removeAllEventListeners",
"hasEventListener",
"dumpAllEventListeners",
}
function Event:init_()
self.target_ = nil
self.listeners_ = {}
self.nextListenerHandleIndex_ = 0
end
function Event:bind(target)
self:init_()
cc.setmethods(target, self, EXPORTED_METHODS)
self.target_ = target
end
function Event:unbind(target)
cc.unsetmethods(target, EXPORTED_METHODS)
self:init_()
end
function Event:on(eventName, listener, tag)
assert(type(eventName) == "string" and eventName ~= "",
"Event:addEventListener() - invalid eventName")
eventName = string.upper(eventName)
if self.listeners_[eventName] == nil then
self.listeners_[eventName] = {}
end
self.nextListenerHandleIndex_ = self.nextListenerHandleIndex_ + 1
local handle = tostring(self.nextListenerHandleIndex_)
tag = tag or ""
self.listeners_[eventName][handle] = {listener, tag}
if DEBUG > 1 then
printInfo("%s [Event] addEventListener() - event: %s, handle: %s, tag: \"%s\"",
tostring(self.target_), eventName, handle, tostring(tag))
end
return self.target_, handle
end
Event.addEventListener = Event.on
function Event:dispatchEvent(event)
event.name = string.upper(tostring(event.name))
local eventName = event.name
if DEBUG > 1 then
printInfo("%s [Event] dispatchEvent() - event %s", tostring(self.target_), eventName)
end
if self.listeners_[eventName] == nil then return end
event.target = self.target_
event.stop_ = false
event.stop = function(self)
self.stop_ = true
end
for handle, listener in pairs(self.listeners_[eventName]) do
if DEBUG > 1 then
printInfo("%s [Event] dispatchEvent() - dispatching event %s to listener %s", tostring(self.target_), eventName, handle)
end
-- listener[1] = listener
-- listener[2] = tag
event.tag = listener[2]
listener[1](event)
if event.stop_ then
if DEBUG > 1 then
printInfo("%s [Event] dispatchEvent() - break dispatching for event %s", tostring(self.target_), eventName)
end
break
end
end
return self.target_
end
function Event:removeEventListener(handleToRemove)
for eventName, listenersForEvent in pairs(self.listeners_) do
for handle, _ in pairs(listenersForEvent) do
if handle == handleToRemove then
listenersForEvent[handle] = nil
if DEBUG > 1 then
printInfo("%s [Event] removeEventListener() - remove listener [%s] for event %s", tostring(self.target_), handle, eventName)
end
return self.target_
end
end
end
return self.target_
end
function Event:removeEventListenersByTag(tagToRemove)
for eventName, listenersForEvent in pairs(self.listeners_) do
for handle, listener in pairs(listenersForEvent) do
-- listener[1] = listener
-- listener[2] = tag
if listener[2] == tagToRemove then
listenersForEvent[handle] = nil
if DEBUG > 1 then
printInfo("%s [Event] removeEventListener() - remove listener [%s] for event %s", tostring(self.target_), handle, eventName)
end
end
end
end
return self.target_
end
function Event:removeEventListenersByEvent(eventName)
self.listeners_[string.upper(eventName)] = nil
if DEBUG > 1 then
printInfo("%s [Event] removeAllEventListenersForEvent() - remove all listeners for event %s", tostring(self.target_), eventName)
end
return self.target_
end
function Event:removeAllEventListeners()
self.listeners_ = {}
if DEBUG > 1 then
printInfo("%s [Event] removeAllEventListeners() - remove all listeners", tostring(self.target_))
end
return self.target_
end
function Event:hasEventListener(eventName)
eventName = string.upper(tostring(eventName))
local t = self.listeners_[eventName]
for _, __ in pairs(t) do
return true
end
return false
end
function Event:dumpAllEventListeners()
print("---- Event:dumpAllEventListeners() ----")
for name, listeners in pairs(self.listeners_) do
printf("-- event: %s", name)
for handle, listener in pairs(listeners) do
printf("-- listener: %s, handle: %s", tostring(listener[1]), tostring(handle))
end
end
return self.target_
end
return Event
| mit |
tahashakiba/boomrange_bot | plugins/quotes.lua | 651 | 1630 | local quotes_file = './data/quotes.lua'
local quotes_table
function read_quotes_file()
local f = io.open(quotes_file, "r+")
if f == nil then
print ('Created a new quotes file on '..quotes_file)
serialize_to_file({}, quotes_file)
else
print ('Quotes loaded: '..quotes_file)
f:close()
end
return loadfile (quotes_file)()
end
function save_quote(msg)
local to_id = tostring(msg.to.id)
if msg.text:sub(11):isempty() then
return "Usage: !addquote quote"
end
if quotes_table == nil then
quotes_table = {}
end
if quotes_table[to_id] == nil then
print ('New quote key to_id: '..to_id)
quotes_table[to_id] = {}
end
local quotes = quotes_table[to_id]
quotes[#quotes+1] = msg.text:sub(11)
serialize_to_file(quotes_table, quotes_file)
return "done!"
end
function get_quote(msg)
local to_id = tostring(msg.to.id)
local quotes_phrases
quotes_table = read_quotes_file()
quotes_phrases = quotes_table[to_id]
return quotes_phrases[math.random(1,#quotes_phrases)]
end
function run(msg, matches)
if string.match(msg.text, "!quote$") then
return get_quote(msg)
elseif string.match(msg.text, "!addquote (.+)$") then
quotes_table = read_quotes_file()
return save_quote(msg)
end
end
return {
description = "Save quote",
description = "Quote plugin, you can create and retrieve random quotes",
usage = {
"!addquote [msg]",
"!quote",
},
patterns = {
"^!addquote (.+)$",
"^!quote$",
},
run = run
}
| gpl-2.0 |
szagoruyko/gtsrb.torch | Optim.lua | 4 | 8042 | --[[ That would be the license for Optim.lua
BSD License
For fbcunn software
Copyright (c) 2014, Facebook, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name Facebook nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]
-- Copyright 2004-present Facebook. All Rights Reserved.
local pl = require('pl.import_into')()
-- from fblualib/fb/util/data.lua , copied here because fblualib is not rockspec ready yet.
-- deepcopy routine that assumes the presence of a 'clone' method in user
-- data should be used to deeply copy. This matches the behavior of Torch
-- tensors.
local function deepcopy(x)
local typename = type(x)
if typename == "userdata" then
return x:clone()
end
if typename == "table" then
local retval = { }
for k,v in pairs(x) do
retval[deepcopy(k)] = deepcopy(v)
end
return retval
end
return x
end
local Optim, parent = torch.class('nn.Optim')
-- Returns weight parameters and bias parameters and associated grad parameters
-- for this module. Annotates the return values with flag marking parameter set
-- as bias parameters set
function Optim.weight_bias_parameters(module)
local weight_params, bias_params
if module.weight then
weight_params = {module.weight, module.gradWeight}
weight_params.is_bias = false
end
if module.bias then
bias_params = {module.bias, module.gradBias}
bias_params.is_bias = true
end
return {weight_params, bias_params}
end
-- The regular `optim` package relies on `getParameters`, which is a
-- beastly abomination before all. This `optim` package uses separate
-- optim state for each submodule of a `nn.Module`.
function Optim:__init(model, optState, checkpoint_data)
assert(model)
assert(checkpoint_data or optState)
assert(not (checkpoint_data and optState))
self.model = model
self.modulesToOptState = {}
-- Keep this around so we update it in setParameters
self.originalOptState = optState
-- Each module has some set of parameters and grad parameters. Since
-- they may be allocated discontinuously, we need separate optState for
-- each parameter tensor. self.modulesToOptState maps each module to
-- a lua table of optState clones.
if not checkpoint_data then
self.model:apply(function(module)
self.modulesToOptState[module] = { }
local params = self.weight_bias_parameters(module)
-- expects either an empty table or 2 element table, one for weights
-- and one for biases
assert(pl.tablex.size(params) == 0 or pl.tablex.size(params) == 2)
for i, _ in ipairs(params) do
self.modulesToOptState[module][i] = deepcopy(optState)
if params[i] and params[i].is_bias then
-- never regularize biases
self.modulesToOptState[module][i].weightDecay = 0.0
end
end
assert(module)
assert(self.modulesToOptState[module])
end)
else
local state = checkpoint_data.optim_state
local modules = {}
self.model:apply(function(m) table.insert(modules, m) end)
assert(pl.tablex.compare_no_order(modules, pl.tablex.keys(state)))
self.modulesToOptState = state
end
end
function Optim:save()
return {
optim_state = self.modulesToOptState
}
end
local function _type_all(obj, t)
for k, v in pairs(obj) do
if type(v) == 'table' then
_type_all(v, t)
else
local tn = torch.typename(v)
if tn and tn:find('torch%..+Tensor') then
obj[k] = v:type(t)
end
end
end
end
function Optim:type(t)
self.model:apply(function(module)
local state= self.modulesToOptState[module]
assert(state)
_type_all(state, t)
end)
end
local function get_device_for_module(mod)
local dev_id = nil
for name, val in pairs(mod) do
if torch.typename(val) == 'torch.CudaTensor' then
local this_dev = val:getDevice()
if this_dev ~= 0 then
-- _make sure the tensors are allocated consistently
assert(dev_id == nil or dev_id == this_dev)
dev_id = this_dev
end
end
end
return dev_id -- _may still be zero if none are allocated.
end
local function on_device_for_module(mod, f)
local this_dev = get_device_for_module(mod)
if this_dev ~= nil then
return cutorch.withDevice(this_dev, f)
end
return f()
end
function Optim:optimize(optimMethod, inputs, targets, criterion)
assert(optimMethod)
assert(inputs)
assert(targets)
assert(criterion)
assert(self.modulesToOptState)
self.model:zeroGradParameters()
local output = self.model:forward(inputs)
local err = criterion:forward(output, targets)
local df_do = criterion:backward(output, targets)
self.model:backward(inputs, df_do)
-- We'll set these in the loop that iterates over each module. Get them
-- out here to be captured.
local curGrad
local curParam
local function fEvalMod(x)
return err, curGrad
end
for curMod, opt in pairs(self.modulesToOptState) do
on_device_for_module(curMod, function()
local curModParams = self.weight_bias_parameters(curMod)
-- expects either an empty table or 2 element table, one for weights
-- and one for biases
assert(pl.tablex.size(curModParams) == 0 or
pl.tablex.size(curModParams) == 2)
if curModParams then
for i, tensor in ipairs(curModParams) do
if curModParams[i] then
-- expect param, gradParam pair
curParam, curGrad = table.unpack(curModParams[i])
assert(curParam and curGrad)
optimMethod(fEvalMod, curParam, opt[i])
end
end
end
end)
end
return err, output
end
function Optim:setParameters(newParams)
assert(newParams)
assert(type(newParams) == 'table')
local function splice(dest, src)
for k,v in pairs(src) do
dest[k] = v
end
end
splice(self.originalOptState, newParams)
for _,optStates in pairs(self.modulesToOptState) do
for i,optState in pairs(optStates) do
assert(type(optState) == 'table')
splice(optState, newParams)
end
end
end
| mit |
notcake/gooey | lua/gooey/ui/controls/gcomboboxx.lua | 1 | 4308 | local PANEL = {}
function PANEL:Init ()
self.Autocompletion = vgui.Create ("GListBox", self)
self.Autocompletion:SetMouseInputEnabled (true)
self.Autocompletion:SetMultiple (false)
self.Autocompletion:SetVisible (false)
self.Autocompletion.Think = function (comboBox)
if not self:IsValid () then
comboBox:Remove ()
return
end
if not self:IsFocused () and not self.Autocompletion:IsFocused () and not self.Autocompletion:IsHovered () and self.AutocompletionVisible then
self.Autocompletion:SetParent (self)
self.AutocompletionVisible = false
self.Autocompletion:SetVisible (false)
end
end
self.Autocompletion:AddEventListener ("ItemSelected", function (comboBox, item)
if item then
self:SetText (item:GetText ())
self:DispatchEvent ("TextChanged", self:GetText ())
end
end)
self.AutocompletionVisible = false
self.LastAutocompletedText = nil
self.LastShowable = false
self.AutocompletionCache = {}
self.Autocompleter = nil
end
function PANEL:HideAutocompletion ()
if self.AutocompletionVisible then
self.Autocompletion:SetParent (self)
self.AutocompletionVisible = false
self.Autocompletion:SetVisible (false)
end
end
function PANEL:LayoutAutocompletion ()
local x, y = self:LocalToScreen (0, self:GetTall () + 4)
local dx, dy = self.Autocompletion:GetParent ():LocalToScreen (0, 0)
x = x - dx
y = y - dy
self.Autocompletion:SetPos (x, y)
self.Autocompletion:SetSize (self:GetWide (), 256)
end
function PANEL:OnTextChanged ()
self:UpdateAutocompletion ()
self:DispatchEvent ("TextChanged", self:GetText ())
end
function PANEL:SetAutocompleter (autocompleter)
self.Autocompleter = autocompleter
-- reset caching
self.AutocompletionCache = {}
self.LastAutocompletedText = nil
end
function PANEL:ShowAutocompletion ()
if not self.AutocompletionVisible then
local topLevelParent = self:GetParent ()
while topLevelParent:GetParent ():GetParent () do
topLevelParent = topLevelParent:GetParent ()
end
self.Autocompletion:SetParent (topLevelParent)
self.AutocompletionVisible = true
self.Autocompletion:SetVisible (true)
self:LayoutAutocompletion ()
end
end
function PANEL:Think ()
if self:IsFocused () or self.Autocompletion:IsFocused () or self.Autocompletion:IsHovered () then
if not self.AutocompletionVisible then
self:UpdateAutocompletion (self.LastShowable == false)
end
self.LastShowable = true
else
if self.AutocompletionVisible then
self:HideAutocompletion ()
end
self.LastShowable = false
end
end
function PANEL:UpdateAutocompletion (forceRegeneration)
if not forceRegeneration and self:GetText () == self.LastAutocompletedText then
return
end
if self.Autocompleter == nil then
return
end
local results = nil
if self.AutocompletionCache [self:GetText ()] then
results = self.AutocompletionCache [self:GetText ()]
else
results = self.Autocompleter
if type (self.Autocompleter) == "function" then
results = self.Autocompleter (self:GetText ())
end
self.AutocompletionCache [self:GetText ()] = results
end
local show = true
if #results == 0 then
show = false
end
if #results == 1 and results [1] == self:GetText () then
show = false
end
if show then
self:ShowAutocompletion ()
-- avoid repopulating if the dropdown already has the items we want
if self.LastAutocompletedText ~= self:GetText () then
-- try to reuse controls.
-- ugly, but fast code ahead
local i = 1
local toremove = {}
local controls = self.Autocompletion.Items
for k, v in pairs (controls) do
if i > #results then
-- hide the lines we don't need
while k ~= nil do
controls [k]:SetVisible (false)
k = next (controls, k)
end
break
end
v:SetVisible (true)
v:SetText (results [i])
i = i + 1
end
-- add extra lines
while i < #results do
self.Autocompletion:AddItem (results [i])
i = i + 1
end
self.Autocompletion:InvalidateLayout ()
end
else
self:HideAutocompletion ()
end
self.LastAutocompletedText = self:GetText ()
return show
end
Gooey.Register ("GComboBoxX", PANEL, "DTextEntry") | gpl-3.0 |
opentomb/OpenTomb | scripts/entity/entity_model_id_override.lua | 2 | 5094 | -- OPENTOMB ENTITY MODEL OVERRIDE SCRIPT
-- by TeslaRus
--------------------------------------------------------------------------------
-- The purpose of this script is to replace certain in-game models with another
-- ones. This is needed for early TR versions, which had sprites instead of
-- in-level items.
--------------------------------------------------------------------------------
print("entity_model_id_override->loaded !");
--------------------------------------------------------------------------------
----------------------------- TR_I, TR_I_DEMO, TR_I_UB -------------------------
--------------------------------------------------------------------------------
tr1_id_override = {};
-- ITEMS
tr1_id_override[93] = 108; -- BIG MEDKIT
tr1_id_override[94] = 109; -- SMALL MEDKIT
-- WEAPONS
tr1_id_override[84] = 99; -- PISTOLS
tr1_id_override[85] = 100; -- SHOTGUN
tr1_id_override[86] = 101; -- DESERT EAGLES
tr1_id_override[87] = 102; -- UZI
-- AMMO
tr1_id_override[88] = 103; -- Infinite pistol ammo, never on the map (Who knows?..)
tr1_id_override[89] = 104; -- SHOTGUN
tr1_id_override[90] = 105; -- DESERT EAGLES
tr1_id_override[91] = 106; -- UZI
-- QUAES ITEMS / KEYS
tr1_id_override[141] = 145; -- MAIN ARTEFACT
tr1_id_override[142] = 146; -- MAIN ARTEFACT
tr1_id_override[143] = 150; -- MAIN ARTEFACT
tr1_id_override[144] = 150; -- MAIN ARTEFACT
tr1_id_override[110] = 114; -- keys and others
tr1_id_override[111] = 115;
tr1_id_override[112] = 116;
tr1_id_override[113] = 117;
tr1_id_override[126] = 127; --
tr1_id_override[129] = 133; --
tr1_id_override[130] = 134; --
tr1_id_override[131] = 135; --
tr1_id_override[132] = 136; --
--------------------------------------------------------------------------------
--------------------------------- TR_II, TR_II_DEMO ----------------------------
--------------------------------------------------------------------------------
tr2_id_override = {};
-- ITEMS
tr2_id_override[149] = 171; -- SMALL MEDKIT
tr2_id_override[150] = 172; -- BIG MEDKIT
tr2_id_override[151] = 173; -- FLARES
-- WEAPONS
tr2_id_override[135] = 157; -- PISTOLS
tr2_id_override[136] = 158; -- SHOTGUN
tr2_id_override[137] = 159; -- AUTOMAGS
tr2_id_override[138] = 160; -- UZI
tr2_id_override[139] = 161; -- GARPOON
tr2_id_override[140] = 162; -- M16
tr2_id_override[141] = 163; -- GRENADE GUN
-- AMMO
tr2_id_override[143] = 165; -- SHOTGUN
tr2_id_override[144] = 166; -- DESERT EAGLES
tr2_id_override[145] = 167; -- UZI
tr2_id_override[146] = 168; -- GARPOON
tr2_id_override[147] = 169; -- M16
tr2_id_override[148] = 170; -- GRENADE GUN
-- QUEST
tr2_id_override[174] = 178;
tr2_id_override[175] = 179;
tr2_id_override[176] = 180;
tr2_id_override[177] = 181;
tr2_id_override[193] = 197;
tr2_id_override[194] = 198;
tr2_id_override[195] = 199;
tr2_id_override[196] = 200;
--------------------------------------------------------------------------------
-------------------------------------- TR_III ----------------------------------
--------------------------------------------------------------------------------
tr3_id_override = {};
--------------------------------------------------------------------------------
--------------------------------- TR_IV, TR_IV_DEMO ----------------------------
--------------------------------------------------------------------------------
tr4_id_override = {};
--------------------------------------------------------------------------------
------------------------------------- TR_V -------------------------------------
--------------------------------------------------------------------------------
tr5_id_override = {};
function getOverridedID(ver, id)
if(ver < 3) then -- TR_I, TR_I_DEMO, TR_I_UB
if(tr1_id_override[id] == nil) then
return -1;
else
return tr1_id_override[id];
end;
elseif(ver < 5) then -- TR_II, TR_II_DEMO
if(tr2_id_override[id] == nil) then
return -1;
else
return tr2_id_override[id];
end;
elseif(ver < 6) then -- TR_III
if(tr3_id_override[id] == nil) then
return -1;
else
return tr3_id_override[id];
end;
elseif(ver < 8) then -- TR_IV, TR_IV_DEMO
if(tr4_id_override[id] == nil) then
return -1;
else
return tr4_id_override[id];
end;
elseif(ver < 9) then -- TR_V
if(tr5_id_override[id] == nil) then
return -1;
else
return tr5_id_override[id];
end;
else
return -1;
end;
end; | lgpl-3.0 |
u255436/CppSharp | build/scripts/Build.lua | 5 | 1685 | require "Utils"
function get_msbuild_path()
local msbuild = '%SystemRoot%\\system32\\reg.exe query "HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\4.0" /v MSBuildToolsPath'
local val = execute(msbuild)
for i in string.gmatch(val, "%S+") do
if os.isdir(i) then
return i
end
end
error("MSBuild path could not be found in Windows registry.")
end
function msbuild(sln, conf)
local msbuild_path = path.normalize(path.join(get_msbuild_path(), "msbuild.exe"))
local sln = path.normalize(sln)
local cmd = msbuild_path .. " " .. sln
if conf ~= nil then
cmd = cmd .. " /p:Configuration=" .. conf
end
execute_or_die(cmd)
end
function ninja(dir, action)
local cmd = "ninja -C " .. dir
if action then
cmd = cmd .. " " .. action
end
return execute_or_die(cmd)
end
function run_premake(file, action)
-- search for file with extension Lua
if os.isfile(file .. ".lua") then
file = file .. ".lua"
end
local cmd = string.format("%s --file=%s %s", _PREMAKE_COMMAND, file, action)
return execute_or_die(cmd)
end
function build_cppsharp()
-- install dependencies
run_premake("Provision", "provision")
-- if there is an llvm git clone then use it
-- otherwise download and extract llvm/clang build
run_premake("LLVM", "download_llvm")
-- generate project files
run_premake("../premake4", "gmake")
-- build cppsharp
--[[BUILD_CONF=release_x32;
config=$BUILD_CONF make -C build/gmake/
BUILD_DIR=`ls build/gmake/lib`
mkdir -p "$PWD"/build/gmake/lib/lib/"$BUILD_DIR"
cp "$PWD"/build/gmake/lib/"$BUILD_DIR"/libNamespacesBase.* "$PWD"/build/gmake/lib/lib/"$BUILD_DIR"
]]
end
if _ACTION == "build_cppsharp" then
build_cppsharp()
os.exit()
end
| mit |
npge/lua-npge | src/npge/alignment/init.lua | 2 | 1046 | -- lua-npge, Nucleotide PanGenome explorer (Lua module)
-- Copyright (C) 2014-2016 Boris Nagaev
-- See the LICENSE file for terms of use.
return {
left = require 'npge.alignment.left',
anchor = require 'npge.alignment.anchor',
toAtgcn = require 'npge.alignment.toAtgcn',
toAtgcnAndGap = require 'npge.alignment.toAtgcnAndGap',
unwindRow = require 'npge.alignment.unwindRow',
complement = require 'npge.alignment.complement',
complementRows = require 'npge.alignment.complementRows',
moveIdentical = require 'npge.alignment.moveIdentical',
join = require 'npge.alignment.join',
alignRows = require 'npge.alignment.alignRows',
refine = require 'npge.alignment.refine',
removePureGaps = require 'npge.alignment.removePureGaps',
identity = require 'npge.alignment.identity',
consensus = require 'npge.alignment.consensus',
goodSlices = require 'npge.alignment.goodSlices',
goodColumns = require 'npge.alignment.goodColumns',
minIdentical = require 'npge.alignment.minIdentical',
}
| mit |
dev-osrose/osIROSE-new | scripts/npcs/ai/[arumic_researcher]_catherine_clara.lua | 2 | 1069 | registerNpc(1212, {
walk_speed = 0,
run_speed = 0,
scale = 110,
r_weapon = 0,
l_weapon = 0,
level = 10,
hp = 100,
attack = 100,
hit = 100,
def = 100,
res = 100,
avoid = 100,
attack_spd = 100,
is_magic_damage = 0,
ai_type = 236,
give_exp = 0,
drop_type = 56,
drop_money = 0,
drop_item = 0,
union_number = 0,
need_summon_count = 551,
sell_tab0 = 551,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 200,
npc_type = 999,
hit_material_type = 0,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end | apache-2.0 |
josephholsten/redis | deps/lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| bsd-3-clause |
cvvergara/vrp-trash-collection | tools/osrm-work/uruguay/car-new.lua | 6 | 12954 | -- Begin of globals
--require("lib/access") --function temporarily inlined
barrier_whitelist = { ["cattle_grid"] = true, ["border_control"] = true, ["checkpoint"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["lift_gate"] = true, ["no"] = true, ["entrance"] = true }
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestry"] = true, ["emergency"] = true, ["psv"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
access_tags_hierachy = { "motorcar", "motor_vehicle", "vehicle", "access" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true }
restriction_exception_tags = { "motorcar", "motor_vehicle", "vehicle" }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 45,
["trunk"] = 85,
["trunk_link"] = 40,
["primary"] = 65,
["primary_link"] = 30,
["secondary"] = 55,
["secondary_link"] = 25,
["tertiary"] = 40,
["tertiary_link"] = 20,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["movable"] = 5,
["shuttle_train"] = 10,
["default"] = 10
}
-- surface/trackype/smoothness
-- values were estimated from looking at the photos at the relevant wiki pages
-- max speed for surfaces
surface_speeds = {
["asphalt"] = nil, -- nil mean no limit. removing the line has the same effect
["concrete"] = nil,
["concrete:plates"] = nil,
["concrete:lanes"] = nil,
["paved"] = nil,
["cement"] = 80,
["compacted"] = 80,
["fine_gravel"] = 80,
["paving_stones"] = 60,
["metal"] = 60,
["bricks"] = 60,
["grass"] = 40,
["wood"] = 40,
["sett"] = 40,
["grass_paver"] = 40,
["gravel"] = 40,
["unpaved"] = 40,
["ground"] = 40,
["dirt"] = 40,
["pebblestone"] = 40,
["tartan"] = 40,
["cobblestone"] = 30,
["clay"] = 30,
["earth"] = 20,
["stone"] = 20,
["rocky"] = 20,
["sand"] = 20,
["mud"] = 10
}
-- max speed for tracktypes
tracktype_speeds = {
["grade1"] = 60,
["grade2"] = 40,
["grade3"] = 30,
["grade4"] = 25,
["grade5"] = 20
}
-- max speed for smoothnesses
smoothness_speeds = {
["intermediate"] = 80,
["bad"] = 40,
["very_bad"] = 20,
["horrible"] = 10,
["very_horrible"] = 5,
["impassable"] = 0
}
-- http://wiki.openstreetmap.org/wiki/Speed_limits
maxspeed_table_default = {
["urban"] = 50,
["rural"] = 90,
["trunk"] = 110,
["motorway"] = 130
}
-- List only exceptions
maxspeed_table = {
["ch:rural"] = 80,
["ch:trunk"] = 100,
["ch:motorway"] = 120,
["de:living_street"] = 7,
["ru:living_street"] = 20,
["ru:urban"] = 60,
["ua:urban"] = 60,
["at:rural"] = 100,
["de:rural"] = 100,
["at:trunk"] = 100,
["cz:trunk"] = 0,
["ro:trunk"] = 100,
["cz:motorway"] = 0,
["de:motorway"] = 0,
["ru:motorway"] = 110,
["gb:nsl_single"] = (60*1609)/1000,
["gb:nsl_dual"] = (70*1609)/1000,
["gb:motorway"] = (70*1609)/1000,
["uk:nsl_single"] = (60*1609)/1000,
["uk:nsl_dual"] = (70*1609)/1000,
["uk:motorway"] = (70*1609)/1000
}
traffic_signal_penalty = 2
use_turn_restrictions = true
local take_minimum_of_speeds = false
local obey_oneway = true
local obey_bollards = true
local ignore_areas = true -- future feature
local u_turn_penalty = 20
local abs = math.abs
local min = math.min
local max = math.max
local speed_reduction = 0.8
--modes
local mode_normal = 1
local mode_ferry = 2
local mode_movable_bridge = 3
local function find_access_tag(source, access_tags_hierachy)
for i,v in ipairs(access_tags_hierachy) do
local access_tag = source:get_value_by_key(v)
if access_tag and "" ~= access_tag then
return access_tag
end
end
return ""
end
function get_exceptions(vector)
for i,v in ipairs(restriction_exception_tags) do
vector:Add(v)
end
end
local function parse_maxspeed(source)
if not source then
return 0
end
local n = tonumber(source:match("%d*"))
if n then
if string.match(source, "mph") or string.match(source, "mp/h") then
n = (n*1609)/1000;
end
else
-- parse maxspeed like FR:urban
source = string.lower(source)
n = maxspeed_table[source]
if not n then
local highway_type = string.match(source, "%a%a:(%a+)")
n = maxspeed_table_default[highway_type]
if not n then
n = 0
end
end
end
return n
end
-- function turn_function (angle)
-- -- print ("called at angle " .. angle )
-- local index = math.abs(math.floor(angle/10+0.5))+1 -- +1 'coz LUA starts as idx 1
-- local penalty = turn_cost_table[index]
-- -- print ("index: " .. index .. ", bias: " .. penalty )
-- return penalty
-- end
function node_function (node, result)
-- parse access and barrier tags
local access = find_access_tag(node, access_tags_hierachy)
if access ~= "" then
if access_tag_blacklist[access] then
result.barrier = true
end
else
local barrier = node:get_value_by_key("barrier")
if barrier and "" ~= barrier then
if not barrier_whitelist[barrier] then
result.barrier = true
end
end
end
-- check if node is a traffic light
local tag = node:get_value_by_key("highway")
if tag and "traffic_signals" == tag then
result.traffic_lights = true;
end
end
function way_function (way, result)
local highway = way:get_value_by_key("highway")
local route = way:get_value_by_key("route")
local bridge = way:get_value_by_key("bridge")
if not ((highway and highway ~= "") or (route and route ~= "") or (bridge and bridge ~= "")) then
return
end
-- we dont route over areas
local area = way:get_value_by_key("area")
if ignore_areas and area and "yes" == area then
return
end
-- check if oneway tag is unsupported
local oneway = way:get_value_by_key("oneway")
if oneway and "reversible" == oneway then
return
end
local impassable = way:get_value_by_key("impassable")
if impassable and "yes" == impassable then
return
end
local status = way:get_value_by_key("status")
if status and "impassable" == status then
return
end
local width = math.huge
local width_string = way:get_value_by_key("width")
if width_string and tonumber(width_string:match("%d*")) then
width = tonumber(width_string:match("%d*"))
end
-- Check if we are allowed to access the way
local access = find_access_tag(way, access_tags_hierachy)
if access_tag_blacklist[access] then
return
end
-- handling ferries and piers
local route_speed = speed_profile[route]
if (route_speed and route_speed > 0) then
highway = route;
local duration = way:get_value_by_key("duration")
if duration and durationIsValid(duration) then
result.duration = max( parseDuration(duration), 1 );
end
result.forward_mode = mode_ferry
result.backward_mode = mode_ferry
result.forward_speed = route_speed
result.backward_speed = route_speed
end
-- handling movable bridges
local bridge_speed = speed_profile[bridge]
local capacity_car = way:get_value_by_key("capacity:car")
if (bridge_speed and bridge_speed > 0) and (capacity_car ~= 0) then
highway = bridge;
local duration = way:get_value_by_key("duration")
if duration and durationIsValid(duration) then
result.duration = max( parseDuration(duration), 1 );
end
result.forward_mode = mode_movable_bridge
result.backward_mode = mode_movable_bridge
result.forward_speed = bridge_speed
result.backward_speed = bridge_speed
end
-- leave early of this way is not accessible
if "" == highway then
return
end
if result.forward_speed == -1 then
local highway_speed = speed_profile[highway]
local max_speed = parse_maxspeed( way:get_value_by_key("maxspeed") )
-- Set the avg speed on the way if it is accessible by road class
if highway_speed then
if max_speed and max_speed > highway_speed then
result.forward_speed = max_speed
result.backward_speed = max_speed
-- max_speed = math.huge
else
result.forward_speed = highway_speed
result.backward_speed = highway_speed
end
else
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] then
result.forward_speed = speed_profile["default"]
result.backward_speed = speed_profile["default"]
end
end
if 0 == max_speed then
max_speed = math.huge
end
result.forward_speed = min(result.forward_speed, max_speed)
result.backward_speed = min(result.backward_speed, max_speed)
end
if -1 == result.forward_speed and -1 == result.backward_speed then
return
end
-- reduce speed on bad surfaces
local surface = way:get_value_by_key("surface")
local tracktype = way:get_value_by_key("tracktype")
local smoothness = way:get_value_by_key("smoothness")
if surface and surface_speeds[surface] then
result.forward_speed = math.min(surface_speeds[surface], result.forward_speed)
result.backward_speed = math.min(surface_speeds[surface], result.backward_speed)
end
if tracktype and tracktype_speeds[tracktype] then
result.forward_speed = math.min(tracktype_speeds[tracktype], result.forward_speed)
result.backward_speed = math.min(tracktype_speeds[tracktype], result.backward_speed)
end
if smoothness and smoothness_speeds[smoothness] then
result.forward_speed = math.min(smoothness_speeds[smoothness], result.forward_speed)
result.backward_speed = math.min(smoothness_speeds[smoothness], result.backward_speed)
end
-- parse the remaining tags
local name = way:get_value_by_key("name")
local ref = way:get_value_by_key("ref")
local junction = way:get_value_by_key("junction")
-- local barrier = way:get_value_by_key("barrier", "")
-- local cycleway = way:get_value_by_key("cycleway", "")
local service = way:get_value_by_key("service")
-- Set the name that will be used for instructions
if ref and "" ~= ref then
result.name = ref
elseif name and "" ~= name then
result.name = name
-- else
-- result.name = highway -- if no name exists, use way type
end
if junction and "roundabout" == junction then
result.roundabout = true;
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
result.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service and service ~= "" and service_tag_restricted[service] then
result.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if oneway == "-1" then
result.forward_mode = 0
elseif oneway == "yes" or
oneway == "1" or
oneway == "true" or
junction == "roundabout" or
(highway == "motorway_link" and oneway ~="no") or
(highway == "motorway" and oneway ~= "no") then
result.backward_mode = 0
end
end
-- Override speed settings if explicit forward/backward maxspeeds are given
local maxspeed_forward = parse_maxspeed(way:get_value_by_key( "maxspeed:forward"))
local maxspeed_backward = parse_maxspeed(way:get_value_by_key( "maxspeed:backward"))
if maxspeed_forward and maxspeed_forward > 0 then
if 0 ~= result.forward_mode and 0 ~= result.backward_mode then
result.backward_speed = result.forward_speed
end
result.forward_speed = maxspeed_forward
end
if maxspeed_backward and maxspeed_backward > 0 then
result.backward_speed = maxspeed_backward
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] then
result.ignore_in_grid = true
end
-- scale speeds to get better avg driving times
if result.forward_speed > 0 then
local scaled_speed = result.forward_speed*speed_reduction + 11;
local penalized_speed = math.huge
if width <= 3 then
penalized_speed = result.forward_speed / 2;
end
result.forward_speed = math.min(penalized_speed, scaled_speed)
end
if result.backward_speed > 0 then
local scaled_speed = result.backward_speed*speed_reduction + 11;
local penalized_speed = math.huge
if width <= 3 then
penalized_speed = result.backward_speed / 2;
end
result.backward_speed = math.min(penalized_speed, scaled_speed)
end
end
-- These are wrappers to parse vectors of nodes and ways and thus to speed up any tracing JIT
function node_vector_function(vector)
for v in vector.nodes do
node_function(v)
end
end
| mit |
MinetestForFun/minetest-minetestforfun-server | mods/unified_inventory/waypoints.lua | 8 | 6964 | local S = unified_inventory.gettext
local F = unified_inventory.fgettext
local hud_colors = {
{"#FFFFFF", 0xFFFFFF, S("White")},
{"#DBBB00", 0xf1d32c, S("Yellow")},
{"#DD0000", 0xDD0000, S("Red")},
{"#2cf136", 0x2cf136, S("Green")},
{"#2c4df1", 0x2c4df1, S("Blue")},
}
local hud_colors_max = #hud_colors
-- Stores temporary player data (persists until player leaves)
local waypoints_temp = {}
unified_inventory.register_page("waypoints", {
get_formspec = function(player)
local player_name = player:get_player_name()
-- build a "fake" temp entry if the server took too long
-- during sign-on and returned an empty entry
if not waypoints_temp[player_name] then waypoints_temp[player_name] = {hud = 1} end
local waypoints = datastorage.get(player_name, "waypoints")
local formspec = "background[0,4.5;8,4;ui_main_inventory.png]" ..
"image[0,0;1,1;ui_waypoints_icon.png]" ..
"label[1,0;" .. F("Waypoints") .. "]"
-- Tabs buttons:
for i = 1, 5, 1 do
formspec = formspec ..
"image_button[0.0," .. 0.2 + i * 0.7 .. ";.8,.8;" ..
(i == waypoints.selected and "ui_blue_icon_background.png^" or "") ..
"ui_" .. i .. "_icon.png;" ..
"select_waypoint" .. i .. ";]" ..
"tooltip[select_waypoint" .. i .. ";"
.. (S("Select Waypoint #%d"):format(i)).."]"
end
local i = waypoints.selected or 1
local waypoint = waypoints[i] or {}
local temp = waypoints_temp[player_name][i] or {}
local default_name = string.format(S("Waypoint %d"), i)
-- Main buttons:
formspec = formspec ..
"image_button[4.5,3.7;.8,.8;"..
"ui_waypoint_set_icon.png;"..
"set_waypoint"..i..";]"..
"tooltip[set_waypoint" .. i .. ";"
.. F("Set waypoint to current location").."]"
formspec = formspec ..
"image_button[5.2,3.7;.8,.8;"..
(waypoint.active and "ui_on_icon.png" or "ui_off_icon.png")..";"..
"toggle_waypoint"..i..";]"..
"tooltip[toggle_waypoint" .. i .. ";"
.. F("Make waypoint "
..(waypoint.active and "invisible" or "visible")).."]"
formspec = formspec ..
"image_button[5.9,3.7;.8,.8;"..
(waypoint.display_pos and "ui_green_icon_background.png" or "ui_red_icon_background.png").."^ui_xyz_icon.png;"..
"toggle_display_pos" .. i .. ";]"..
"tooltip[toggle_display_pos" .. i .. ";"
.. F((waypoint.display_pos and "Disable" or "Enable")
.." display of waypoint coordinates").."]"
formspec = formspec ..
"image_button[6.6,3.7;.8,.8;"..
"ui_circular_arrows_icon.png;"..
"toggle_color"..i..";]"..
"tooltip[toggle_color" .. i .. ";"
.. F("Change color of waypoint display").."]"
formspec = formspec ..
"image_button[7.3,3.7;.8,.8;"..
"ui_pencil_icon.png;"..
"rename_waypoint"..i..";]"..
"tooltip[rename_waypoint" .. i .. ";"
.. F("Edit waypoint name").."]"
-- Waypoint's info:
if waypoint.active then
formspec = formspec .. "label[1,0.8;"..F("Waypoint active").."]"
else
formspec = formspec .. "label[1,0.8;"..F("Waypoint inactive").."]"
end
if temp.edit then
formspec = formspec ..
"field[1.3,3.2;6,.8;rename_box" .. i .. ";;"
..(waypoint.name or default_name).."]" ..
"image_button[7.3,2.9;.8,.8;"..
"ui_ok_icon.png;"..
"confirm_rename"..i.. ";]"..
"tooltip[confirm_rename" .. i .. ";"
.. F("Finish editing").."]"
end
formspec = formspec .. "label[1,1.3;"..F("World position")..": " ..
minetest.pos_to_string(waypoint.world_pos or vector.new()) .. "]" ..
"label[1,1.8;"..F("Name")..": ".. (waypoint.name or default_name) .. "]" ..
"label[1,2.3;"..F("HUD text color")..": " ..
hud_colors[waypoint.color or 1][3] .. "]"
return {formspec=formspec}
end,
})
unified_inventory.register_button("waypoints", {
type = "image",
image = "ui_waypoints_icon.png",
tooltip = S("Waypoints"),
hide_lite=true,
show_with = false, --Modif MFF (Crabman 30/06/2015)
})
local function update_hud(player, waypoints, temp, i)
local waypoint = waypoints[i]
if not waypoint then return end
temp[i] = temp[i] or {}
temp = temp[i]
local pos = waypoint.world_pos or vector.new()
local name
if waypoint.display_pos then
name = minetest.pos_to_string(pos)
if waypoint.name then
name = name..", "..waypoint.name
end
else
name = waypoint.name or "Waypoint "..i
end
if temp.hud then
player:hud_remove(temp.hud)
end
if waypoint.active then
temp.hud = player:hud_add({
hud_elem_type = "waypoint",
number = hud_colors[waypoint.color or 1][2] ,
name = name,
text = "m",
world_pos = pos
})
else
temp.hud = nil
end
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname ~= "" then return end
local player_name = player:get_player_name()
local update_formspec = false
local need_update_hud = false
local hit = false
local waypoints = datastorage.get(player_name, "waypoints")
local temp = waypoints_temp[player_name]
for i = 1, 5, 1 do
if fields["select_waypoint"..i] then
hit = true
waypoints.selected = i
update_formspec = true
end
if fields["toggle_waypoint"..i] then
hit = true
waypoints[i] = waypoints[i] or {}
waypoints[i].active = not (waypoints[i].active)
need_update_hud = true
update_formspec = true
end
if fields["set_waypoint"..i] then
hit = true
local pos = player:getpos()
pos.x = math.floor(pos.x)
pos.y = math.floor(pos.y)
pos.z = math.floor(pos.z)
waypoints[i] = waypoints[i] or {}
waypoints[i].world_pos = pos
need_update_hud = true
update_formspec = true
end
if fields["rename_waypoint"..i] then
hit = true
temp[i] = temp[i] or {}
temp[i].edit = true
update_formspec = true
end
if fields["toggle_display_pos"..i] then
hit = true
waypoints[i] = waypoints[i] or {}
waypoints[i].display_pos = not waypoints[i].display_pos
need_update_hud = true
update_formspec = true
end
if fields["toggle_color"..i] then
hit = true
waypoints[i] = waypoints[i] or {}
local color = waypoints[i].color or 1
color = color + 1
if color > hud_colors_max then
color = 1
end
waypoints[i].color = color
need_update_hud = true
update_formspec = true
end
if fields["confirm_rename"..i] then
hit = true
waypoints[i] = waypoints[i] or {}
temp[i].edit = false
waypoints[i].name = fields["rename_box"..i]
need_update_hud = true
update_formspec = true
end
if need_update_hud then
update_hud(player, waypoints, temp, i)
end
if update_formspec then
unified_inventory.set_inventory_formspec(player, "waypoints")
end
if hit then return end
end
end)
minetest.register_on_joinplayer(function(player)
local player_name = player:get_player_name()
local waypoints = datastorage.get(player_name, "waypoints")
local temp = {}
waypoints_temp[player_name] = temp
for i = 1, 5 do
update_hud(player, waypoints, temp, i)
end
end)
minetest.register_on_leaveplayer(function(player)
waypoints_temp[player:get_player_name()] = nil
end)
| unlicense |
AntumDeluge/arianne-stendhal | data/script/region/atlantis/music.lua | 3 | 1410 | --[[
***************************************************************************
* Copyright © 2020 - Arianne *
***************************************************************************
***************************************************************************
* *
* This program 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 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
]]
-- city
local zones = {
"deniran_atlantis_n2_w",
"deniran_atlantis_nw",
"deniran_atlantis_w",
"deniran_atlantis_sw",
"deniran_atlantis_n2",
"deniran_atlantis_n",
"deniran_atlantis",
"deniran_atlantis_s",
"deniran_atlantis_n2_e",
"deniran_atlantis_ne",
"deniran_atlantis_e",
"deniran_atlantis_se",
}
for _, z in pairs(zones) do
local zone = "-7_" .. z
if game:setZone(zone) then
game:setMusic("settlement_of_the_frontier", {volume=85})
else
logger:warn("Could not set zone " .. zone .. " to create BackGroundMusicSource")
end
end
| gpl-2.0 |
dev-osrose/osIROSE-new | scripts/mobs/ai/nigrum.lua | 2 | 1075 | registerNpc(383, {
walk_speed = 300,
run_speed = 1100,
scale = 280,
r_weapon = 0,
l_weapon = 0,
level = 120,
hp = 217,
attack = 695,
hit = 336,
def = 897,
res = 364,
avoid = 157,
attack_spd = 100,
is_magic_damage = 0,
ai_type = 338,
give_exp = 971,
drop_type = 395,
drop_money = 60,
drop_item = 80,
union_number = 80,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 250,
npc_type = 11,
hit_material_type = 2,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end | apache-2.0 |
r4dikal/Bd | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| gpl-3.0 |
opentomb/OpenTomb | scripts/strings/portuguese-ptbr/global_items.lua | 1 | 3366 | -- OPENTOMB INVENTORY GLOBAL ITEM NAMES
-- by Lwmte, Sep 2014
-- Brazilian Portuguese translation by: Rafael Fontenelle
-- Translation Version: 1.0.0.0 (January 17, 2018)
--------------------------------------------------------------------------------
-- In this file, we list all the global item names used across all games.
-- Non-global item names should be eventually listed in level-specific scripts.
-- Note that names list not always resemble item list, as we also introduce
-- game-specific global item names (e.g. compass was replaced by watch in TR2-3)
--------------------------------------------------------------------------------
ITEM_NAME_COMPASS = "Bússola"
ITEM_NAME_WATCH = "Estatísticas"
ITEM_NAME_PASSPORT = "Jogo"
ITEM_NAME_LARAHOME = "Casa da Lara"
ITEM_NAME_VIDEO = "Configurações de vídeo"
ITEM_NAME_AUDIO = "Configurações de áudio"
ITEM_NAME_CONTROLS = "Configurações de controle"
ITEM_NAME_LOAD = "Carregar jogo"
ITEM_NAME_SAVE = "Salvar jogo"
ITEM_NAME_MAP = "Mapa"
ITEM_NAME_PISTOLS = "Pistola"
ITEM_NAME_SHOTGUN = "Espingarda"
ITEM_NAME_MAGNUMS = "Magnums"
ITEM_NAME_AUTOMAGS = "Pistolas automáticas"
ITEM_NAME_DESERTEAGLE = "Desert eagle"
ITEM_NAME_REVOLVER = "Revólver"
ITEM_NAME_UZIS = "Uzis"
ITEM_NAME_M16 = "M16"
ITEM_NAME_MP5 = "MP5"
ITEM_NAME_HK = "Pistola H&K"
ITEM_NAME_GRENADEGUN = "Lançador de granadas"
ITEM_NAME_ROCKETGUN = "Bazuca"
ITEM_NAME_HARPOONGUN = "Arpão"
ITEM_NAME_CROSSBOW = "Besta"
ITEM_NAME_GRAPPLEGUN = "Gancho"
ITEM_NAME_LASERSIGHT = "Mira laser"
ITEM_NAME_BINOCULARS = "Binóculos"
ITEM_NAME_SILENCER = "Silenciador"
ITEM_NAME_REVOLVER_LASERSIGHT = "Revólver + mira laser"
ITEM_NAME_CROSSBOW_LASERSIGHT = "Besta + mira laser"
ITEM_NAME_HK_LASERSIGHT = "Pistola H&K + mira laser"
-- We don't need to specify each ammo name, as usually one weapon
-- has one type of ammo. This was changed since TR4, for which we
-- specify some ammo names explicitly.
ITEM_NAME_PISTOL_AMMO = "Munição de pistola"
ITEM_NAME_SHOTGUN_AMMO = "Munição de espingarda"
ITEM_NAME_SHOTGUN_NORMAL_AMMO = "Munição normal de espingarda"
ITEM_NAME_SHOTGUN_WIDESHOT_AMMO = "Munição de expansão de espingarda"
ITEM_NAME_MAGNUM_AMMO = "Munição de magnum"
ITEM_NAME_AUTOMAG_AMMO = "Munição de pistola automática"
ITEM_NAME_DESERTEAGLE_AMMO = "Munição de desert eagle"
ITEM_NAME_REVOLVER_AMMO = "Munição de revólver"
ITEM_NAME_UZI_AMMO = "Munição de Uzi"
ITEM_NAME_M16_AMMO = "Munição de M16"
ITEM_NAME_MP5_AMMO = "Munição de MP5"
ITEM_NAME_HK_AMMO = "Munição de pistola H&K"
ITEM_NAME_GRENADEGUN_AMMO = "Munição de lançador de granada"
ITEM_NAME_GRENADEGUN_NORMAL_AMMO = "Munição normal de lançador de granada"
ITEM_NAME_GRENADEGUN_SUPER_AMMO = "Munição super de lançador de gradada"
ITEM_NAME_GRENADEGUN_FLASH_AMMO = "Munição flash de lançador de granada"
ITEM_NAME_ROCKETGUN_AMMO = "Foguetes"
ITEM_NAME_HARPOONGUN_AMMO = "Arpões"
ITEM_NAME_CROSSBOW_NORMAL_AMMO = "Munição normal de besta"
ITEM_NAME_CROSSBOW_POISON_AMMO = "Munição envenenada de besta"
ITEM_NAME_CROSSBOW_EXPLOSIVE_AMMO = "Munição explosiva de besta"
ITEM_NAME_GRAPPLEGUN_AMMO = "Munição de gancho"
ITEM_NAME_FLARES = "Sinalizador"
ITEM_NAME_TORCH = "Tocha" -- Don't know why we may need this?..
ITEM_NAME_SMALL_MEDIPACK = "Kit médico pequeno"
ITEM_NAME_LARGE_MEDIPACK = "Kit médico grande"
| lgpl-3.0 |
pingidentity/lua-resty-openidc | tests/spec/pkce_spec.lua | 1 | 3301 | local http = require('socket.http')
local test_support = require('test_support')
require 'busted.runner'()
describe('when pkce is disabled in authorize request', function()
test_support.start_server()
teardown(test_support.stop_server)
local _, status, headers = http.request({
url = 'http://127.0.0.1/default/t',
redirect = false
})
it('there is no code_challenge parameter', function()
assert.falsy(string.match(headers['location'], '.*code_challenge=.*'))
end)
it('there is no code_challenge_method parameter', function()
assert.falsy(string.match(headers['location'], '.*code_challenge_method=.*'))
end)
end)
describe('when pkce is enabled in authorize request', function()
test_support.start_server({oidc_opts = { use_pkce = true } })
teardown(test_support.stop_server)
local _, status, headers = http.request({
url = 'http://127.0.0.1/default/t',
redirect = false
})
it('there is a code_challenge parameter', function()
assert.truthy(string.match(headers['location'], '.*code_challenge=.*'))
end)
it('there is a S256 code_challenge_method parameter', function()
assert.truthy(string.match(headers['location'], '.*code_challenge_method=S256.*'))
end)
end)
local function assert_token_endpoint_call_contains(s, case_insensitive)
assert.error_log_contains("Received token request: .*" .. s .. ".*",
case_insensitive)
end
local function assert_token_endpoint_call_doesnt_contain(s, case_insensitive)
assert.is_not.error_log_contains("Received token request: .*" .. s .. ".*",
case_insensitive)
end
describe('when pkce is disabled and the token endpoint is invoked', function()
test_support.start_server()
teardown(test_support.stop_server)
test_support.login()
it("the request doesn't contain a code_verifier", function()
assert_token_endpoint_call_doesnt_contain('.*code_verifier=.*')
end)
end)
describe('when pkce is enabled and the token endpoint is invoked', function()
test_support.start_server({oidc_opts = { use_pkce = true } })
teardown(test_support.stop_server)
local _, _, headers = http.request({
url = "http://127.0.0.1/default/t",
redirect = false
})
local state = test_support.grab(headers, 'state')
local code_challenge = test_support.grab(headers, 'code_challenge')
test_support.register_nonce(headers)
http.request({
url = "http://127.0.0.1/default/redirect_uri?code=foo&state=" .. state,
headers = { cookie = test_support.extract_cookies(headers) },
redirect = false
})
local log = test_support.load("/tmp/server/logs/error.log")
local code_verifier = log:match('Received token request: .*code_verifier=([^&]-)[&,]')
it('the request contains a code_verifier', function()
assert.truthy(code_verifier)
end)
it('hashing the code verifier leads to the challenge', function()
local as_base64 = function(s)
local rem = #s % 4
if rem > 0 then
s = s .. string.rep('=', 4 - rem)
end
return s:gsub('%-', '+'):gsub('_', '/')
end
local challenge = as_base64(code_challenge)
local hashed_verifier = (require 'mime').b64((require 'sha2').bytes(code_verifier))
assert.are.equals(hashed_verifier, challenge)
end)
end)
| apache-2.0 |
dev-osrose/osIROSE-new | scripts/npcs/ai/[cleric]_karitte.lua | 2 | 1065 | registerNpc(1053, {
walk_speed = 0,
run_speed = 0,
scale = 120,
r_weapon = 0,
l_weapon = 0,
level = 10,
hp = 100,
attack = 100,
hit = 100,
def = 100,
res = 100,
avoid = 100,
attack_spd = 100,
is_magic_damage = 0,
ai_type = 0,
give_exp = 0,
drop_type = 72,
drop_money = 0,
drop_item = 0,
union_number = 0,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 200,
npc_type = 999,
hit_material_type = 0,
face_icon = 15,
summon_mob_type = 15,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end | apache-2.0 |
dev-osrose/osIROSE-new | scripts/mobs/ai/hunter_clown.lua | 2 | 1950 | registerNpc(186, {
walk_speed = 170,
run_speed = 700,
scale = 110,
r_weapon = 1042,
l_weapon = 0,
level = 50,
hp = 23,
attack = 228,
hit = 144,
def = 131,
res = 70,
avoid = 83,
attack_spd = 85,
is_magic_damage = 0,
ai_type = 29,
give_exp = 39,
drop_type = 195,
drop_money = 25,
drop_item = 55,
union_number = 55,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 2100,
npc_type = 6,
hit_material_type = 1,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
registerNpc(189, {
walk_speed = 170,
run_speed = 700,
scale = 125,
r_weapon = 1042,
l_weapon = 0,
level = 59,
hp = 36,
attack = 271,
hit = 171,
def = 158,
res = 82,
avoid = 97,
attack_spd = 100,
is_magic_damage = 0,
ai_type = 264,
give_exp = 44,
drop_type = 195,
drop_money = 25,
drop_item = 38,
union_number = 38,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 2100,
npc_type = 6,
hit_material_type = 1,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end | apache-2.0 |
jeffrysleddens/KarniCrap | libs/LibStub/LibStub.lua | 10 | 2251 | -- $Id: LibStub.lua 103 2014-10-16 03:02:50Z mikk $
-- LibStub is a simple versioning stub meant for use in Libraries. http://www.wowace.com/addons/libstub/ for more info
-- LibStub is hereby placed in the Public Domain
-- Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel, joshborke
local LIBSTUB_MAJOR, LIBSTUB_MINOR = "LibStub", 2 -- NEVER MAKE THIS AN SVN REVISION! IT NEEDS TO BE USABLE IN ALL REPOS!
local LibStub = _G[LIBSTUB_MAJOR]
-- Check to see is this version of the stub is obsolete
if not LibStub or LibStub.minor < LIBSTUB_MINOR then
LibStub = LibStub or {libs = {}, minors = {} }
_G[LIBSTUB_MAJOR] = LibStub
LibStub.minor = LIBSTUB_MINOR
-- LibStub:NewLibrary(major, minor)
-- major (string) - the major version of the library
-- minor (string or number ) - the minor version of the library
--
-- returns nil if a newer or same version of the lib is already present
-- returns empty library object or old library object if upgrade is needed
function LibStub:NewLibrary(major, minor)
assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)")
minor = assert(tonumber(strmatch(minor, "%d+")), "Minor version must either be a number or contain a number.")
local oldminor = self.minors[major]
if oldminor and oldminor >= minor then return nil end
self.minors[major], self.libs[major] = minor, self.libs[major] or {}
return self.libs[major], oldminor
end
-- LibStub:GetLibrary(major, [silent])
-- major (string) - the major version of the library
-- silent (boolean) - if true, library is optional, silently return nil if its not found
--
-- throws an error if the library can not be found (except silent is set)
-- returns the library object if found
function LibStub:GetLibrary(major, silent)
if not self.libs[major] and not silent then
error(("Cannot find a library instance of %q."):format(tostring(major)), 2)
end
return self.libs[major], self.minors[major]
end
-- LibStub:IterateLibraries()
--
-- Returns an iterator for the currently registered libraries
function LibStub:IterateLibraries()
return pairs(self.libs)
end
setmetatable(LibStub, { __call = LibStub.GetLibrary })
end
| gpl-3.0 |
ld-test/luarocks | src/luarocks/purge.lua | 20 | 2636 |
--- Module implementing the LuaRocks "purge" command.
-- Remove all rocks from a given tree.
--module("luarocks.purge", package.seeall)
local purge = {}
package.loaded["luarocks.purge"] = purge
local util = require("luarocks.util")
local fs = require("luarocks.fs")
local path = require("luarocks.path")
local search = require("luarocks.search")
local deps = require("luarocks.deps")
local repos = require("luarocks.repos")
local manif = require("luarocks.manif")
local cfg = require("luarocks.cfg")
local remove = require("luarocks.remove")
purge.help_summary = "Remove all installed rocks from a tree."
purge.help_arguments = "--tree=<tree> [--old-versions]"
purge.help = [[
This command removes rocks en masse from a given tree.
By default, it removes all rocks from a tree.
The --tree argument is mandatory: luarocks purge does not
assume a default tree.
--old-versions Keep the highest-numbered version of each
rock and remove the other ones. By default
it only removes old versions if they are
not needed as dependencies. This can be
overridden with the flag --force.
]]
function purge.run(...)
local flags = util.parse_flags(...)
local tree = flags["tree"]
if type(tree) ~= "string" then
return nil, "The --tree argument is mandatory. "..util.see_help("purge")
end
local results = {}
local query = search.make_query("")
query.exact_name = false
if not fs.is_dir(tree) then
return nil, "Directory not found: "..tree
end
local ok, err = fs.check_command_permissions(flags)
if not ok then return nil, err, cfg.errorcodes.PERMISSIONDENIED end
search.manifest_search(results, path.rocks_dir(tree), query)
local sort = function(a,b) return deps.compare_versions(b,a) end
if flags["old-versions"] then
sort = deps.compare_versions
end
for package, versions in util.sortedpairs(results) do
for version, repositories in util.sortedpairs(versions, sort) do
if flags["old-versions"] then
util.printout("Keeping "..package.." "..version.."...")
local ok, err = remove.remove_other_versions(package, version, flags["force"])
if not ok then
util.printerr(err)
end
break
else
util.printout("Removing "..package.." "..version.."...")
local ok, err = repos.delete_version(package, version, true)
if not ok then
util.printerr(err)
end
end
end
end
return manif.make_manifest(cfg.rocks_dir, "one")
end
return purge
| mit |
oregamikiller/cocos2dPod | cocos/scripting/lua-bindings/auto/api/Physics3DRigidBody.lua | 11 | 12856 |
--------------------------------
-- @module Physics3DRigidBody
-- @extend Physics3DObject
-- @parent_module cc
--------------------------------
-- Set the acceleration.
-- @function [parent=#Physics3DRigidBody] setGravity
-- @param self
-- @param #vec3_table acceleration
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get friction.
-- @function [parent=#Physics3DRigidBody] getFriction
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- @overload self, float
-- @overload self, vec3_table
-- @function [parent=#Physics3DRigidBody] setAngularFactor
-- @param self
-- @param #vec3_table angFac
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
--
-- @function [parent=#Physics3DRigidBody] addConstraint
-- @param self
-- @param #cc.Physics3DConstraint constraint
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get the pointer of btRigidBody.
-- @function [parent=#Physics3DRigidBody] getRigidBody
-- @param self
-- @return btRigidBody#btRigidBody ret (return value: btRigidBody)
--------------------------------
-- Get total force.
-- @function [parent=#Physics3DRigidBody] getTotalForce
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Get the total number of constraints.
-- @function [parent=#Physics3DRigidBody] getConstraintCount
-- @param self
-- @return unsigned int#unsigned int ret (return value: unsigned int)
--------------------------------
-- Apply a central force.<br>
-- param force the value of the force
-- @function [parent=#Physics3DRigidBody] applyCentralForce
-- @param self
-- @param #vec3_table force
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set mass and inertia.
-- @function [parent=#Physics3DRigidBody] setMassProps
-- @param self
-- @param #float mass
-- @param #vec3_table inertia
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set friction.
-- @function [parent=#Physics3DRigidBody] setFriction
-- @param self
-- @param #float frict
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set kinematic object.
-- @function [parent=#Physics3DRigidBody] setKinematic
-- @param self
-- @param #bool kinematic
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set linear damping and angular damping.
-- @function [parent=#Physics3DRigidBody] setDamping
-- @param self
-- @param #float lin_damping
-- @param #float ang_damping
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Apply a impulse.<br>
-- param impulse the value of the impulse<br>
-- param rel_pos the position of the impulse
-- @function [parent=#Physics3DRigidBody] applyImpulse
-- @param self
-- @param #vec3_table impulse
-- @param #vec3_table rel_pos
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Check rigid body is kinematic object.
-- @function [parent=#Physics3DRigidBody] isKinematic
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Apply a torque.<br>
-- param torque the value of the torque
-- @function [parent=#Physics3DRigidBody] applyTorque
-- @param self
-- @param #vec3_table torque
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set motion threshold, don't do continuous collision detection if the motion (in one step) is less then ccdMotionThreshold
-- @function [parent=#Physics3DRigidBody] setCcdMotionThreshold
-- @param self
-- @param #float ccdMotionThreshold
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set rolling friction.
-- @function [parent=#Physics3DRigidBody] setRollingFriction
-- @param self
-- @param #float frict
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get motion threshold.
-- @function [parent=#Physics3DRigidBody] getCcdMotionThreshold
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Get the linear factor.
-- @function [parent=#Physics3DRigidBody] getLinearFactor
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Damps the velocity, using the given linearDamping and angularDamping.
-- @function [parent=#Physics3DRigidBody] applyDamping
-- @param self
-- @param #float timeStep
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get the angular velocity.
-- @function [parent=#Physics3DRigidBody] getAngularVelocity
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
--
-- @function [parent=#Physics3DRigidBody] init
-- @param self
-- @param #cc.Physics3DRigidBodyDes info
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Apply a torque impulse.<br>
-- param torque the value of the torque
-- @function [parent=#Physics3DRigidBody] applyTorqueImpulse
-- @param self
-- @param #vec3_table torque
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Active or inactive.
-- @function [parent=#Physics3DRigidBody] setActive
-- @param self
-- @param #bool active
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set the linear factor.
-- @function [parent=#Physics3DRigidBody] setLinearFactor
-- @param self
-- @param #vec3_table linearFactor
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set the linear velocity.
-- @function [parent=#Physics3DRigidBody] setLinearVelocity
-- @param self
-- @param #vec3_table lin_vel
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get the linear velocity.
-- @function [parent=#Physics3DRigidBody] getLinearVelocity
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Set swept sphere radius.
-- @function [parent=#Physics3DRigidBody] setCcdSweptSphereRadius
-- @param self
-- @param #float radius
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Apply a force.<br>
-- param force the value of the force<br>
-- param rel_pos the position of the force
-- @function [parent=#Physics3DRigidBody] applyForce
-- @param self
-- @param #vec3_table force
-- @param #vec3_table rel_pos
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set the angular velocity.
-- @function [parent=#Physics3DRigidBody] setAngularVelocity
-- @param self
-- @param #vec3_table ang_vel
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Apply a central impulse.<br>
-- param impulse the value of the impulse
-- @function [parent=#Physics3DRigidBody] applyCentralImpulse
-- @param self
-- @param #vec3_table impulse
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get the acceleration.
-- @function [parent=#Physics3DRigidBody] getGravity
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Get rolling friction.
-- @function [parent=#Physics3DRigidBody] getRollingFriction
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Set the center of mass.
-- @function [parent=#Physics3DRigidBody] setCenterOfMassTransform
-- @param self
-- @param #mat4_table xform
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set the inverse of local inertia.
-- @function [parent=#Physics3DRigidBody] setInvInertiaDiagLocal
-- @param self
-- @param #vec3_table diagInvInertia
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- @overload self, unsigned int
-- @overload self, cc.Physics3DConstraint
-- @function [parent=#Physics3DRigidBody] removeConstraint
-- @param self
-- @param #cc.Physics3DConstraint constraint
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get total torque.
-- @function [parent=#Physics3DRigidBody] getTotalTorque
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Get inverse of mass.
-- @function [parent=#Physics3DRigidBody] getInvMass
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Get constraint by index.
-- @function [parent=#Physics3DRigidBody] getConstraint
-- @param self
-- @param #unsigned int idx
-- @return Physics3DConstraint#Physics3DConstraint ret (return value: cc.Physics3DConstraint)
--------------------------------
-- Get restitution.
-- @function [parent=#Physics3DRigidBody] getRestitution
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Get swept sphere radius.
-- @function [parent=#Physics3DRigidBody] getCcdSweptSphereRadius
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Get hit friction.
-- @function [parent=#Physics3DRigidBody] getHitFraction
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Get angular damping.
-- @function [parent=#Physics3DRigidBody] getAngularDamping
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Get the inverse of local inertia.
-- @function [parent=#Physics3DRigidBody] getInvInertiaDiagLocal
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Get the center of mass.
-- @function [parent=#Physics3DRigidBody] getCenterOfMassTransform
-- @param self
-- @return mat4_table#mat4_table ret (return value: mat4_table)
--------------------------------
-- Get the angular factor.
-- @function [parent=#Physics3DRigidBody] getAngularFactor
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Set restitution.
-- @function [parent=#Physics3DRigidBody] setRestitution
-- @param self
-- @param #float rest
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set hit friction.
-- @function [parent=#Physics3DRigidBody] setHitFraction
-- @param self
-- @param #float hitFraction
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get linear damping.
-- @function [parent=#Physics3DRigidBody] getLinearDamping
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- override.
-- @function [parent=#Physics3DRigidBody] getWorldTransform
-- @param self
-- @return mat4_table#mat4_table ret (return value: mat4_table)
--------------------------------
--
-- @function [parent=#Physics3DRigidBody] Physics3DRigidBody
-- @param self
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
return nil
| mit |
i-z/cocos2d-x-samples | samples/FantasyWarrior3D/src/cocos/cocosbuilder/CCBReaderLoad.lua | 79 | 5530 | ccb = ccb or {}
function CCBReaderLoad(strFilePath,proxy,owner)
if nil == proxy then
return nil
end
local ccbReader = proxy:createCCBReader()
local node = ccbReader:load(strFilePath)
local rootName = ""
--owner set in readCCBFromFile is proxy
if nil ~= owner then
--Callbacks
local ownerCallbackNames = ccbReader:getOwnerCallbackNames()
local ownerCallbackNodes = ccbReader:getOwnerCallbackNodes()
local ownerCallbackControlEvents = ccbReader:getOwnerCallbackControlEvents()
local i = 1
for i = 1,table.getn(ownerCallbackNames) do
local callbackName = ownerCallbackNames[i]
local callbackNode = tolua.cast(ownerCallbackNodes[i],"cc.Node")
if "function" == type(owner[callbackName]) then
proxy:setCallback(callbackNode, owner[callbackName], ownerCallbackControlEvents[i])
else
print("Warning: Cannot find owner's lua function:" .. ":" .. callbackName .. " for ownerVar selector")
end
end
--Variables
local ownerOutletNames = ccbReader:getOwnerOutletNames()
local ownerOutletNodes = ccbReader:getOwnerOutletNodes()
for i = 1, table.getn(ownerOutletNames) do
local outletName = ownerOutletNames[i]
local outletNode = tolua.cast(ownerOutletNodes[i],"cc.Node")
owner[outletName] = outletNode
end
end
local nodesWithAnimationManagers = ccbReader:getNodesWithAnimationManagers()
local animationManagersForNodes = ccbReader:getAnimationManagersForNodes()
for i = 1 , table.getn(nodesWithAnimationManagers) do
local innerNode = tolua.cast(nodesWithAnimationManagers[i], "cc.Node")
local animationManager = tolua.cast(animationManagersForNodes[i], "cc.CCBAnimationManager")
local documentControllerName = animationManager:getDocumentControllerName()
if "" == documentControllerName then
end
if nil ~= ccb[documentControllerName] then
ccb[documentControllerName]["mAnimationManager"] = animationManager
end
--Callbacks
local documentCallbackNames = animationManager:getDocumentCallbackNames()
local documentCallbackNodes = animationManager:getDocumentCallbackNodes()
local documentCallbackControlEvents = animationManager:getDocumentCallbackControlEvents()
for i = 1,table.getn(documentCallbackNames) do
local callbackName = documentCallbackNames[i]
local callbackNode = tolua.cast(documentCallbackNodes[i],"cc.Node")
if "" ~= documentControllerName and nil ~= ccb[documentControllerName] then
if "function" == type(ccb[documentControllerName][callbackName]) then
proxy:setCallback(callbackNode, ccb[documentControllerName][callbackName], documentCallbackControlEvents[i])
else
print("Warning: Cannot found lua function [" .. documentControllerName .. ":" .. callbackName .. "] for docRoot selector")
end
end
end
--Variables
local documentOutletNames = animationManager:getDocumentOutletNames()
local documentOutletNodes = animationManager:getDocumentOutletNodes()
for i = 1, table.getn(documentOutletNames) do
local outletName = documentOutletNames[i]
local outletNode = tolua.cast(documentOutletNodes[i],"cc.Node")
if nil ~= ccb[documentControllerName] then
ccb[documentControllerName][outletName] = tolua.cast(outletNode, proxy:getNodeTypeName(outletNode))
end
end
--[[
if (typeof(controller.onDidLoadFromCCB) == "function")
controller.onDidLoadFromCCB();
]]--
--Setup timeline callbacks
local keyframeCallbacks = animationManager:getKeyframeCallbacks()
for i = 1 , table.getn(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 and nil ~= ccb[documentControllerName] then
local callfunc = cc.CallFunc:create(ccb[documentControllerName][callbackName])
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
return node
end
local function CCBuilderReaderLoad(strFilePath,proxy,owner)
print("\n********** \n".."CCBuilderReaderLoad(strFilePath,proxy,owner)".." was deprecated please use ".. "CCBReaderLoad(strFilePath,proxy,owner)" .. " instead.\n**********")
return CCBReaderLoad(strFilePath,proxy,owner)
end
rawset(_G,"CCBuilderReaderLoad",CCBuilderReaderLoad) | mit |
zzuse/hammerspoon | widgets/hcalendar.lua | 2 | 6229 | hcalbgcolor = {red=0,blue=0,green=0,alpha=0.3}
hcaltitlecolor = {red=1,blue=1,green=1,alpha=0.3}
offdaycolor = {red=255/255,blue=120/255,green=120/255,alpha=1}
hcaltodaycolor = {red=1,blue=1,green=1,alpha=0.2}
midlinecolor = {red=1,blue=1,green=1,alpha=0.5}
midlinetodaycolor = {red=0,blue=1,green=186/255,alpha=0.8}
midlineoffcolor = {red=1,blue=119/255,green=119/255,alpha=0.5}
if not hcaltopleft then hcaltopleft = {40,658} end
weeknames = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}
hcaltitlewh = {180,32}
hcaldaywh = {23.43,24}
function showHCalendar()
local titlestr = os.date("%B %Y")
if not hcaltitle then
local styledtitle = hs.styledtext.new(titlestr,{font={size=18},color=hcaltitlecolor,paragraphStyle={alignment="left"}})
local title_rect = hs.geometry.rect(hcaltopleft[1]+10,hcaltopleft[2]+15,hcaltitlewh[1],hcaltitlewh[2])
hcaltitle = hs.drawing.text(title_rect,styledtitle)
hcaltitle:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces)
hcaltitle:setLevel(hs.drawing.windowLevels.desktopIcon)
hcaltitle:show()
else
hcaltitle:setText(titlestr)
end
local currentyear = os.date("%Y")
local currentmonth = os.date("%m")
local firstdayofnextmonth = os.time{year=currentyear, month=currentmonth+1, day=1}
local maxdayofcurrentmonth = os.date("*t", firstdayofnextmonth-24*60*60).day
weekdayup = ""
daydown = ""
offday = {}
for i=1,maxdayofcurrentmonth do
local weekdayofquery = os.date("*t", os.time{year=currentyear, month=currentmonth, day=i}).wday
local weekstr = weeknames[weekdayofquery]
weekdayup = weekdayup .. weekstr .. ' '
daydown = daydown .. string.format('%2s',i)..' '
if weekstr == 'Sa' or weekstr == 'Su' then
table.insert(offday,{i,weekstr..'\n'..string.format('%2s',i)})
end
end
local caltext = weekdayup..'\n'..daydown
if not hcaltextdraw then
local styledcaltext = hs.styledtext.new(caltext,{font={name="Courier-Bold",size=13},paragraphStyle={lineSpacing=8.0}})
local caltextrect = hs.geometry.rect(hcaltopleft[1]+10,hcaltopleft[2]+15+hcaltitlewh[2],hcaldaywh[1]*maxdayofcurrentmonth,43)
hcaltextdraw = hs.drawing.text(caltextrect,styledcaltext)
hcaltextdraw:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces)
hcaltextdraw:setLevel(hs.drawing.windowLevels.desktopIcon)
hcaltextdraw:show()
else
hcaltextdraw:setText(caltext)
end
local midlinerect = hs.geometry.rect(hcaltopleft[1]+10,hcaltopleft[2]+15+hcaltitlewh[2]+20,hcaldaywh[1]*maxdayofcurrentmonth-3,4)
if not midlinedraw then
midlinedraw = hs.drawing.rectangle(midlinerect)
midlinedraw:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces)
midlinedraw:setLevel(hs.drawing.windowLevels.desktopIcon)
midlinedraw:setFillColor(midlinecolor)
midlinedraw:setStroke(false)
midlinedraw:show()
else
midlinedraw:setFrame(midlinerect)
end
local hcalbgrect = hs.geometry.rect(hcaltopleft[1],hcaltopleft[2],hcaldaywh[1]*maxdayofcurrentmonth+20-3,102)
if not hcalbg then
hcalbg = hs.drawing.rectangle(hcalbgrect)
hcalbg:setFillColor(hcalbgcolor)
hcalbg:setStroke(false)
hcalbg:setRoundedRectRadii(10,10)
hcalbg:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces)
hcalbg:setLevel(hs.drawing.windowLevels.desktopIcon)
hcalbg:show()
else
hcalbg:setFrame(hcalbgrect)
end
if offday_holder and #offday_holder > 0 then
for i=1,#offday_holder do
offday_holder[i]:delete()
offdaymidline_holder[i]:delete()
end
end
offday_holder = {}
offdaymidline_holder = {}
for i=1,#offday do
local offdayrect = hs.geometry.rect(hcaltopleft[1]+10+hcaldaywh[1]*(offday[i][1]-1),hcaltopleft[2]+15+hcaltitlewh[2],hcaldaywh[1],43)
local offdaytext = hs.styledtext.new(offday[i][2],{font={name="Courier-Bold",size=13},color=offdaycolor,paragraphStyle={lineSpacing=8.0}})
table.insert(offday_holder,hs.drawing.text(offdayrect,offdaytext))
offday_holder[i]:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces)
offday_holder[i]:setLevel(hs.drawing.windowLevels.desktopIcon)
offday_holder[i]:show()
local offdaymidlinerect = hs.geometry.rect(hcaltopleft[1]+10+hcaldaywh[1]*(offday[i][1]-1)-3,hcaltopleft[2]+15+hcaltitlewh[2]+20,hcaldaywh[1],4)
table.insert(offdaymidline_holder,hs.drawing.rectangle(offdaymidlinerect))
offdaymidline_holder[i]:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces)
offdaymidline_holder[i]:setLevel(hs.drawing.windowLevels.desktopIcon)
offdaymidline_holder[i]:setFillColor(midlineoffcolor)
offdaymidline_holder[i]:setStroke(false)
offdaymidline_holder[i]:show()
end
local today = math.tointeger(os.date("%d"))
local todayrect = hs.geometry.rect(hcaltopleft[1]+10+hcaldaywh[1]*(today-1)-3,hcaltopleft[2]+15+hcaltitlewh[2],hcaldaywh[1],43)
if not todaydraw then
todaydraw = hs.drawing.rectangle(todayrect)
todaydraw:setFillColor(hcaltodaycolor)
todaydraw:setStroke(false)
todaydraw:setRoundedRectRadii(3,3)
todaydraw:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces)
todaydraw:setLevel(hs.drawing.windowLevels.desktopIcon)
todaydraw:show()
else
todaydraw:setFrame(todayrect)
end
todaymidlinerect = hs.geometry.rect(hcaltopleft[1]+10+hcaldaywh[1]*(today-1)-3,hcaltopleft[2]+15+hcaltitlewh[2]+20,hcaldaywh[1],4)
-- Don't know why the draw order is not correct
if todaymidlinedraw then
todaymidlinedraw:delete()
todaymidlinedraw=nil
end
todaymidlinedraw = hs.drawing.rectangle(todaymidlinerect)
todaymidlinedraw:setFillColor(midlinetodaycolor)
todaymidlinedraw:setStroke(false)
todaymidlinedraw:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces)
todaymidlinedraw:setLevel(hs.drawing.windowLevels.desktopIcon)
todaymidlinedraw:show()
end
showHCalendar()
hcaltimer = hs.timer.doEvery(1800, function() showHCalendar() end)
| mit |
PurgePJ/VouchBot | deps/discordia/libs/enums.lua | 1 | 3711 | local function enum(tbl)
local call = {}
for k, v in pairs(tbl) do
if call[v] then
return error(string.format('enum clash for %q and %q', k, call[v]))
end
call[v] = k
end
return setmetatable({}, {
__call = function(_, k)
if call[k] then
return call[k]
else
return error('invalid enumeration: ' .. k)
end
end,
__index = function(_, k)
if tbl[k] then
return tbl[k]
else
return error('invalid enumeration: ' .. k)
end
end,
__pairs = function()
return next, tbl
end,
__newindex = function()
return error('cannot overwrite enumeration')
end,
})
end
local enums = {enum = enum}
enums.defaultAvatar = enum {
blurple = 0,
gray = 1,
green = 2,
orange = 3,
red = 4,
}
enums.notificationSetting = enum {
allMessages = 0,
onlyMentions = 1,
}
enums.channelType = enum {
text = 0,
private = 1,
voice = 2,
group = 3,
category = 4,
}
enums.messageType = enum {
default = 0,
recipientAdd = 1,
recipientRemove = 2,
call = 3,
channelNameChange = 4,
channelIconchange = 5,
pinnedMessage = 6,
memberJoin = 7,
}
enums.relationshipType = enum {
none = 0,
friend = 1,
blocked = 2,
pendingIncoming = 3,
pendingOutgoing = 4,
}
enums.gameType = enum {
default = 0,
streaming = 1,
}
enums.verificationLevel = enum {
none = 0,
low = 1,
medium = 2,
high = 3, -- (╯°□°)╯︵ ┻━┻
veryHigh = 4, -- ┻━┻ ミヽ(ಠ益ಠ)ノ彡┻━┻
}
enums.explicitContentLevel = enum {
none = 0,
medium = 1,
high = 2,
}
enums.permission = enum {
createInstantInvite = 0x00000001,
kickMembers = 0x00000002,
banMembers = 0x00000004,
administrator = 0x00000008,
manageChannels = 0x00000010,
manageGuild = 0x00000020,
addReactions = 0x00000040,
viewAuditLog = 0x00000080,
readMessages = 0x00000400,
sendMessages = 0x00000800,
sendTextToSpeech = 0x00001000,
manageMessages = 0x00002000,
embedLinks = 0x00004000,
attachFiles = 0x00008000,
readMessageHistory = 0x00010000,
mentionEveryone = 0x00020000,
useExternalEmojis = 0x00040000,
connect = 0x00100000,
speak = 0x00200000,
muteMembers = 0x00400000,
deafenMembers = 0x00800000,
moveMembers = 0x01000000,
useVoiceActivity = 0x02000000,
changeNickname = 0x04000000,
manageNicknames = 0x08000000,
manageRoles = 0x10000000,
manageWebhooks = 0x20000000,
manageEmojis = 0x40000000,
}
enums.actionType = enum {
guildUpdate = 1,
channelCreate = 10,
channelUpdate = 11,
channelDelete = 12,
channelOverwriteCreate = 13,
channelOverwriteUpdate = 14,
channelOverwriteDelete = 15,
memberKick = 20,
memberPrune = 21,
memberBanAdd = 22,
memberBanRemove = 23,
memberUpdate = 24,
memberRoleUpdate = 25,
roleCreate = 30,
roleUpdate = 31,
roleDelete = 32,
inviteCreate = 40,
inviteUpdate = 41,
inviteDelete = 42,
webhookCreate = 50,
webhookUpdate = 51,
webhookDelete = 52,
emojiCreate = 60,
emojiUpdate = 61,
emojiDelete = 62,
messageDelete = 72,
}
enums.logLevel = enum {
none = 0,
error = 1,
warning = 2,
info = 3,
debug = 4,
}
return enums
| gpl-3.0 |
lytedev/love2d-bootstrap | lib/animation/state.lua | 1 | 4457 | --[[
File: src/animation/state.lua
Author: Daniel "lytedev" Flanagan
Website: http://dmf.me
A manager for an animation Group and for drawing the current state.
]]--
local Frame = require("lib.animation.frame")
local State = Class{}
function State:init(image, group, size, initialKey)
self:reset()
self.image = image
self.group = group
self.key = "default"
if self.group then
self.key = group.initialKey
end
if initialKey then
self.key = initialKey
end
self.size = size or Vector(self.image:getWidth(), self.image:getHeight())
self.overlay = {255, 255, 255, 255}
self.offset = Vector(0, 0)
self.quad = love.graphics.newQuad(0, 0, self.size.x, self.size.y, self.image:getWidth(), self.image:getHeight())
end
function State:reset()
self.currentFrameID = 1
self.currentTime = 0
self.currentFrames = 0
self.started = false
self.ended = true
self.looping = false
self.bouncing = false
end
function State:setKey(key)
self.key = key
self:reset()
end
function State:getSet()
if self.group then
return self.group:getSet(self.key)
else
return nil
end
end
function State:getFrame()
local a = self:getSet()
if a then
return a:getFrame(self.currentFrameID)
else
cprint("Animation: Tried to fetch Frame with no Set - returning image dimension frame")
return Frame(Vector(0, 0), Vector(self.image:getWidth(), self.image:getHeight()))
end
end
function State:update(dt)
self.currentTime = self.currentTime + dt
self.currentFrames = self.currentFrames + 1
local a = self:getSet()
if not a then
return
end
if self.currentFrameID > #a.frames then
self:reset()
end
if #a.frames >= 1 and self.currentFrameID >= 1 then
local f = self:getFrame()
if f.frames then
if self.currentFrames >= f.frames then
self:nextFrame(f, a)
end
end
if self.currentTime >= f.time then
self:nextFrame(f, a)
end
self.quad:setViewport(f.source.x, f.source.y, f.size.x, f.size.y)
self.offset = f.offset
end
end
function State:nextFrame(currentFrame, currentSet)
self.currentTime = 0
self.currentFrames = 0
if not self.bouncing then
self.currentFrameID = self.currentFrameID + 1
else
if self.currentFrameID > 1 then
self.currentFrameID = self.currentFrameID - 1
else
self.bouncing = false
self.currentFrameID = self.currentFrameID + 1
end
end
local innerLoopExists = currentSet.loopStart > 1 and currentSet.loopEnd < #currentSet.frames and currentSet.loopEnd >= currentSet.loopStart;
if not self.started then
if self.bouncing then
if self.currentFrameID <= 1 then
self.bouncing = false
-- self.currentFrameID = self.currentFrameID + 1
end
else
self.looping = innerLoopExists and self.currentFrameID >= currentSet.loopEnd
if self.currentFrameID > #currentSet.frames or self.looping then
self.started = true
self.bouncing = self.bounce
if not self.bounce and innerLoopExists then
self.currentFrameID = currentSet.loopStart
elseif not self.bounce then
self.started = false
self.currentFrameID = 1
end
end
end
elseif self.looping and innerLoopExists then
self.bouncing = not (self.currentFrameID <= currentSet.loopStart and self.bouncing)
if self.currentFrameID >= currentSet.loopEnd and not self.bounce then
self.currentFrameID = currentSet.loopStart
end
else
if #currentSet.frames >= 1 then
if self.currentFrameID >= #currentSet.frames then
self.ended = true
self.started = false
self.looping = false
self.bouncing = self.bounce
if not self.bounce then
self.currentFrameID = 1
end
end
end
end
end
function State:draw(position)
love.graphics.setColor(self.overlay)
love.graphics.drawq(self.image, self.quad, (position.x + self.offset.x), (position.y + self.offset.y))
end
return State
| mit |
eladhoffer/eladtools | GlobalDominantPooling.lua | 2 | 1246 | require 'nn'
require 'cunn'
local GlobalDominantPooling, parent = torch.class('nn.GlobalDominantPooling', 'nn.Module')
function GlobalDominantPooling:__init(ratio)
self.ratio = ratio or 0.25
self.output = torch.Tensor()
self.mask = torch.Tensor()
self.buffer = torch.Tensor()
self.gradInput = torch.Tensor()
end
function GlobalDominantPooling:updateOutput(input)
torch.max(self.mask, self.mask, input, 2)
local _,dominantFeat = input:view(input:size(1),input:size(2),-1):sum(3):max(2)
dominantFeat = dominantFeat:view(input:size(1), 1, 1, 1):expand(input:size(1), 1, input:size(3), input:size(4))
torch.eq(self.mask, self.mask, dominantFeat)
--self.mask:scatter(dim,indices,1):typeAs(input)
self.mask:cdiv(self.mask:view(input:size(1),-1):sum(2):view(-1,1,1,1):expandAs(self.mask))
torch.cmul(self.buffer, input, self.mask:expandAs(input))
torch.sum(self.output, self.buffer:view(input:size(1),input:size(2),-1), 3)
self.output = self.output:select(3,1)
return self.output
end
function GlobalDominantPooling:updateGradInput(input, gradOutput)
torch.cmul(self.gradInput, gradOutput:view(input:size(1),input:size(2),1,1):expandAs(input),self.mask:expandAs(input))
return self.gradInput:expandAs(input)
end
| mit |
bn7/darkstar | scripts/zones/Uleguerand_Range/Zone.lua | 11 | 2413 | -----------------------------------
--
-- Zone: Uleguerand_Range (5)
--
-----------------------------------
package.loaded["scripts/zones/Uleguerand_Range/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/weather");
require("scripts/globals/zone");
require("scripts/zones/Uleguerand_Range/TextIDs");
require("scripts/globals/missions");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
-- Jormungand
SetRespawnTime(16797969, 86400, 259200);
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(363.025,16,-60,12);
end
if (player:getCurrentMission(COP) == DAWN and player:getVar("COP_louverance_story")== 1 ) then
cs=0x0011;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0011) then
player:setVar("COP_louverance_story",2);
end
end;
-----------------------------------
-- onZoneWeatherChange
-----------------------------------
function onZoneWeatherChange(weather)
local waterfall = GetNPCByID(16798112);
if (weather == WEATHER_SNOW or weather == WEATHER_BLIZZARDS) then
if (waterfall:getAnimation() ~= 9) then
waterfall:setAnimation(9);
end
else
if (waterfall:getAnimation() ~= 8) then
waterfall:setAnimation(8);
end
end
end;
| gpl-3.0 |
bn7/darkstar | scripts/zones/Selbina/npcs/Explorer_Moogle.lua | 17 | 1855 | -----------------------------------
-- Area: Selbina
-- NPC: Explorer Moogle
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/teleports");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
accept = 0;
event = 0x046f;
if (player:getGil() < 300) then
accept = 1;
end
if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then
event = event + 1;
end
player:startEvent(event,player:getZoneID(),0,accept);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local price = 300;
if (csid == 0x046f) then
if (option == 1 and player:delGil(price)) then
toExplorerMoogle(player,231);
elseif (option == 2 and player:delGil(price)) then
toExplorerMoogle(player,234);
elseif (option == 3 and player:delGil(price)) then
toExplorerMoogle(player,240);
elseif (option == 4 and player:delGil(price)) then
toExplorerMoogle(player,248);
elseif (option == 5 and player:delGil(price)) then
toExplorerMoogle(player,249);
end
end
end; | gpl-3.0 |
bn7/darkstar | scripts/zones/North_Gustaberg/npcs/qm2.lua | 14 | 1694 | -----------------------------------
-- Area: North Gustaberg
-- NPC: qm2 (???)
-- Involved in Quest "As Thick As Thieves"
-- @pos -232.924 99.107 442.990 106
-----------------------------------
package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/quests");
require("scripts/zones/North_Gustaberg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local thickAsThievesGamblingCS = player:getVar("thickAsThievesGamblingCS");
if (thickAsThievesGamblingCS == 5) then
SpawnMob(17211848):updateClaim(player);
elseif (thickAsThievesGamblingCS == 6) then
player:startEvent(0x00c8,1092);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00c8) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1092);
else
player:addItem(1092);
player:messageSpecial(ITEM_OBTAINED,1092);
player:setVar("thickAsThievesGamblingCS",7);
end
end
end; | gpl-3.0 |
HuangYuNan/thcsvr | expansions/script/c999013.lua | 1 | 8398 | --水边的幻想 濑笈叶
local M = c999013
local Mid = 999013
function M.initial_effect(c)
--link summon
c:EnableReviveLimit()
Nef.AddLinkProcedureWithDesc(c, aux.FilterBoolFunction(Card.IsRace, RACE_PLANT), 2, 2, nil, aux.Stringid(Mid, 2))
--link summon custom
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetDescription(aux.Stringid(Mid, 0))
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE+EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetRange(LOCATION_EXTRA)
e1:SetCountLimit(1, Mid*10+1)
e1:SetCondition(M.lkcon)
e1:SetOperation(M.lkop)
e1:SetValue(SUMMON_TYPE_LINK)
c:RegisterEffect(e1)
-- fusion
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_FUSION_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetDescription(aux.Stringid(Mid, 1))
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1, Mid*10+2)
e2:SetCost(M.spcost)
e2:SetTarget(M.sptg)
e2:SetOperation(M.spop)
c:RegisterEffect(e2)
end
function M.CheckMaterialSingle(c, fc, mc)
local tp = fc:GetControler()
if not c:IsCanBeFusionMaterial(fc) then return false end
local t = fc.hana_mat
if not t then return false end
for i, f in pairs(t) do
if f(c) then return true end
end
return false
end
function M.fmatcheck(c, fc)
return c:IsAbleToGrave() and M.CheckMaterialSingle(c, fc)
end
function M.fmatcheck2(c, fc, mg)
if not mg or mg:GetCount() == 0 then return false end
return c:IsAbleToGrave() and M.CheckMaterialSingle(c, fc)
and mg:IsExists(M.gridcheck, 1, nil, fc, c)
end
function M.gridcheck(c, fc, c2)
local tp = fc:GetControler()
return Duel.GetLocationCountFromEx(tp, tp, Group.FromCards(c, c2), fc) > 0
end
function M.fusionfilter(c, tp)
return c:IsType(TYPE_FUSION) and c:IsRace(RACE_PLANT)
and Duel.IsExistingMatchingCard(M.CheckMaterialSingle, tp, LOCATION_HAND+LOCATION_MZONE, 0, 1, nil, c)
end
--[[
fg:所有植物族融合怪兽
]]
function M.matfilter1(c, fg, tp)
local g1 = Duel.GetMatchingGroup(M.fmatcheck, tp, LOCATION_HAND+LOCATION_MZONE, 0, nil, c)
return fg:IsExists(M.matfilter2, 1, c, g1, c:GetCode(), tp)
end
--[[
g1: 第1只融合怪兽的所有可用素材组
code: 第1只融合怪兽的卡密
]]
function M.matfilter2(c, g1, code, tp)
if c:IsCode(code) then return false end
local g2 = Duel.GetMatchingGroup(M.fmatcheck2, tp, LOCATION_HAND+LOCATION_MZONE, 0, nil, c, g1)
if g2:GetCount() == 0 then return false end
g2:Merge(g1)
return g2:GetCount() > 1
end
function M.samefilter(c, g)
return g:IsContains(c)
end
function M.lkcon(e, c)
if c == nil then return true end
if c:IsType(TYPE_PENDULUM) and c:IsFaceup() then return false end
local tp = c:GetControler()
local mg = Duel.GetMatchingGroup(M.fusionfilter, tp, LOCATION_EXTRA, 0, nil, tp)
return mg:IsExists(M.matfilter1, 1, nil, mg, tp)
end
function M.lkop(e,tp,eg,ep,ev,re,r,rp,c)
local mg = Duel.GetMatchingGroup(M.fusionfilter, tp, LOCATION_EXTRA, 0, nil, tp)
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_CONFIRM)
local fc1 = mg:FilterSelect(tp, M.matfilter1, 1, 1, nil, mg, tp):GetFirst()
local matg1 = Duel.GetMatchingGroup(M.fmatcheck, tp, LOCATION_HAND+LOCATION_MZONE, 0, nil, fc1)
local fc2 = mg:FilterSelect(tp, M.matfilter2, 1, 1, fc1, matg1, fc1:GetCode(), tp):GetFirst()
local matg2 = Duel.GetMatchingGroup(M.fmatcheck2, tp, LOCATION_HAND+LOCATION_MZONE, 0, nil, fc2, matg1)
Duel.ConfirmCards(1-tp, Group.FromCards(fc1, fc2))
--
-- 排除原先matg1中的不可用素材
matg1 = Duel.GetMatchingGroup(M.fmatcheck2, tp, LOCATION_HAND+LOCATION_MZONE, 0, nil, fc1, matg2)
-- 对两组素材中共有的卡进行处理
local same = matg1:Filter(M.samefilter, nil, matg2)
if same:GetCount() == 1 then
same = same:GetFirst()
if matg2:GetCount() == 1 then
matg1:RemoveCard(same)
elseif matg1:GetCount() == 1 then
matg2:RemoveCard(same)
end
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_LMATERIAL)
local dis1 = matg1:Select(tp, 1, 1, nil)
local dis2 = matg2:FilterSelect(tp, M.fmatcheck2, 1, 1, dis1:GetFirst(), fc2, dis1)
--
dis1:Merge(dis2)
c:SetMaterial(dis1)
Duel.SendtoGrave(dis1, REASON_MATERIAL+REASON_LINK)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_BE_LINK_MATERIAL)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetReset(RESET_EVENT+0xfe0000+RESET_PHASE+PHASE_END)
e1:SetValue(1)
c:RegisterEffect(e1, true)
end
--
function M.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk == 0 then return Duel.IsExistingMatchingCard(Card.IsAbleToGraveAsCost, tp, LOCATION_HAND, 0, 1, nil) end
Duel.DiscardHand(tp, Card.IsAbleToGraveAsCost, 1, 1, REASON_COST)
end
function M.spfilter1(c,e,tp,m,f,chkf)
return c:IsType(TYPE_FUSION) and (not f or f(c))
and c:IsCanBeSpecialSummoned(e, SUMMON_TYPE_FUSION, tp, false, false) and c:CheckFusionMaterial(m, nil, chkf)
end
function M.spfilter2(c, e, tp, m, f, chkf, this_card)
return c:IsType(TYPE_FUSION) and c:IsRace(RACE_PLANT) and (not f or f(c))
and c:IsCanBeSpecialSummoned(e, SUMMON_TYPE_FUSION, tp, false, false) and c:CheckFusionMaterial(m, this_card, chkf)
end
function M.mfilter1(c, e)
return c:IsType(TYPE_MONSTER) and c:IsLocation(LOCATION_HAND+LOCATION_GRAVE+LOCATION_ONFIELD)
and c:IsAbleToDeck() and not c:IsImmuneToEffect(e) and c:IsCanBeFusionMaterial()
end
function M.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk == 0 then
local chkf = nil
local mg = Duel.GetMatchingGroup(Card.IsType, tp, LOCATION_HAND+LOCATION_GRAVE+LOCATION_ONFIELD, 0, nil, TYPE_MONSTER)
local mg1 = mg:Filter(M.mfilter1, nil, e)
local res = Duel.IsExistingMatchingCard(M.spfilter1, tp, LOCATION_EXTRA, 0, 1, nil, e, tp, mg1, nil, chkf)
if res then return true end
local c = e:GetHandler()
local mg2 = Duel.GetMatchingGroup(M.mfilter1, tp, 0, LOCATION_GRAVE+LOCATION_ONFIELD, nil, e)
mg2:AddCard(c)
res = Duel.IsExistingMatchingCard(M.spfilter2, tp, LOCATION_EXTRA, 0, 1, nil, e, tp, mg2, nil, chkf, c)
if not res then
local ce = Duel.GetChainMaterial(tp)
if ce ~= nil then
local fgroup = ce:GetTarget()
local mg3 = fgroup(ce, e, tp)
local mf = ce:GetValue()
res = Duel.IsExistingMatchingCard(M.spfilter1, tp, LOCATION_EXTRA, 0, 1, nil, e, tp, mg3, mf, chkf)
end
end
return res
end
Duel.SetOperationInfo(0, CATEGORY_SPECIAL_SUMMON, nil, 1, tp, LOCATION_EXTRA)
end
function M.spop(e,tp,eg,ep,ev,re,r,rp)
local chkf = nil
local mg = Duel.GetMatchingGroup(Card.IsType, tp, LOCATION_HAND+LOCATION_GRAVE+LOCATION_ONFIELD, 0, nil, TYPE_MONSTER)
local mg1 = mg:Filter(M.mfilter1, nil, e)
local sg1 = Duel.GetMatchingGroup(M.spfilter1, tp, LOCATION_EXTRA, 0, nil, e, tp, mg1, nil, chkf)
--
local c = e:GetHandler()
local mg2 = Duel.GetMatchingGroup(M.mfilter1, tp, 0, LOCATION_GRAVE+LOCATION_ONFIELD, nil, e)
mg2:AddCard(c)
local sg2 = Duel.GetMatchingGroup(M.spfilter2, tp, LOCATION_EXTRA, 0, nil, e, tp, mg2, nil, chkf, c)
--
sg1:Merge(sg2)
--
local mg3 = nil
local sg3 = nil
local ce = Duel.GetChainMaterial(tp)
if ce ~= nil then
local fgroup = ce:GetTarget()
mg3 = fgroup(ce,e,tp)
local mf = ce:GetValue()
sg3 = Duel.GetMatchingGroup(M.spfilter1, tp, LOCATION_EXTRA, 0, nil, e, tp, mg3, mf, chkf)
end
if sg1:GetCount() > 0 or (sg3 ~= nil and sg3:GetCount() > 0) then
local sg = sg1:Clone()
if sg3 then sg:Merge(sg3) end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_SPSUMMON)
local tg = sg:Select(tp, 1, 1, nil)
local tc = tg:GetFirst()
if sg1:IsContains(tc) and (sg3 == nil or not sg3:IsContains(tc) or not Duel.SelectYesNo(tp, ce:GetDescription())) then
if tc:IsRace(RACE_PLANT) and sg2:IsContains(tc) and Duel.SelectYesNo(tp, aux.Stringid(Mid, 3)) then
local mat1 = Duel.SelectFusionMaterial(tp, tc, mg2, c, chkf)
tc:SetMaterial(mat1)
Duel.ConfirmCards(1-tp, mat1)
Duel.SendtoDeck(mat1, nil, 2, REASON_EFFECT+REASON_MATERIAL+REASON_FUSION)
else
local mat2 = Duel.SelectFusionMaterial(tp, tc, mg1, nil, chkf)
tc:SetMaterial(mat2)
Duel.ConfirmCards(1-tp, mat2)
Duel.SendtoDeck(mat2, nil, 2, REASON_EFFECT+REASON_MATERIAL+REASON_FUSION)
end
Duel.BreakEffect()
Duel.SpecialSummon(tc, SUMMON_TYPE_FUSION, tp, tp, false, false, POS_FACEUP)
else
local mat = Duel.SelectFusionMaterial(tp, tc, mg3, nil, chkf)
local fop = ce:GetOperation()
fop(ce, e, tp, tc, mat)
end
tc:CompleteProcedure()
end
end | gpl-2.0 |
bn7/darkstar | scripts/zones/Outer_Horutoto_Ruins/npcs/Grounds_Tome.lua | 30 | 1115 | -----------------------------------
-- Area: Outer Horutoto Ruins
-- NPC: Grounds Tome
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startGov(GOV_EVENT_OUTER_HORUTOTO_RUINS,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,663,664,665,666,667,668,669,670,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,663,664,665,666,667,668,669,670,0,0,GOV_MSG_OUTER_HORUTOTO_RUINS);
end;
| gpl-3.0 |
shizhai/wprobe | build_dir/target-mips_r2_uClibc-0.9.33.2/luci/contrib/luasrcdiet/lua/optlex.lua | 125 | 31588 | --[[--------------------------------------------------------------------
optlex.lua: does lexer-based optimizations
This file is part of LuaSrcDiet.
Copyright (c) 2008 Kein-Hong Man <khman@users.sf.net>
The COPYRIGHT file describes the conditions
under which this software may be distributed.
See the ChangeLog for more information.
----------------------------------------------------------------------]]
--[[--------------------------------------------------------------------
-- NOTES:
-- * For more lexer-based optimization ideas, see the TODO items or
-- look at technotes.txt.
-- * TODO: general string delimiter conversion optimizer
-- * TODO: (numbers) warn if overly significant digit
----------------------------------------------------------------------]]
local base = _G
local string = require "string"
module "optlex"
local match = string.match
local sub = string.sub
local find = string.find
local rep = string.rep
local print
------------------------------------------------------------------------
-- variables and data structures
------------------------------------------------------------------------
-- error function, can override by setting own function into module
error = base.error
warn = {} -- table for warning flags
local stoks, sinfos, stoklns -- source lists
local is_realtoken = { -- significant (grammar) tokens
TK_KEYWORD = true,
TK_NAME = true,
TK_NUMBER = true,
TK_STRING = true,
TK_LSTRING = true,
TK_OP = true,
TK_EOS = true,
}
local is_faketoken = { -- whitespace (non-grammar) tokens
TK_COMMENT = true,
TK_LCOMMENT = true,
TK_EOL = true,
TK_SPACE = true,
}
local opt_details -- for extra information
------------------------------------------------------------------------
-- true if current token is at the start of a line
-- * skips over deleted tokens via recursion
------------------------------------------------------------------------
local function atlinestart(i)
local tok = stoks[i - 1]
if i <= 1 or tok == "TK_EOL" then
return true
elseif tok == "" then
return atlinestart(i - 1)
end
return false
end
------------------------------------------------------------------------
-- true if current token is at the end of a line
-- * skips over deleted tokens via recursion
------------------------------------------------------------------------
local function atlineend(i)
local tok = stoks[i + 1]
if i >= #stoks or tok == "TK_EOL" or tok == "TK_EOS" then
return true
elseif tok == "" then
return atlineend(i + 1)
end
return false
end
------------------------------------------------------------------------
-- counts comment EOLs inside a long comment
-- * in order to keep line numbering, EOLs need to be reinserted
------------------------------------------------------------------------
local function commenteols(lcomment)
local sep = #match(lcomment, "^%-%-%[=*%[")
local z = sub(lcomment, sep + 1, -(sep - 1)) -- remove delims
local i, c = 1, 0
while true do
local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i)
if not p then break end -- if no matches, done
i = p + 1
c = c + 1
if #s > 0 and r ~= s then -- skip CRLF or LFCR
i = i + 1
end
end
return c
end
------------------------------------------------------------------------
-- compares two tokens (i, j) and returns the whitespace required
-- * important! see technotes.txt for more information
-- * only two grammar/real tokens are being considered
-- * if "", no separation is needed
-- * if " ", then at least one whitespace (or EOL) is required
------------------------------------------------------------------------
local function checkpair(i, j)
local match = match
local t1, t2 = stoks[i], stoks[j]
--------------------------------------------------------------------
if t1 == "TK_STRING" or t1 == "TK_LSTRING" or
t2 == "TK_STRING" or t2 == "TK_LSTRING" then
return ""
--------------------------------------------------------------------
elseif t1 == "TK_OP" or t2 == "TK_OP" then
if (t1 == "TK_OP" and (t2 == "TK_KEYWORD" or t2 == "TK_NAME")) or
(t2 == "TK_OP" and (t1 == "TK_KEYWORD" or t1 == "TK_NAME")) then
return ""
end
if t1 == "TK_OP" and t2 == "TK_OP" then
-- for TK_OP/TK_OP pairs, see notes in technotes.txt
local op, op2 = sinfos[i], sinfos[j]
if (match(op, "^%.%.?$") and match(op2, "^%.")) or
(match(op, "^[~=<>]$") and op2 == "=") or
(op == "[" and (op2 == "[" or op2 == "=")) then
return " "
end
return ""
end
-- "TK_OP" + "TK_NUMBER" case
local op = sinfos[i]
if t2 == "TK_OP" then op = sinfos[j] end
if match(op, "^%.%.?%.?$") then
return " "
end
return ""
--------------------------------------------------------------------
else-- "TK_KEYWORD" | "TK_NAME" | "TK_NUMBER" then
return " "
--------------------------------------------------------------------
end
end
------------------------------------------------------------------------
-- repack tokens, removing deletions caused by optimization process
------------------------------------------------------------------------
local function repack_tokens()
local dtoks, dinfos, dtoklns = {}, {}, {}
local j = 1
for i = 1, #stoks do
local tok = stoks[i]
if tok ~= "" then
dtoks[j], dinfos[j], dtoklns[j] = tok, sinfos[i], stoklns[i]
j = j + 1
end
end
stoks, sinfos, stoklns = dtoks, dinfos, dtoklns
end
------------------------------------------------------------------------
-- number optimization
-- * optimization using string formatting functions is one way of doing
-- this, but here, we consider all cases and handle them separately
-- (possibly an idiotic approach...)
-- * scientific notation being generated is not in canonical form, this
-- may or may not be a bad thing, feedback welcome
-- * note: intermediate portions need to fit into a normal number range
-- * optimizations can be divided based on number patterns:
-- * hexadecimal:
-- (1) no need to remove leading zeros, just skip to (2)
-- (2) convert to integer if size equal or smaller
-- * change if equal size -> lose the 'x' to reduce entropy
-- (3) number is then processed as an integer
-- (4) note: does not make 0[xX] consistent
-- * integer:
-- (1) note: includes anything with trailing ".", ".0", ...
-- (2) remove useless fractional part, if present, e.g. 123.000
-- (3) remove leading zeros, e.g. 000123
-- (4) switch to scientific if shorter, e.g. 123000 -> 123e3
-- * with fraction:
-- (1) split into digits dot digits
-- (2) if no integer portion, take as zero (can omit later)
-- (3) handle degenerate .000 case, after which the fractional part
-- must be non-zero (if zero, it's matched as an integer)
-- (4) remove trailing zeros for fractional portion
-- (5) p.q where p > 0 and q > 0 cannot be shortened any more
-- (6) otherwise p == 0 and the form is .q, e.g. .000123
-- (7) if scientific shorter, convert, e.g. .000123 -> 123e-6
-- * scientific:
-- (1) split into (digits dot digits) [eE] ([+-] digits)
-- (2) if significand has ".", shift it out so it becomes an integer
-- (3) if significand is zero, just use zero
-- (4) remove leading zeros for significand
-- (5) shift out trailing zeros for significand
-- (6) examine exponent and determine which format is best:
-- integer, with fraction, scientific
------------------------------------------------------------------------
local function do_number(i)
local before = sinfos[i] -- 'before'
local z = before -- working representation
local y -- 'after', if better
--------------------------------------------------------------------
if match(z, "^0[xX]") then -- hexadecimal number
local v = base.tostring(base.tonumber(z))
if #v <= #z then
z = v -- change to integer, AND continue
else
return -- no change; stick to hex
end
end
--------------------------------------------------------------------
if match(z, "^%d+%.?0*$") then -- integer or has useless frac
z = match(z, "^(%d+)%.?0*$") -- int portion only
if z + 0 > 0 then
z = match(z, "^0*([1-9]%d*)$") -- remove leading zeros
local v = #match(z, "0*$")
local nv = base.tostring(v)
if v > #nv + 1 then -- scientific is shorter
z = sub(z, 1, #z - v).."e"..nv
end
y = z
else
y = "0" -- basic zero
end
--------------------------------------------------------------------
elseif not match(z, "[eE]") then -- number with fraction part
local p, q = match(z, "^(%d*)%.(%d+)$") -- split
if p == "" then p = 0 end -- int part zero
if q + 0 == 0 and p == 0 then
y = "0" -- degenerate .000 case
else
-- now, q > 0 holds and p is a number
local v = #match(q, "0*$") -- remove trailing zeros
if v > 0 then
q = sub(q, 1, #q - v)
end
-- if p > 0, nothing else we can do to simplify p.q case
if p + 0 > 0 then
y = p.."."..q
else
y = "."..q -- tentative, e.g. .000123
local v = #match(q, "^0*") -- # leading spaces
local w = #q - v -- # significant digits
local nv = base.tostring(#q)
-- e.g. compare 123e-6 versus .000123
if w + 2 + #nv < 1 + #q then
y = sub(q, -w).."e-"..nv
end
end
end
--------------------------------------------------------------------
else -- scientific number
local sig, ex = match(z, "^([^eE]+)[eE]([%+%-]?%d+)$")
ex = base.tonumber(ex)
-- if got ".", shift out fractional portion of significand
local p, q = match(sig, "^(%d*)%.(%d*)$")
if p then
ex = ex - #q
sig = p..q
end
if sig + 0 == 0 then
y = "0" -- basic zero
else
local v = #match(sig, "^0*") -- remove leading zeros
sig = sub(sig, v + 1)
v = #match(sig, "0*$") -- shift out trailing zeros
if v > 0 then
sig = sub(sig, 1, #sig - v)
ex = ex + v
end
-- examine exponent and determine which format is best
local nex = base.tostring(ex)
if ex == 0 then -- it's just an integer
y = sig
elseif ex > 0 and (ex <= 1 + #nex) then -- a number
y = sig..rep("0", ex)
elseif ex < 0 and (ex >= -#sig) then -- fraction, e.g. .123
v = #sig + ex
y = sub(sig, 1, v).."."..sub(sig, v + 1)
elseif ex < 0 and (#nex >= -ex - #sig) then
-- e.g. compare 1234e-5 versus .01234
-- gives: #sig + 1 + #nex >= 1 + (-ex - #sig) + #sig
-- -> #nex >= -ex - #sig
v = -ex - #sig
y = "."..rep("0", v)..sig
else -- non-canonical scientific representation
y = sig.."e"..ex
end
end--if sig
end
--------------------------------------------------------------------
if y and y ~= sinfos[i] then
if opt_details then
print("<number> (line "..stoklns[i]..") "..sinfos[i].." -> "..y)
opt_details = opt_details + 1
end
sinfos[i] = y
end
end
------------------------------------------------------------------------
-- string optimization
-- * note: works on well-formed strings only!
-- * optimizations on characters can be summarized as follows:
-- \a\b\f\n\r\t\v -- no change
-- \\ -- no change
-- \"\' -- depends on delim, other can remove \
-- \[\] -- remove \
-- \<char> -- general escape, remove \
-- \<eol> -- normalize the EOL only
-- \ddd -- if \a\b\f\n\r\t\v, change to latter
-- if other < ascii 32, keep ddd but zap leading zeros
-- if >= ascii 32, translate it into the literal, then also
-- do escapes for \\,\",\' cases
-- <other> -- no change
-- * switch delimiters if string becomes shorter
------------------------------------------------------------------------
local function do_string(I)
local info = sinfos[I]
local delim = sub(info, 1, 1) -- delimiter used
local ndelim = (delim == "'") and '"' or "'" -- opposite " <-> '
local z = sub(info, 2, -2) -- actual string
local i = 1
local c_delim, c_ndelim = 0, 0 -- "/' counts
--------------------------------------------------------------------
while i <= #z do
local c = sub(z, i, i)
----------------------------------------------------------------
if c == "\\" then -- escaped stuff
local j = i + 1
local d = sub(z, j, j)
local p = find("abfnrtv\\\n\r\"\'0123456789", d, 1, true)
------------------------------------------------------------
if not p then -- \<char> -- remove \
z = sub(z, 1, i - 1)..sub(z, j)
i = i + 1
------------------------------------------------------------
elseif p <= 8 then -- \a\b\f\n\r\t\v\\
i = i + 2 -- no change
------------------------------------------------------------
elseif p <= 10 then -- \<eol> -- normalize EOL
local eol = sub(z, j, j + 1)
if eol == "\r\n" or eol == "\n\r" then
z = sub(z, 1, i).."\n"..sub(z, j + 2)
elseif p == 10 then -- \r case
z = sub(z, 1, i).."\n"..sub(z, j + 1)
end
i = i + 2
------------------------------------------------------------
elseif p <= 12 then -- \"\' -- remove \ for ndelim
if d == delim then
c_delim = c_delim + 1
i = i + 2
else
c_ndelim = c_ndelim + 1
z = sub(z, 1, i - 1)..sub(z, j)
i = i + 1
end
------------------------------------------------------------
else -- \ddd -- various steps
local s = match(z, "^(%d%d?%d?)", j)
j = i + 1 + #s -- skip to location
local cv = s + 0
local cc = string.char(cv)
local p = find("\a\b\f\n\r\t\v", cc, 1, true)
if p then -- special escapes
s = "\\"..sub("abfnrtv", p, p)
elseif cv < 32 then -- normalized \ddd
s = "\\"..cv
elseif cc == delim then -- \<delim>
s = "\\"..cc
c_delim = c_delim + 1
elseif cc == "\\" then -- \\
s = "\\\\"
else -- literal character
s = cc
if cc == ndelim then
c_ndelim = c_ndelim + 1
end
end
z = sub(z, 1, i - 1)..s..sub(z, j)
i = i + #s
------------------------------------------------------------
end--if p
----------------------------------------------------------------
else-- c ~= "\\" -- <other> -- no change
i = i + 1
if c == ndelim then -- count ndelim, for switching delimiters
c_ndelim = c_ndelim + 1
end
----------------------------------------------------------------
end--if c
end--while
--------------------------------------------------------------------
-- switching delimiters, a long-winded derivation:
-- (1) delim takes 2+2*c_delim bytes, ndelim takes c_ndelim bytes
-- (2) delim becomes c_delim bytes, ndelim becomes 2+2*c_ndelim bytes
-- simplifying the condition (1)>(2) --> c_delim > c_ndelim
if c_delim > c_ndelim then
i = 1
while i <= #z do
local p, q, r = find(z, "([\'\"])", i)
if not p then break end
if r == delim then -- \<delim> -> <delim>
z = sub(z, 1, p - 2)..sub(z, p)
i = p
else-- r == ndelim -- <ndelim> -> \<ndelim>
z = sub(z, 1, p - 1).."\\"..sub(z, p)
i = p + 2
end
end--while
delim = ndelim -- actually change delimiters
end
--------------------------------------------------------------------
z = delim..z..delim
if z ~= sinfos[I] then
if opt_details then
print("<string> (line "..stoklns[I]..") "..sinfos[I].." -> "..z)
opt_details = opt_details + 1
end
sinfos[I] = z
end
end
------------------------------------------------------------------------
-- long string optimization
-- * note: warning flagged if trailing whitespace found, not trimmed
-- * remove first optional newline
-- * normalize embedded newlines
-- * reduce '=' separators in delimiters if possible
------------------------------------------------------------------------
local function do_lstring(I)
local info = sinfos[I]
local delim1 = match(info, "^%[=*%[") -- cut out delimiters
local sep = #delim1
local delim2 = sub(info, -sep, -1)
local z = sub(info, sep + 1, -(sep + 1)) -- lstring without delims
local y = ""
local i = 1
--------------------------------------------------------------------
while true do
local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i)
-- deal with a single line
local ln
if not p then
ln = sub(z, i)
elseif p >= i then
ln = sub(z, i, p - 1)
end
if ln ~= "" then
-- flag a warning if there are trailing spaces, won't optimize!
if match(ln, "%s+$") then
warn.lstring = "trailing whitespace in long string near line "..stoklns[I]
end
y = y..ln
end
if not p then -- done if no more EOLs
break
end
-- deal with line endings, normalize them
i = p + 1
if p then
if #s > 0 and r ~= s then -- skip CRLF or LFCR
i = i + 1
end
-- skip first newline, which can be safely deleted
if not(i == 1 and i == p) then
y = y.."\n"
end
end
end--while
--------------------------------------------------------------------
-- handle possible deletion of one or more '=' separators
if sep >= 3 then
local chk, okay = sep - 1
-- loop to test ending delimiter with less of '=' down to zero
while chk >= 2 do
local delim = "%]"..rep("=", chk - 2).."%]"
if not match(y, delim) then okay = chk end
chk = chk - 1
end
if okay then -- change delimiters
sep = rep("=", okay - 2)
delim1, delim2 = "["..sep.."[", "]"..sep.."]"
end
end
--------------------------------------------------------------------
sinfos[I] = delim1..y..delim2
end
------------------------------------------------------------------------
-- long comment optimization
-- * note: does not remove first optional newline
-- * trim trailing whitespace
-- * normalize embedded newlines
-- * reduce '=' separators in delimiters if possible
------------------------------------------------------------------------
local function do_lcomment(I)
local info = sinfos[I]
local delim1 = match(info, "^%-%-%[=*%[") -- cut out delimiters
local sep = #delim1
local delim2 = sub(info, -sep, -1)
local z = sub(info, sep + 1, -(sep - 1)) -- comment without delims
local y = ""
local i = 1
--------------------------------------------------------------------
while true do
local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i)
-- deal with a single line, extract and check trailing whitespace
local ln
if not p then
ln = sub(z, i)
elseif p >= i then
ln = sub(z, i, p - 1)
end
if ln ~= "" then
-- trim trailing whitespace if non-empty line
local ws = match(ln, "%s*$")
if #ws > 0 then ln = sub(ln, 1, -(ws + 1)) end
y = y..ln
end
if not p then -- done if no more EOLs
break
end
-- deal with line endings, normalize them
i = p + 1
if p then
if #s > 0 and r ~= s then -- skip CRLF or LFCR
i = i + 1
end
y = y.."\n"
end
end--while
--------------------------------------------------------------------
-- handle possible deletion of one or more '=' separators
sep = sep - 2
if sep >= 3 then
local chk, okay = sep - 1
-- loop to test ending delimiter with less of '=' down to zero
while chk >= 2 do
local delim = "%]"..rep("=", chk - 2).."%]"
if not match(y, delim) then okay = chk end
chk = chk - 1
end
if okay then -- change delimiters
sep = rep("=", okay - 2)
delim1, delim2 = "--["..sep.."[", "]"..sep.."]"
end
end
--------------------------------------------------------------------
sinfos[I] = delim1..y..delim2
end
------------------------------------------------------------------------
-- short comment optimization
-- * trim trailing whitespace
------------------------------------------------------------------------
local function do_comment(i)
local info = sinfos[i]
local ws = match(info, "%s*$") -- just look from end of string
if #ws > 0 then
info = sub(info, 1, -(ws + 1)) -- trim trailing whitespace
end
sinfos[i] = info
end
------------------------------------------------------------------------
-- returns true if string found in long comment
-- * this is a feature to keep copyright or license texts
------------------------------------------------------------------------
local function keep_lcomment(opt_keep, info)
if not opt_keep then return false end -- option not set
local delim1 = match(info, "^%-%-%[=*%[") -- cut out delimiters
local sep = #delim1
local delim2 = sub(info, -sep, -1)
local z = sub(info, sep + 1, -(sep - 1)) -- comment without delims
if find(z, opt_keep, 1, true) then -- try to match
return true
end
end
------------------------------------------------------------------------
-- main entry point
-- * currently, lexer processing has 2 passes
-- * processing is done on a line-oriented basis, which is easier to
-- grok due to the next point...
-- * since there are various options that can be enabled or disabled,
-- processing is a little messy or convoluted
------------------------------------------------------------------------
function optimize(option, toklist, semlist, toklnlist)
--------------------------------------------------------------------
-- set option flags
--------------------------------------------------------------------
local opt_comments = option["opt-comments"]
local opt_whitespace = option["opt-whitespace"]
local opt_emptylines = option["opt-emptylines"]
local opt_eols = option["opt-eols"]
local opt_strings = option["opt-strings"]
local opt_numbers = option["opt-numbers"]
local opt_keep = option.KEEP
opt_details = option.DETAILS and 0 -- upvalues for details display
print = print or base.print
if opt_eols then -- forced settings, otherwise won't work properly
opt_comments = true
opt_whitespace = true
opt_emptylines = true
end
--------------------------------------------------------------------
-- variable initialization
--------------------------------------------------------------------
stoks, sinfos, stoklns -- set source lists
= toklist, semlist, toklnlist
local i = 1 -- token position
local tok, info -- current token
local prev -- position of last grammar token
-- on same line (for TK_SPACE stuff)
--------------------------------------------------------------------
-- changes a token, info pair
--------------------------------------------------------------------
local function settoken(tok, info, I)
I = I or i
stoks[I] = tok or ""
sinfos[I] = info or ""
end
--------------------------------------------------------------------
-- processing loop (PASS 1)
--------------------------------------------------------------------
while true do
tok, info = stoks[i], sinfos[i]
----------------------------------------------------------------
local atstart = atlinestart(i) -- set line begin flag
if atstart then prev = nil end
----------------------------------------------------------------
if tok == "TK_EOS" then -- end of stream/pass
break
----------------------------------------------------------------
elseif tok == "TK_KEYWORD" or -- keywords, identifiers,
tok == "TK_NAME" or -- operators
tok == "TK_OP" then
-- TK_KEYWORD and TK_OP can't be optimized without a big
-- optimization framework; it would be more of an optimizing
-- compiler, not a source code compressor
-- TK_NAME that are locals needs parser to analyze/optimize
prev = i
----------------------------------------------------------------
elseif tok == "TK_NUMBER" then -- numbers
if opt_numbers then
do_number(i) -- optimize
end
prev = i
----------------------------------------------------------------
elseif tok == "TK_STRING" or -- strings, long strings
tok == "TK_LSTRING" then
if opt_strings then
if tok == "TK_STRING" then
do_string(i) -- optimize
else
do_lstring(i) -- optimize
end
end
prev = i
----------------------------------------------------------------
elseif tok == "TK_COMMENT" then -- short comments
if opt_comments then
if i == 1 and sub(info, 1, 1) == "#" then
-- keep shbang comment, trim whitespace
do_comment(i)
else
-- safe to delete, as a TK_EOL (or TK_EOS) always follows
settoken() -- remove entirely
end
elseif opt_whitespace then -- trim whitespace only
do_comment(i)
end
----------------------------------------------------------------
elseif tok == "TK_LCOMMENT" then -- long comments
if keep_lcomment(opt_keep, info) then
------------------------------------------------------------
-- if --keep, we keep a long comment if <msg> is found;
-- this is a feature to keep copyright or license texts
if opt_whitespace then -- trim whitespace only
do_lcomment(i)
end
prev = i
elseif opt_comments then
local eols = commenteols(info)
------------------------------------------------------------
-- prepare opt_emptylines case first, if a disposable token
-- follows, current one is safe to dump, else keep a space;
-- it is implied that the operation is safe for '-', because
-- current is a TK_LCOMMENT, and must be separate from a '-'
if is_faketoken[stoks[i + 1]] then
settoken() -- remove entirely
tok = ""
else
settoken("TK_SPACE", " ")
end
------------------------------------------------------------
-- if there are embedded EOLs to keep and opt_emptylines is
-- disabled, then switch the token into one or more EOLs
if not opt_emptylines and eols > 0 then
settoken("TK_EOL", rep("\n", eols))
end
------------------------------------------------------------
-- if optimizing whitespaces, force reinterpretation of the
-- token to give a chance for the space to be optimized away
if opt_whitespace and tok ~= "" then
i = i - 1 -- to reinterpret
end
------------------------------------------------------------
else -- disabled case
if opt_whitespace then -- trim whitespace only
do_lcomment(i)
end
prev = i
end
----------------------------------------------------------------
elseif tok == "TK_EOL" then -- line endings
if atstart and opt_emptylines then
settoken() -- remove entirely
elseif info == "\r\n" or info == "\n\r" then
-- normalize the rest of the EOLs for CRLF/LFCR only
-- (note that TK_LCOMMENT can change into several EOLs)
settoken("TK_EOL", "\n")
end
----------------------------------------------------------------
elseif tok == "TK_SPACE" then -- whitespace
if opt_whitespace then
if atstart or atlineend(i) then
-- delete leading and trailing whitespace
settoken() -- remove entirely
else
------------------------------------------------------------
-- at this point, since leading whitespace have been removed,
-- there should be a either a real token or a TK_LCOMMENT
-- prior to hitting this whitespace; the TK_LCOMMENT case
-- only happens if opt_comments is disabled; so prev ~= nil
local ptok = stoks[prev]
if ptok == "TK_LCOMMENT" then
-- previous TK_LCOMMENT can abut with anything
settoken() -- remove entirely
else
-- prev must be a grammar token; consecutive TK_SPACE
-- tokens is impossible when optimizing whitespace
local ntok = stoks[i + 1]
if is_faketoken[ntok] then
-- handle special case where a '-' cannot abut with
-- either a short comment or a long comment
if (ntok == "TK_COMMENT" or ntok == "TK_LCOMMENT") and
ptok == "TK_OP" and sinfos[prev] == "-" then
-- keep token
else
settoken() -- remove entirely
end
else--is_realtoken
-- check a pair of grammar tokens, if can abut, then
-- delete space token entirely, otherwise keep one space
local s = checkpair(prev, i + 1)
if s == "" then
settoken() -- remove entirely
else
settoken("TK_SPACE", " ")
end
end
end
------------------------------------------------------------
end
end
----------------------------------------------------------------
else
error("unidentified token encountered")
end
----------------------------------------------------------------
i = i + 1
end--while
repack_tokens()
--------------------------------------------------------------------
-- processing loop (PASS 2)
--------------------------------------------------------------------
if opt_eols then
i = 1
-- aggressive EOL removal only works with most non-grammar tokens
-- optimized away because it is a rather simple scheme -- basically
-- it just checks 'real' token pairs around EOLs
if stoks[1] == "TK_COMMENT" then
-- first comment still existing must be shbang, skip whole line
i = 3
end
while true do
tok, info = stoks[i], sinfos[i]
--------------------------------------------------------------
if tok == "TK_EOS" then -- end of stream/pass
break
--------------------------------------------------------------
elseif tok == "TK_EOL" then -- consider each TK_EOL
local t1, t2 = stoks[i - 1], stoks[i + 1]
if is_realtoken[t1] and is_realtoken[t2] then -- sanity check
local s = checkpair(i - 1, i + 1)
if s == "" then
settoken() -- remove entirely
end
end
end--if tok
--------------------------------------------------------------
i = i + 1
end--while
repack_tokens()
end
--------------------------------------------------------------------
if opt_details and opt_details > 0 then print() end -- spacing
return stoks, sinfos, stoklns
end
| gpl-2.0 |
HuangYuNan/thcsvr | expansions/script/c10006.lua | 1 | 2678 |
--百鬼王 伊吹萃香
function c10006.initial_effect(c)
--xyz summon
c:EnableReviveLimit()
aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsSetCard,0x208),8,2)
--atk up
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(10006,0))
e1:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DEFCHANGE)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c10006.cost)
e1:SetOperation(c10006.operation)
c:RegisterEffect(e1)
--spsummon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(10006,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetCode(EVENT_DESTROYED)
e3:SetCondition(c10006.spcon)
e3:SetTarget(c10006.sptg)
e3:SetOperation(c10006.spop)
c:RegisterEffect(e3)
end
function c10006.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c10006.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local bd=c:GetDefense()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(bd)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_UPDATE_DEFENSE)
e2:SetValue(-bd)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
c:RegisterEffect(e2)
end
function c10006.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_MZONE) and c:IsReason(REASON_EFFECT) and c:GetOverlayCount()~=0
end
function c10006.spfilter(c,e,tp)
return c:IsRace(RACE_ZOMBIE) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c10006.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and c10006.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c10006.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c10006.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,tp,LOCATION_GRAVE)
end
function c10006.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not tc:IsRelateToEffect(e) or Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
if tc then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
Dysoch/DyWorld | DyWorld-Dynamics/data/core/items/satellites-dyson.lua | 1 | 1086 |
for i = 1,5 do
data:extend({
{
type = "item",
name = "basic-dyson-satellite-"..i,
icons = {
{
icon = "__base__/graphics/icons/satellite.png",
},
},
icon_size = 64, icon_mipmaps = 4,
subgroup = DyDs.."satellites-3",
order = (-1 + i),
stack_size = 1,
},
{
type = "item",
name = "advanced-dyson-satellite-"..i,
icons = {
{
icon = "__base__/graphics/icons/satellite.png",
},
},
icon_size = 64, icon_mipmaps = 4,
subgroup = DyDs.."satellites-3",
order = (i+4),
stack_size = 1,
},
{
type = "item",
name = "basic-dyson-sphere-comp-"..i,
icons = {
{
icon = "__base__/graphics/icons/satellite.png",
},
},
icon_size = 64, icon_mipmaps = 4,
subgroup = DyDs.."satellites-4",
order = (-1 + i),
stack_size = 1,
},
{
type = "item",
name = "advanced-dyson-sphere-comp-"..i,
icons = {
{
icon = "__base__/graphics/icons/satellite.png",
},
},
icon_size = 64, icon_mipmaps = 4,
subgroup = DyDs.."satellites-4",
order = (i+4),
stack_size = 1,
},
})
end | gpl-3.0 |
bn7/darkstar | scripts/zones/Kuftal_Tunnel/npcs/qm5.lua | 17 | 1466 | -----------------------------------
-- Area: Kuftal Tunnel
-- NPC: ???
-- Involved in Mission: Bastok 8-2
-----------------------------------
package.loaded["scripts/zones/Kuftal_Tunnel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Kuftal_Tunnel/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local missionStatus = player:getVar("MissionStatus");
if (player:getCurrentMission(BASTOK) == ENTER_THE_TALEKEEPER and missionStatus == 1) then
player:startEvent(0x00c);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (option == 0) then
if (csid == 0x00c) then
player:setVar("MissionStatus",2);
player:messageSpecial(FELL);
end
end
end; | gpl-3.0 |
bn7/darkstar | scripts/zones/The_Sanctuary_of_ZiTah/npcs/qm4.lua | 12 | 1829 | -----------------------------------
-- Area: The Sanctuary of Zitah
-- NPC: ???
-- Finishes Quest: Lovers in the Dusk
-- @zone 121
-----------------------------------
package.loaded["scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/weather");
require("scripts/zones/The_Sanctuary_of_ZiTah/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local LoversInTheDusk = player:getQuestStatus(BASTOK,LOVERS_IN_THE_DUSK);
local TOTD = VanadielTOTD();
if (TOTD == TIME_DUSK and LoversInTheDusk == QUEST_ACCEPTED) then
player:startEvent(0x00cc);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00cc) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17346);
else
player:addItem(17346);
player:messageSpecial(ITEM_OBTAINED,17346); -- Siren Flute
player:addFame(BASTOK,120);
player:completeQuest(BASTOK,LOVERS_IN_THE_DUSK);
end
end
end; | gpl-3.0 |
bn7/darkstar | scripts/zones/Al_Zahbi/npcs/Devonte.lua | 14 | 1034 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Devonte
-- Type: Standard NPC
-- @zone 48
-- @pos 29.449 -1 142.671
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00f9);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
yinjun322/quick-ng | quick/samples/coinflip/src/app/scenes/PlayLevelScene.lua | 8 | 1890 |
local Levels = import("..data.Levels")
local Board = import("..views.Board")
local AdBar = import("..views.AdBar")
local PlayLevelScene = class("PlayLevelScene", function()
return display.newScene("PlayLevelScene")
end)
function PlayLevelScene:ctor(levelIndex)
local bg = display.newSprite("#PlayLevelSceneBg.png")
-- make background sprite always align top
bg:setPosition(display.cx, display.top - bg:getContentSize().height / 2)
self:addChild(bg)
local title = display.newSprite("#Title.png", display.left + 150, display.top - 50)
title:setScale(0.5)
self:addChild(title)
local adBar = AdBar.new()
self:addChild(adBar)
local label = cc.ui.UILabel.new({
UILabelType = 1,
text = string.format("Level: %s", tostring(levelIndex)),
font = "UIFont.fnt",
x = display.left + 10,
y = display.bottom + 120,
align = cc.ui.TEXT_ALIGN_LEFT,
})
self:addChild(label)
self.board = Board.new(Levels.get(levelIndex))
self.board:addEventListener("LEVEL_COMPLETED", handler(self, self.onLevelCompleted))
self:addChild(self.board)
cc.ui.UIPushButton.new({normal = "#BackButton.png", pressed = "#BackButtonSelected.png"})
:align(display.CENTER, display.right - 100, display.bottom + 120)
:onButtonClicked(function()
app:enterChooseLevelScene()
end)
:addTo(self)
end
function PlayLevelScene:onLevelCompleted()
audio.playSound(GAME_SFX.levelCompleted)
local dialog = display.newSprite("#LevelCompletedDialogBg.png")
dialog:setPosition(display.cx, display.top + dialog:getContentSize().height / 2 + 40)
self:addChild(dialog)
transition.moveTo(dialog, {time = 0.7, y = display.top - dialog:getContentSize().height / 2 - 40, easing = "BOUNCEOUT"})
end
function PlayLevelScene:onEnter()
end
return PlayLevelScene
| mit |
Klius/love2dtestpong | libs/shine/boxblur.lua | 7 | 3038 | --[[
The MIT License (MIT)
Copyright (c) 2015 Matthias Richter
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.
]]--
return {
description = "Box blur shader with support for different horizontal and vertical blur size",
new = function(self)
self.radius_h, self.radius_v = 3, 3
self.canvas_h, self.canvas_v = love.graphics.newCanvas(), love.graphics.newCanvas()
self.shader = love.graphics.newShader[[
extern vec2 direction;
extern number radius;
vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _)
{
vec4 c = vec4(0.0f);
for (float i = -radius; i <= radius; i += 1.0f)
{
c += Texel(texture, tc + i * direction);
}
return c / (2.0f * radius + 1.0f) * color;
}
]]
self.shader:send("direction",{1.0,0.0}) --Not needed but may fix some errors if the shader is used somewhere else
end,
draw = function(self, func, ...)
local s = love.graphics.getShader()
local co = {love.graphics.getColor()}
-- draw scene
self:_render_to_canvas(self.canvas_h, func, ...)
love.graphics.setColor(co)
love.graphics.setShader(self.shader)
local b = love.graphics.getBlendMode()
love.graphics.setBlendMode('alpha', 'premultiplied')
-- first pass (horizontal blur)
self.shader:send('direction', {1 / love.graphics.getWidth(), 0})
self.shader:send('radius', math.floor(self.radius_h + .5))
self:_render_to_canvas(self.canvas_v,
love.graphics.draw, self.canvas_h, 0,0)
-- second pass (vertical blur)
self.shader:send('direction', {0, 1 / love.graphics.getHeight()})
self.shader:send('radius', math.floor(self.radius_v + .5))
love.graphics.draw(self.canvas_v, 0,0)
-- restore blendmode, shader and canvas
love.graphics.setBlendMode(b)
love.graphics.setShader(s)
end,
set = function(self, key, value)
local sz = math.floor(assert(tonumber(value), "Not a number: "..tostring(value)) + .5)
if key == "radius" then
self.radius_h, self.radius_v = sz, sz
elseif key == "radius_h" or key == "radius_v" then
self[key] = sz
else
error("Unknown property: " .. tostring(key))
end
return self
end
}
| gpl-3.0 |
nenonahar/GENERAAL | plugins/lock_inlin.lua | 2 | 1329 | --[[ -- تم التعديل و التعريب بواسطه @KNSLTHM
--[[
Dev @KNSLTHM
Dev @NAHAR2_BOT
CH > @NENO_CH
--]]
do
local function pre_process(msg)
local inline = 'mate:'..msg.to.id
if msg.text == '[unsupported]' and redis:get(inline) and not is_momod(msg) then
delete_msg(msg.id, ok_cb, true)
end
return msg
end
local function tshake(msg, matches)
if is_momod(msg) and matches[1] == "قفل" and matches[2] == "الانلاين" then
local inline = 'mate:'..msg.to.id
redis:set(inline, true)
return ""
end
if is_momod(msg) and matches[1] == "فتح" and matches[2] == "الانلاين" then
local inline = 'mate:'..msg.to.id
redis:del(inline)
return ""
end
end
return {
patterns ={
'^(قفل) (الانلاين)$',
'^(فتح) (الانلاين)$',
'^[#!/](قفل) (الانلاين)$',
'^[#!/](فتح) (الانلاين)$',
},
run = tshake,
pre_process = pre_process
}
end
--[[ -- تم التعديل و التعريب بواسطه @KNSLTHM
--[[
Dev @KNSLTHM
Dev @NAHAR2_BOT
CH > @NENO_CH
--]]
| gpl-2.0 |
Thadah/GarryWare13 | entities/entities/ware_trigger/cl_init.lua | 1 | 1940 |
include("shared.lua")
ENT.RenderGroup = RENDERGROUP_TRANSLUCENT
function ENT:Draw()
end
local function DrawBox(pos, mins, maxs, F, R, U)
local bld = (pos + mins.x * F + mins.y * R + mins.z * U):ToScreen()
local brd = (pos + mins.x * F + maxs.y * R + mins.z * U):ToScreen()
local frd = (pos + maxs.x * F + maxs.y * R + mins.z * U):ToScreen()
local fld = (pos + maxs.x * F + mins.y * R + mins.z * U):ToScreen()
local blu = (pos + mins.x * F + mins.y * R + maxs.z * U):ToScreen()
local bru = (pos + mins.x * F + maxs.y * R + maxs.z * U):ToScreen()
local fru = (pos + maxs.x * F + maxs.y * R + maxs.z * U):ToScreen()
local flu = (pos + maxs.x * F + mins.y * R + maxs.z * U):ToScreen()
surface.DrawLine(bld.x, bld.y, brd.x, brd.y)
surface.DrawLine(brd.x, brd.y, frd.x, frd.y)
surface.DrawLine(frd.x, frd.y, fld.x, fld.y)
surface.DrawLine(fld.x, fld.y, bld.x, bld.y)
surface.DrawLine(blu.x, blu.y, bru.x, bru.y)
surface.DrawLine(bru.x, bru.y, fru.x, fru.y)
surface.DrawLine(fru.x, fru.y, flu.x, flu.y)
surface.DrawLine(flu.x, flu.y, blu.x, blu.y)
surface.DrawLine(blu.x, blu.y, bld.x, bld.y)
surface.DrawLine(bru.x, bru.y, brd.x, brd.y)
surface.DrawLine(flu.x, flu.y, fld.x, fld.y)
surface.DrawLine(fru.x, fru.y, frd.x, frd.y)
end
hook.Add("HUDPaint", "WARE_TRIGGER_DEBUG", function()
if not GetConVar("ware_debug") or GetConVar("ware_debug"):GetInt() != 1 then
return
end
for _,v in pairs(ents.FindByClass("ware_trigger")) do
local mins = v:GetNWVector("mins")
local maxs = v:GetNWVector("maxs")
local vmax = v:GetNWVector("vmax")
if mins and maxs then
local pos = v:GetPos()
local F = v:GetForward()
local R = v:GetRight()
local U = v:GetUp()
surface.SetDrawColor(255, 255, 0, 255)
DrawBox(pos, mins, maxs, F, R, U)
if vmax then
surface.SetDrawColor(255, 0, 0, 255)
DrawBox(pos, (-1) * vmax, vmax, Vector(1,0,0), Vector(0,1,0), Vector(0,0,1))
end
end
end
end)
| gpl-2.0 |
sarahgerweck/Ace3 | AceGUI-3.0/widgets/AceGUIWidget-Keybinding.lua | 38 | 6512 | --[[-----------------------------------------------------------------------------
Keybinding Widget
Set Keybindings in the Config UI.
-------------------------------------------------------------------------------]]
local Type, Version = "Keybinding", 24
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local pairs = pairs
-- WoW APIs
local IsShiftKeyDown, IsControlKeyDown, IsAltKeyDown = IsShiftKeyDown, IsControlKeyDown, IsAltKeyDown
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: NOT_BOUND
local wowMoP
do
local _, _, _, interface = GetBuildInfo()
wowMoP = (interface >= 50000)
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Control_OnEnter(frame)
frame.obj:Fire("OnEnter")
end
local function Control_OnLeave(frame)
frame.obj:Fire("OnLeave")
end
local function Keybinding_OnClick(frame, button)
if button == "LeftButton" or button == "RightButton" then
local self = frame.obj
if self.waitingForKey then
frame:EnableKeyboard(false)
self.msgframe:Hide()
frame:UnlockHighlight()
self.waitingForKey = nil
else
frame:EnableKeyboard(true)
self.msgframe:Show()
frame:LockHighlight()
self.waitingForKey = true
end
end
AceGUI:ClearFocus()
end
local ignoreKeys = {
["BUTTON1"] = true, ["BUTTON2"] = true,
["UNKNOWN"] = true,
["LSHIFT"] = true, ["LCTRL"] = true, ["LALT"] = true,
["RSHIFT"] = true, ["RCTRL"] = true, ["RALT"] = true,
}
local function Keybinding_OnKeyDown(frame, key)
local self = frame.obj
if self.waitingForKey then
local keyPressed = key
if keyPressed == "ESCAPE" then
keyPressed = ""
else
if ignoreKeys[keyPressed] then return end
if IsShiftKeyDown() then
keyPressed = "SHIFT-"..keyPressed
end
if IsControlKeyDown() then
keyPressed = "CTRL-"..keyPressed
end
if IsAltKeyDown() then
keyPressed = "ALT-"..keyPressed
end
end
frame:EnableKeyboard(false)
self.msgframe:Hide()
frame:UnlockHighlight()
self.waitingForKey = nil
if not self.disabled then
self:SetKey(keyPressed)
self:Fire("OnKeyChanged", keyPressed)
end
end
end
local function Keybinding_OnMouseDown(frame, button)
if button == "LeftButton" or button == "RightButton" then
return
elseif button == "MiddleButton" then
button = "BUTTON3"
elseif button == "Button4" then
button = "BUTTON4"
elseif button == "Button5" then
button = "BUTTON5"
end
Keybinding_OnKeyDown(frame, button)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetWidth(200)
self:SetLabel("")
self:SetKey("")
self.waitingForKey = nil
self.msgframe:Hide()
self:SetDisabled(false)
self.button:EnableKeyboard(false)
end,
-- ["OnRelease"] = nil,
["SetDisabled"] = function(self, disabled)
self.disabled = disabled
if disabled then
self.button:Disable()
self.label:SetTextColor(0.5,0.5,0.5)
else
self.button:Enable()
self.label:SetTextColor(1,1,1)
end
end,
["SetKey"] = function(self, key)
if (key or "") == "" then
self.button:SetText(NOT_BOUND)
self.button:SetNormalFontObject("GameFontNormal")
else
self.button:SetText(key)
self.button:SetNormalFontObject("GameFontHighlight")
end
end,
["GetKey"] = function(self)
local key = self.button:GetText()
if key == NOT_BOUND then
key = nil
end
return key
end,
["SetLabel"] = function(self, label)
self.label:SetText(label or "")
if (label or "") == "" then
self.alignoffset = nil
self:SetHeight(24)
else
self.alignoffset = 30
self:SetHeight(44)
end
end,
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local ControlBackdrop = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 3, right = 3, top = 3, bottom = 3 }
}
local function keybindingMsgFixWidth(frame)
frame:SetWidth(frame.msg:GetWidth() + 10)
frame:SetScript("OnUpdate", nil)
end
local function Constructor()
local name = "AceGUI30KeybindingButton" .. AceGUI:GetNextWidgetNum(Type)
local frame = CreateFrame("Frame", nil, UIParent)
local button = CreateFrame("Button", name, frame, wowMoP and "UIPanelButtonTemplate" or "UIPanelButtonTemplate2")
button:EnableMouse(true)
button:RegisterForClicks("AnyDown")
button:SetScript("OnEnter", Control_OnEnter)
button:SetScript("OnLeave", Control_OnLeave)
button:SetScript("OnClick", Keybinding_OnClick)
button:SetScript("OnKeyDown", Keybinding_OnKeyDown)
button:SetScript("OnMouseDown", Keybinding_OnMouseDown)
button:SetPoint("BOTTOMLEFT")
button:SetPoint("BOTTOMRIGHT")
button:SetHeight(24)
button:EnableKeyboard(false)
local text = button:GetFontString()
text:SetPoint("LEFT", 7, 0)
text:SetPoint("RIGHT", -7, 0)
local label = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
label:SetPoint("TOPLEFT")
label:SetPoint("TOPRIGHT")
label:SetJustifyH("CENTER")
label:SetHeight(18)
local msgframe = CreateFrame("Frame", nil, UIParent)
msgframe:SetHeight(30)
msgframe:SetBackdrop(ControlBackdrop)
msgframe:SetBackdropColor(0,0,0)
msgframe:SetFrameStrata("FULLSCREEN_DIALOG")
msgframe:SetFrameLevel(1000)
msgframe:SetToplevel(true)
local msg = msgframe:CreateFontString(nil, "OVERLAY", "GameFontNormal")
msg:SetText("Press a key to bind, ESC to clear the binding or click the button again to cancel.")
msgframe.msg = msg
msg:SetPoint("TOPLEFT", 5, -5)
msgframe:SetScript("OnUpdate", keybindingMsgFixWidth)
msgframe:SetPoint("BOTTOM", button, "TOP")
msgframe:Hide()
local widget = {
button = button,
label = label,
msgframe = msgframe,
frame = frame,
alignoffset = 30,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
button.obj = widget
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| bsd-3-clause |
bn7/darkstar | scripts/zones/Cape_Teriggan/npcs/Dultwa_IM.lua | 14 | 3310 | -----------------------------------
-- Area: Cape Teriggan
-- NPC: Dulwa, I.M.
-- Type: Border Conquest Guards
-- @pos 119 0 282 113
-----------------------------------
package.loaded["scripts/zones/Cape_Teriggan/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Cape_Teriggan/TextIDs");
local guardnation = NATION_BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = VOLLBOW;
local csid = 0x7ff8;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
bn7/darkstar | scripts/globals/weaponskills/stringing_pummel.lua | 19 | 1733 | -----------------------------------
-- Stringing Pummel
-- Sword weapon skill
-- Skill Level: N/A
-- Delivers a sixfold attack. Damage varies with TP. Kenkonken: Aftermath effect varies with TP.
-- Available only after completing the Unlocking a Myth (Puppetmaster) quest.
-- Aligned with the Shadow Gorget, Soil Gorget & Flame Gorget.
-- Aligned with the Shadow Belt, Soil Belt & Flame Belt.
-- Element: Darkness
-- Modifiers: STR:32% VIT:32%
-- 100%TP 200%TP 300%TP
-- 1 1 1
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 6;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.32; params.dex_wsc = 0.0; params.vit_wsc = 0.32; params.agi_wsc = 0.0; params.int_wsc = 0.0;
params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.15; params.crit200 = 0.45; params.crit300 = 0.65;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.crit300 = 0.45; -- params.crit200 = 0.45; -- unknown
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
if ((player:getEquipID(SLOT_MAIN) == 19008) and (player:getMainJob() == JOBS.PUP)) then
if (damage > 0) then
applyAftermathEffect(player, tp)
end
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
HuangYuNan/thcsvr | expansions/script/c7001101.lua | 1 | 1130 | --无意识的破坏冲动
function c7001101.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(7001101,0))
e1:SetCategory(CATEGORY_COIN+CATEGORY_DESTROY+CATEGORY_TOHAND)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c7001101.tg)
e1:SetOperation(c7001101.activate)
c:RegisterEffect(e1)
end
function c7001101.filter(c)
return c:IsDestructable() or c:IsAbleToHand()
end
function c7001101.tg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c7001101.filter,tp,0,LOCATION_MZONE,1,e:GetHandler()) end
Duel.SetOperationInfo(0,CATEGORY_COIN,nil,1,0,0)
end
function c7001101.activate(e,tp,eg,ep,ev,re,r,rp)
local res=Duel.TossCoin(tp,1)
if res==1 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectMatchingCard(tp,Card.IsDestructable,tp,0,LOCATION_MZONE,1,1,e:GetHandler())
Duel.Destroy(g,REASON_EFFECT)
else
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToHand,tp,0,LOCATION_MZONE,1,1,e:GetHandler())
Duel.SendtoHand(g,nil,REASON_EFFECT)
end
end
| gpl-2.0 |
bn7/darkstar | scripts/zones/Abyssea-Tahrongi/npcs/qm15.lua | 14 | 1566 | -----------------------------------
-- Zone: Abyssea-Tahrongi
-- NPC: ???
-- Spawns Lacovie
-- @pos ? ? ? 45
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/status");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(16961951) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(OVERGROWN_MANDRAGORA_FLOWER) and player:hasKeyItem(CHIPPED_SANDWORM_TOOTH)) then
player:startEvent(1020, OVERGROWN_MANDRAGORA_FLOWER, CHIPPED_SANDWORM_TOOTH); -- Ask if player wants to use KIs
else
player:startEvent(1021, OVERGROWN_MANDRAGORA_FLOWER, CHIPPED_SANDWORM_TOOTH); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1020 and option == 1) then
SpawnMob(16961951):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(OVERGROWN_MANDRAGORA_FLOWER);
player:delKeyItem(CHIPPED_SANDWORM_TOOTH);
end
end;
| gpl-3.0 |
bn7/darkstar | scripts/zones/Alzadaal_Undersea_Ruins/npcs/_20u.lua | 26 | 3263 | -----------------------------------
-- Area: Alzadaal Undersea Ruins
-- Door: Gilded Gateway (Arrapago)
-- @pos -580 0 -159 72
-----------------------------------
package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/besieged");
require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(REMNANTS_PERMIT)) then
local mask = -2
-- salvage2 NYI
--[[if player:getMainLvl() >= 96 then
mask = -14
else]]if player:getMainLvl() >= 65 then
mask = -6
end
player:startEvent(408, 0, mask, 0, 0, 8)
else
player:messageSpecial(NOTHING_HAPPENS);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option,target)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
-- 9 = arrapago, 54 = base salvage number
local instanceid = bit.rshift(option, 19) + 64
local party = player:getParty();
if (party ~= nil) then
for i,v in ipairs(party) do
if (not v:hasKeyItem(REMNANTS_PERMIT)) then
player:messageText(target,MEMBER_NO_REQS, false);
player:instanceEntry(target,1);
return;
elseif (v:getZone() == player:getZone() and v:checkDistance(player) > 50) then
player:messageText(target,MEMBER_TOO_FAR, false);
player:instanceEntry(target,1);
return;
elseif (v:checkImbuedItems()) then
player:messageText(target,MEMBER_IMBUED_ITEM, false);
player:instanceEntry(target,1);
return;
end
end
end
player:createInstance(instanceid, 74);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,target)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if ((csid == 408 and option == 4) or csid == 0x74) then
player:setPos(0,0,0,0,74);
end
end;
-----------------------------------
-- onInstanceLoaded
-----------------------------------
function onInstanceCreated(player,target,instance)
if (instance) then
player:setInstance(instance);
player:instanceEntry(target,4);
player:delKeyItem(REMNANTS_PERMIT);
if (party ~= nil) then
for i,v in ipairs(party) do
if v:getID() ~= player:getID() and v:getZone() == player:getZone() then
v:setInstance(instance);
v:startEvent(0x74, 8);
v:delKeyItem(REMNANTS_PERMIT);
end
end
end
else
player:messageText(target,CANNOT_ENTER, false);
player:instanceEntry(target,3);
end
end;
| gpl-3.0 |
bn7/darkstar | scripts/globals/items/red_curry_bun_+1.lua | 12 | 2062 | -----------------------------------------
-- ID: 5765
-- Item: red_curry_bun_+1
-- Food Effect: 60 Min, All Races
-----------------------------------------
-- TODO: Group effects
-- Health 35
-- Strength 7
-- Agility 3
-- Attack % 25 (cap 150)
-- Ranged Atk % 25 (cap 150)
-- Demon Killer 6
-- Resist Sleep +5
-- HP recovered when healing +6
-- MP recovered when healing +3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5765);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 35);
target:addMod(MOD_STR, 7);
target:addMod(MOD_AGI, 3);
target:addMod(MOD_FOOD_ATTP, 25);
target:addMod(MOD_FOOD_ATT_CAP, 150);
target:addMod(MOD_FOOD_RATTP, 25);
target:addMod(MOD_FOOD_RATT_CAP, 150);
target:addMod(MOD_DEMON_KILLER, 6);
target:addMod(MOD_SLEEPRES, 5);
target:addMod(MOD_HPHEAL, 6);
target:addMod(MOD_MPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 35);
target:delMod(MOD_STR, 7);
target:delMod(MOD_AGI, 3);
target:delMod(MOD_FOOD_ATTP, 25);
target:delMod(MOD_FOOD_ATT_CAP, 150);
target:delMod(MOD_FOOD_RATTP, 25);
target:delMod(MOD_FOOD_RATT_CAP, 150);
target:delMod(MOD_DEMON_KILLER, 6);
target:delMod(MOD_SLEEPRES, 5);
target:delMod(MOD_HPHEAL, 6);
target:delMod(MOD_MPHEAL, 3);
end; | gpl-3.0 |
HuangYuNan/thcsvr | expansions/script/c999402.lua | 1 | 2418 | --禁弹『折反射』
local M = c999402
local Mid = 999402
function M.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY+CATEGORY_DAMAGE)
e1:SetDescription(aux.Stringid(Mid, 0))
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0, 0x1e0)
e1:SetCondition(M.con)
e1:SetCost(M.cost)
e1:SetOperation(M.activate)
c:RegisterEffect(e1)
--remove
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(Mid, 1))
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetRange(LOCATION_GRAVE)
e2:SetCode(EVENT_DAMAGE)
e2:SetCondition(M.condition)
e2:SetTarget(M.target)
e2:SetOperation(M.operation)
c:RegisterEffect(e2)
end
M.DescSetName = 0xa3
function M.costfilter(c)
return c:IsSetCard(0x815)
end
function M.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk == 0 then return Duel.CheckReleaseGroup(tp, M.costfilter, 1, nil) end
local g = Duel.SelectReleaseGroup(tp,M.costfilter, 1, 1, nil)
e:SetLabel(g:GetFirst():GetAttack())
Duel.Release(g, REASON_COST)
end
function M.con(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetMatchingGroupCount(Card.IsType, tp, 0, LOCATION_MZONE, nil, TYPE_MONSTER) > 0
end
function M.activate(e,tp,eg,ep,ev,re,r,rp)
local c = e:GetHandler()
local atk = e:GetLabel()
while atk >= 400 do
local mg = Duel.GetMatchingGroup(Card.IsFaceup, tp, 0, LOCATION_MZONE, nil)
mg:AddCard(c)
local rc = mg:RandomSelect(tp, 1):GetFirst()
if rc == c then
Duel.Damage(1-tp, 500, REASON_EFFECT)
else
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(-800)
e1:SetReset(RESET_EVENT+0x1fe0000)
rc:RegisterEffect(e1)
local e2 = e1:Clone()
e2:SetCode(EFFECT_UPDATE_DEFENSE)
rc:RegisterEffect(e2)
if (rc:GetDefense() <= 0 and not rc:IsType(TYPE_LINK)) or rc:GetAttack() <= 0 then
Duel.Destroy(rc, REASON_EFFECT)
end
end
atk = atk - 400
end
end
function M.condition(e,tp,eg,ep,ev,re,r,rp)
return ep == tp
end
function M.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk == 0 then return true end
Duel.SetOperationInfo(0, CATEGORY_REMOVE, e:GetHandler(), 1, 0, 0)
Duel.SetOperationInfo(0, CATEGORY_DAMAGE, nil, 0, 1-tp, 1000)
end
function M.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.Remove(e:GetHandler(), POS_FACEUP, REASON_EFFECT) ~= 0 then
Duel.BreakEffect()
Duel.Damage(1-tp, 1000, REASON_EFFECT)
end
end | gpl-2.0 |
bn7/darkstar | scripts/zones/Lower_Jeuno/npcs/_6tc.lua | 25 | 4144 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Door: "Neptune's Spire"
-- Starts and Finishes Quest: Beat Around the Bushin
-- @zone 245
-- @pos 35 0 -15
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,BEAT_AROUND_THE_BUSHIN) == QUEST_ACCEPTED) then
if (trade:hasItemQty(1526,1) == true and trade:getItemCount() == 1 and player:getVar("BeatAroundTheBushin") == 2) then
player:startEvent(0x009c); -- After trade Wyrm Beard
elseif (trade:hasItemQty(1527,1) == true and trade:getItemCount() == 1 and player:getVar("BeatAroundTheBushin") == 4) then
player:startEvent(0x009d); -- After trade Behemoth Tongue
elseif (trade:hasItemQty(1525,1) == true and trade:getItemCount() == 1 and player:getVar("BeatAroundTheBushin") == 6) then
player:startEvent(0x009e); -- After trade Adamantoise Egg
elseif (trade:hasItemQty(13202,1) == true and trade:getItemCount() == 1 and player:getVar("BeatAroundTheBushin") == 7) then
player:startEvent(0x009f); -- After trade Brown Belt, Finish Quest "Beat around the Bushin"
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) ==A_VESSEL_WITHOUT_A_CAPTAIN and player:getVar("PromathiaStatus")==0) then
player:startEvent(0x0056); --COP event
elseif (player:getCurrentMission(COP) ==TENDING_AGED_WOUNDS and player:getVar("PromathiaStatus")==1) then
player:startEvent(0x0016); --COP event
elseif (player:getVar("BeatAroundTheBushin") == 1) then
player:startEvent(0x009b); -- Start Quest "Beat around the Bushin"
elseif (player:hasKeyItem(TENSHODO_MEMBERS_CARD) == true) then
player:startEvent(0x0069); -- Open the door
else
player:messageSpecial(ITS_LOCKED);
return 1;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0056 ) then
player:setVar("PromathiaStatus",1);
player:startEvent(0x0009);
elseif (csid == 0x0016 ) then
player:completeMission(COP,TENDING_AGED_WOUNDS);
player:addMission(COP,DARKNESS_NAMED);
player:setVar("PromathiaStatus",0);
player:startEvent(0x000A);
elseif (csid == 0x009b) then
player:addQuest(JEUNO,BEAT_AROUND_THE_BUSHIN);
player:setVar("BeatAroundTheBushin",2);
elseif (csid == 0x009c) then
player:setVar("BeatAroundTheBushin",3);
player:tradeComplete();
elseif (csid == 0x009d) then
player:setVar("BeatAroundTheBushin",5);
player:tradeComplete();
elseif (csid == 0x009e) then
player:setVar("BeatAroundTheBushin",7);
player:tradeComplete();
elseif (csid == 0x009f) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13186);
else
player:addTitle(BLACK_BELT);
player:addItem(13186);
player:messageSpecial(ITEM_OBTAINED,13186);
player:setVar("BeatAroundTheBushin",0);
player:addFame(NORG,125);
player:tradeComplete();
player:completeQuest(JEUNO,BEAT_AROUND_THE_BUSHIN);
end
end
end; | gpl-3.0 |
li-wl/kong | kong/plugins/http-log/handler.lua | 1 | 4056 | local basic_serializer = require "kong.plugins.log-serializers.basic"
local BasePlugin = require "kong.plugins.base_plugin"
local cjson = require "cjson"
local url = require "socket.url"
local string_format = string.format
local cjson_encode = cjson.encode
local HttpLogHandler = BasePlugin:extend()
HttpLogHandler.PRIORITY = 1
local HTTP = "http"
local HTTPS = "https"
-- Generates the raw http message.
-- @param `method` http method to be used to send data
-- @param `content_type` the type to set in the header
-- @param `parsed_url` contains the host details
-- @param `body` Body of the message as a string (must be encoded according to the `content_type` parameter)
-- @return raw http message
local function generate_post_payload(method, content_type, parsed_url, body)
local url
if parsed_url.query then
url = parsed_url.path .. "?".. parsed_url.query
else
url = parsed_url.path
end
local headers = string_format(
"%s %s HTTP/1.1\r\nHost: %s\r\nConnection: Keep-Alive\r\nContent-Type: %s\r\nContent-Length: %s\r\n",
method:upper(), url, parsed_url.host, content_type, #body)
if parsed_url.userinfo then
local auth_header = string_format(
"Authorization: Basic %s\r\n",
ngx.encode_base64(parsed_url.userinfo)
)
headers = headers .. auth_header
end
return string_format("%s\r\n%s", headers, body)
end
-- Parse host url.
-- @param `url` host url
-- @return `parsed_url` a table with host details like domain name, port, path etc
local function parse_url(host_url)
local parsed_url = url.parse(host_url)
if not parsed_url.port then
if parsed_url.scheme == HTTP then
parsed_url.port = 80
elseif parsed_url.scheme == HTTPS then
parsed_url.port = 443
end
end
if not parsed_url.path then
parsed_url.path = "/"
end
return parsed_url
end
-- Log to a Http end point.
-- This basically is structured as a timer callback.
-- @param `premature` see openresty ngx.timer.at function
-- @param `conf` plugin configuration table, holds http endpoint details
-- @param `body` raw http body to be logged
-- @param `name` the plugin name (used for logging purposes in case of errors etc.)
local function log(premature, conf, body, name)
if premature then return end
name = "["..name.."] "
local ok, err
local parsed_url = parse_url(conf.http_endpoint)
local host = parsed_url.host
local port = tonumber(parsed_url.port)
local sock = ngx.socket.tcp()
sock:settimeout(conf.timeout)
ok, err = sock:connect(host, port)
if not ok then
ngx.log(ngx.ERR, name.."failed to connect to "..host..":"..tostring(port)..": ", err)
return
end
if parsed_url.scheme == HTTPS then
local _, err = sock:sslhandshake(true, host, false)
if err then
ngx.log(ngx.ERR, name.."failed to do SSL handshake with "..host..":"..tostring(port)..": ", err)
end
end
ok, err = sock:send(generate_post_payload(conf.method, conf.content_type, parsed_url, body))
if not ok then
ngx.log(ngx.ERR, name.."failed to send data to "..host..":"..tostring(port)..": ", err)
end
ok, err = sock:setkeepalive(conf.keepalive)
if not ok then
ngx.log(ngx.ERR, name.."failed to keepalive to "..host..":"..tostring(port)..": ", err)
return
end
end
-- Only provide `name` when deriving from this class. Not when initializing an instance.
function HttpLogHandler:new(name)
HttpLogHandler.super.new(self, name or "http-log")
end
-- serializes context data into an html message body.
-- @param `ngx` The context table for the request being logged
-- @param `conf` plugin configuration table, holds http endpoint details
-- @return html body as string
function HttpLogHandler:serialize(ngx, conf)
return cjson_encode(basic_serializer.serialize(ngx))
end
function HttpLogHandler:log(conf)
HttpLogHandler.super.log(self)
local ok, err = ngx.timer.at(0, log, conf, self:serialize(ngx, conf), self._name)
if not ok then
ngx.log(ngx.ERR, "["..self._name.."] failed to create timer: ", err)
end
end
return HttpLogHandler
| apache-2.0 |
HuangYuNan/thcsvr | expansions/script/c25044.lua | 1 | 4077 | --毒✿梅蒂欣·梅兰可莉
function c25044.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(25044,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,25043)
e1:SetCost(c25044.spcost)
e1:SetTarget(c25044.sptg)
e1:SetOperation(c25044.spop)
c:RegisterEffect(e1)
--search
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(25044,1))
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetCondition(c25044.thcon)
e2:SetTarget(c25044.thtg)
e2:SetOperation(c25044.thop)
e2:SetLabelObject(e1)
c:RegisterEffect(e2)
--poison
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(25044,2))
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_BATTLE_START)
e3:SetCountLimit(1,25043)
e3:SetTarget(c25044.destg)
e3:SetOperation(c25044.desop)
c:RegisterEffect(e3)
--Attribute
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e4:SetCode(EFFECT_ADD_ATTRIBUTE)
e4:SetRange(LOCATION_MZONE)
e4:SetValue(ATTRIBUTE_WIND)
c:RegisterEffect(e4)
end
function c25044.cfilter(c)
return c:IsSetCard(0x208) and c:IsReleasable()
end
function c25044.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return (Duel.GetLocationCount(tp,LOCATION_MZONE)>0
or Duel.IsExistingMatchingCard(c25044.cfilter,tp,LOCATION_MZONE,0,1,e:GetHandler()))
and Duel.CheckReleaseGroupEx(tp,c25044.cfilter,1,e:GetHandler()) end
if Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then
local g=Duel.SelectReleaseGroupEx(tp,c25044.cfilter,1,2,e:GetHandler())
e:SetLabel(g:GetCount())
Duel.Release(g,REASON_COST)
else
local g=Duel.SelectReleaseGroupEx(tp,c25044.cfilter,1,1,e:GetHandler())
if g:GetFirst():GetLocation()==LOCATION_HAND then
local g1=Duel.SelectReleaseGroup(tp,c25044.cfilter,1,1,e:GetHandler())
g:Merge(g1)
elseif Duel.SelectYesNo(tp,aux.Stringid(25044,3)) then
local g1=Duel.SelectReleaseGroupEx(tp,c25044.cfilter,1,1,e:GetHandler())
g:Merge(g1)
end
e:SetLabel(g:GetCount())
Duel.Release(g,REASON_COST)
end
end
function c25044.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c25044.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,1,tp,tp,false,false,POS_FACEUP)
end
end
function c25044.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SPECIAL+1
end
function c25044.thfilter(c)
return c:IsSetCard(0x164) and c:IsType(TYPE_TRAP) and c:IsSSetable()
end
function c25044.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingMatchingCard(c25044.thfilter,tp,LOCATION_DECK,0,1,nil) end
end
function c25044.thop(e,tp,eg,ep,ev,re,r,rp)
local ct=e:GetLabelObject():GetLabel()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET)
local g=Duel.SelectMatchingCard(tp,c25044.thfilter,tp,LOCATION_DECK,0,ct,ct,nil)
if g:GetCount()>0 then
Duel.SSet(tp,g)
Duel.ConfirmCards(1-tp,g)
end
end
function c25044.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
end
function c25044.desop(e,tp,eg,ep,ev,re,r,rp)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCountLimit(1)
e2:SetCode(EVENT_PHASE+PHASE_STANDBY)
e2:SetLabel(0)
e2:SetCondition(c25044.damcon)
e2:SetOperation(c25044.damop)
e2:SetReset(RESET_PHASE+PHASE_STANDBY+RESET_OPPO_TURN,3)
Duel.RegisterEffect(e2,tp)
end
function c25044.damcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()~=tp
end
function c25044.damop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local ct=e:GetLabel()
if(ct<3) then
ct=ct+1
e:SetLabel(ct)
c:SetTurnCounter(ct)
Duel.Damage(1-tp,500,REASON_EFFECT)
end
end
| gpl-2.0 |
bn7/darkstar | scripts/zones/Kazham/npcs/Mitti_Haplihza.lua | 17 | 1072 | -----------------------------------
-- Area: Kazham
-- NPC: Mitti Haplihza
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("BathedInScent") == 1) then
player:startEvent(0x00B8); -- scent from Blue Rafflesias
else
player:startEvent(0x005E);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
nolansingroy/cocos2d-x-samples | samples/KillBug/src/cocos/extension/DeprecatedExtensionFunc.lua | 61 | 1351 | if nil == cc.Control then
return
end
--tip
local function deprecatedTip(old_name,new_name)
print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********")
end
--functions of CCControl will be deprecated end
local CCControlDeprecated = { }
function CCControlDeprecated.addHandleOfControlEvent(self,func,controlEvent)
deprecatedTip("addHandleOfControlEvent","registerControlEventHandler")
print("come in addHandleOfControlEvent")
self:registerControlEventHandler(func,controlEvent)
end
CCControl.addHandleOfControlEvent = CCControlDeprecated.addHandleOfControlEvent
--functions of CCControl will be deprecated end
--Enums of CCTableView will be deprecated begin
CCTableView.kTableViewScroll = cc.SCROLLVIEW_SCRIPT_SCROLL
CCTableView.kTableViewZoom = cc.SCROLLVIEW_SCRIPT_ZOOM
CCTableView.kTableCellTouched = cc.TABLECELL_TOUCHED
CCTableView.kTableCellSizeForIndex = cc.TABLECELL_SIZE_FOR_INDEX
CCTableView.kTableCellSizeAtIndex = cc.TABLECELL_SIZE_AT_INDEX
CCTableView.kNumberOfCellsInTableView = cc.NUMBER_OF_CELLS_IN_TABLEVIEW
--Enums of CCTableView will be deprecated end
--Enums of CCScrollView will be deprecated begin
CCScrollView.kScrollViewScroll = cc.SCROLLVIEW_SCRIPT_SCROLL
CCScrollView.kScrollViewZoom = cc.SCROLLVIEW_SCRIPT_ZOOM
--Enums of CCScrollView will be deprecated end
| mit |
XJMLN/MTA-PSZ | resources/[PSZMTA]/psz-drift/utils.lua | 1 | 1368 | --[[
Drift - zliczanie punktow
@author Jakub 'XJMLN' Starzak <jack@pszmta.pl
@package PSZMTA.psz-drift
@copyright Jakub 'XJMLN' Starzak <jack@pszmta.pl>
Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie.
]]--
function isSportowyPojazd(model)
local sportowe={402,494,502,503,411,559,561,560,506,451,558,549,555,429,541,415,480,562,565,434,477}
for i,v in ipairs(sportowe) do
if model==v then return true end
end
return false
end
function calc_angle(pojazd)
local vx,vy,vz = getElementVelocity(pojazd)
local modV = math.sqrt(vx*vx + vy*vy)
if not isVehicleOnGround(pojazd) then return 0,modV end
local rx,ry,rz = getElementRotation(pojazd)
local sn, cs = -math.sin(math.rad(rz)), math.cos(math.rad(rz))
if modV <= 0.2 then return 0,modV end -- Prędkość poniżej 40km/h
local cosX = (sn*vx + cs*vy)/modV
if cosX > 0.966 or cosX < 0 then return 0,modV end -- obrót pomiędzy 15 i 90 stopniami
return math.deg(math.acos(cosX))*0.5, modV
end
function isPlayerRecordScore(player,wynik)
local playerRecord = getElementData(player,"drift")
if (wynik > (playerRecord or 0)) then
triggerServerEvent("newPlayerRecordScore",resourceRoot,player,wynik)
end
end
addEvent("onPlayerFinish",true)
addEventHandler("onPlayerFinish",getRootElement(),isPlayerRecordScore)
| mit |
WalkWifi/Openwrt | package/ramips/ui/luci-mtk/src/applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-res.lua | 80 | 3097 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
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$
]]--
cbimap = Map("asterisk", "asterisk", "")
module = cbimap:section(TypedSection, "module", "Modules", "")
module.anonymous = true
res_config_mysql = module:option(ListValue, "res_config_mysql", "MySQL Config Resource", "")
res_config_mysql:value("yes", "Load")
res_config_mysql:value("no", "Do Not Load")
res_config_mysql:value("auto", "Load as Required")
res_config_mysql.rmempty = true
res_config_odbc = module:option(ListValue, "res_config_odbc", "ODBC Config Resource", "")
res_config_odbc:value("yes", "Load")
res_config_odbc:value("no", "Do Not Load")
res_config_odbc:value("auto", "Load as Required")
res_config_odbc.rmempty = true
res_config_pgsql = module:option(ListValue, "res_config_pgsql", "PGSQL Module", "")
res_config_pgsql:value("yes", "Load")
res_config_pgsql:value("no", "Do Not Load")
res_config_pgsql:value("auto", "Load as Required")
res_config_pgsql.rmempty = true
res_crypto = module:option(ListValue, "res_crypto", "Cryptographic Digital Signatures", "")
res_crypto:value("yes", "Load")
res_crypto:value("no", "Do Not Load")
res_crypto:value("auto", "Load as Required")
res_crypto.rmempty = true
res_features = module:option(ListValue, "res_features", "Call Parking Resource", "")
res_features:value("yes", "Load")
res_features:value("no", "Do Not Load")
res_features:value("auto", "Load as Required")
res_features.rmempty = true
res_indications = module:option(ListValue, "res_indications", "Indications Configuration", "")
res_indications:value("yes", "Load")
res_indications:value("no", "Do Not Load")
res_indications:value("auto", "Load as Required")
res_indications.rmempty = true
res_monitor = module:option(ListValue, "res_monitor", "Call Monitoring Resource", "")
res_monitor:value("yes", "Load")
res_monitor:value("no", "Do Not Load")
res_monitor:value("auto", "Load as Required")
res_monitor.rmempty = true
res_musiconhold = module:option(ListValue, "res_musiconhold", "Music On Hold Resource", "")
res_musiconhold:value("yes", "Load")
res_musiconhold:value("no", "Do Not Load")
res_musiconhold:value("auto", "Load as Required")
res_musiconhold.rmempty = true
res_odbc = module:option(ListValue, "res_odbc", "ODBC Resource", "")
res_odbc:value("yes", "Load")
res_odbc:value("no", "Do Not Load")
res_odbc:value("auto", "Load as Required")
res_odbc.rmempty = true
res_smdi = module:option(ListValue, "res_smdi", "SMDI Module", "")
res_smdi:value("yes", "Load")
res_smdi:value("no", "Do Not Load")
res_smdi:value("auto", "Load as Required")
res_smdi.rmempty = true
res_snmp = module:option(ListValue, "res_snmp", "SNMP Module", "")
res_snmp:value("yes", "Load")
res_snmp:value("no", "Do Not Load")
res_snmp:value("auto", "Load as Required")
res_snmp.rmempty = true
return cbimap
| gpl-2.0 |
bn7/darkstar | scripts/zones/Uleguerand_Range/npcs/HomePoint#5.lua | 27 | 1258 | -----------------------------------
-- Area: Uleguerand_Range
-- NPC: HomePoint#5
-- @pos
-----------------------------------
package.loaded["scripts/zones/Uleguerand_Range/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Uleguerand_Range/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x2200, 80);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x2200) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
shizhai/wprobe | build_dir/target-mips_r2_uClibc-0.9.33.2/luci/applications/luci-polipo/luasrc/model/cbi/polipo.lua | 79 | 5961 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Aleksandar Krsteski <alekrsteski@gmail.com>
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$
]]--
m = Map("polipo", translate("Polipo"),
translate("Polipo is a small and fast caching web proxy."))
-- General section
s = m:section(NamedSection, "general", "polipo", translate("Proxy"))
s:tab("general", translate("General Settings"))
s:tab("dns", translate("DNS and Query Settings"))
s:tab("proxy", translate("Parent Proxy"))
s:tab("logging", translate("Logging and RAM"))
-- General settings
s:taboption("general", Flag, "enabled", translate("enable"))
o = s:taboption("general", Value, "proxyAddress", translate("Listen address"),
translate("The interface on which Polipo will listen. To listen on all " ..
"interfaces use 0.0.0.0 or :: (IPv6)."))
o.placeholder = "0.0.0.0"
o.datatype = "ipaddr"
o = s:taboption("general", Value, "proxyPort", translate("Listen port"),
translate("Port on which Polipo will listen"))
o.optional = true
o.placeholder = "8123"
o.datatype = "port"
o = s:taboption("general", DynamicList, "allowedClients",
translate("Allowed clients"),
translate("When listen address is set to 0.0.0.0 or :: (IPv6), you must " ..
"list clients that are allowed to connect. The format is IP address " ..
"or network address (192.168.1.123, 192.168.1.0/24, " ..
"2001:660:116::/48 (IPv6))"))
o.datatype = "ipaddr"
o.placeholder = "0.0.0.0/0"
-- DNS settings
dns = s:taboption("dns", Value, "dnsNameServer", translate("DNS server address"),
translate("Set the DNS server address to use, if you want Polipo to use " ..
"different DNS server than the host system."))
dns.optional = true
dns.datatype = "ipaddr"
l = s:taboption("dns", ListValue, "dnsQueryIPv6",
translate("Query DNS for IPv6"))
l.default = "happily"
l:value("true", translate("Query only IPv6"))
l:value("happily", translate("Query IPv4 and IPv6, prefer IPv6"))
l:value("reluctantly", translate("Query IPv4 and IPv6, prefer IPv4"))
l:value("false", translate("Do not query IPv6"))
l = s:taboption("dns", ListValue, "dnsUseGethostbyname",
translate("Query DNS by hostname"))
l.default = "reluctantly"
l:value("true", translate("Always use system DNS resolver"))
l:value("happily",
translate("Query DNS directly, for unknown hosts fall back " ..
"to system resolver"))
l:value("reluctantly",
translate("Query DNS directly, fallback to system resolver"))
l:value("false", translate("Never use system DNS resolver"))
-- Proxy settings
o = s:taboption("proxy", Value, "parentProxy",
translate("Parent proxy address"),
translate("Parent proxy address (in host:port format), to which Polipo " ..
"will forward the requests."))
o.optional = true
o.datatype = "ipaddr"
o = s:taboption("proxy", Value, "parentAuthCredentials",
translate("Parent proxy authentication"),
translate("Basic HTTP authentication supported. Provide username and " ..
"password in username:password format."))
o.optional = true
o.placeholder = "username:password"
-- Logging
s:taboption("logging", Flag, "logSyslog", translate("Log to syslog"))
s:taboption("logging", Value, "logFacility",
translate("Syslog facility")):depends("logSyslog", "1")
v = s:taboption("logging", Value, "logFile",
translate("Log file location"),
translate("Use of external storage device is recommended, because the " ..
"log file is written frequently and can grow considerably."))
v:depends("logSyslog", "")
v.rmempty = true
o = s:taboption("logging", Value, "chunkHighMark",
translate("In RAM cache size (in bytes)"),
translate("How much RAM should Polipo use for its cache."))
o.datatype = "uinteger"
-- Disk cache section
s = m:section(NamedSection, "cache", "polipo", translate("On-Disk Cache"))
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
-- Disk cache settings
s:taboption("general", Value, "diskCacheRoot", translate("Disk cache location"),
translate("Location where polipo will cache files permanently. Use of " ..
"external storage devices is recommended, because the cache can " ..
"grow considerably. Leave it empty to disable on-disk " ..
"cache.")).rmempty = true
s:taboption("general", Flag, "cacheIsShared", translate("Shared cache"),
translate("Enable if cache (proxy) is shared by multiple users."))
o = s:taboption("advanced", Value, "diskCacheTruncateSize",
translate("Truncate cache files size (in bytes)"),
translate("Size to which cached files should be truncated"))
o.optional = true
o.placeholder = "1048576"
o.datatype = "uinteger"
o = s:taboption("advanced", Value, "diskCacheTruncateTime",
translate("Truncate cache files time"),
translate("Time after which cached files will be truncated"))
o.optional = true
o.placeholder = "4d12h"
o = s:taboption("advanced", Value, "diskCacheUnlinkTime",
translate("Delete cache files time"),
translate("Time after which cached files will be deleted"))
o.optional = true
o.placeholder = "32d"
-- Poor man's multiplexing section
s = m:section(NamedSection, "pmm", "polipo",
translate("Poor Man's Multiplexing"),
translate("Poor Man's Multiplexing (PMM) is a technique that simulates " ..
"multiplexing by requesting an instance in multiple segments. It " ..
"tries to lower the latency caused by the weakness of HTTP " ..
"protocol. NOTE: some sites may not work with PMM enabled."))
s:option(Value, "pmmSize", translate("PMM segments size (in bytes)"),
translate("To enable PMM, PMM segment size must be set to some " ..
"positive value.")).rmempty = true
s:option(Value, "pmmFirstSize", translate("First PMM segment size (in bytes)"),
translate("Size of the first PMM segment. If not defined, it defaults " ..
"to twice the PMM segment size.")).rmempty = true
return m
| gpl-2.0 |
bn7/darkstar | scripts/zones/Inner_Horutoto_Ruins/npcs/_5ca.lua | 14 | 2341 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: Mahogany Door
-- Involved In Quest: Making Headlines
-- Involved in Mission 2-1
-- @pos -11 0 20 192
-----------------------------------
package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/Inner_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES);
local CurrentMission = player:getCurrentMission(WINDURST)
local MissionStatus = player:getVar("MissionStatus");
-- Check for Missions first (priority?)
-- We should allow both missions and quests to activate
if (CurrentMission == LOST_FOR_WORDS and MissionStatus == 4) then
player:startEvent(0x002e);
elseif (MakingHeadlines == 1) then
function testflag(set,flag)
return (set % (2*flag) >= flag)
end
local prog = player:getVar("QuestMakingHeadlines_var");
if (testflag(tonumber(prog),16) == false and testflag(tonumber(prog),8) == true) then
player:messageSpecial(7208,1,WINDURST_WOODS_SCOOP); -- Confirm Story
player:setVar("QuestMakingHeadlines_var",prog+16);
else
player:startEvent(0x002c); -- "The door is firmly shut"
end
else
player:startEvent(0x002c); -- "The door is firmly shut"
end;
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x002e) then
-- Mark the progress
player:setVar("MissionStatus",5);
end
end; | gpl-3.0 |
bn7/darkstar | scripts/globals/items/grilled_lik.lua | 12 | 1346 | -----------------------------------------
-- ID: 5648
-- Item: Grilled Lik
-- Food Effect: 60 Mins, All Races
-----------------------------------------
-- Dexterity 4
-- Mind -3
-- Accuracy +2
-- Attack +8
----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5648);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 4);
target:addMod(MOD_MND, -3);
target:addMod(MOD_ACC, 2);
target:addMod(MOD_ATT, 8);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 4);
target:delMod(MOD_MND, -3);
target:delMod(MOD_ACC, 2);
target:delMod(MOD_ATT, 8);
end;
| gpl-3.0 |
bn7/darkstar | scripts/zones/Dynamis-Windurst/mobs/Xoo_Kaza_the_Solemn.lua | 17 | 1160 | -----------------------------------
-- Area: Dynamis Windurst
-- NPC: Xoo Kaza the Solemn
-- Boss Trigger for RDM NM
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local bossTrigger = GetServerVariable("[DynaWindurst]Boss_Trigger");
if (bossTrigger == 0 or bossTrigger == 1 or bossTrigger == 4 or bossTrigger == 5) then
SetServerVariable("[DynaWindurst]Boss_Trigger",bossTrigger + 2);
SpawnMob(17543586); -- 110
SpawnMob(17543587); -- 111
end
-- If 3 first boss trigger are killed -> pop the last trigger
if (GetServerVariable("[DynaWindurst]Boss_Trigger") == 7) then
SpawnMob(17543590); -- 114
SpawnMob(17543591); -- 115
SpawnMob(17543592); -- 116
SetServerVariable("[DynaWindurst]Boss_Trigger",8);
end
end; | gpl-3.0 |
abbasgh12345/extremeseed | plugins/invite.lua | 299 | 1025 | -- Invite other user to the chat group.
-- Use !invite name User_name or !invite id id_number
-- The User_name is the print_name (there are no spaces but _)
do
local function callback(extra, success, result)
vardump(success)
vardump(result)
end
local function run(msg, matches)
local user = matches[2]
-- User submitted a user name
if matches[1] == "name" then
user = string.gsub(user," ","_")
end
-- User submitted an id
if matches[1] == "id" then
user = 'user#id'..user
end
-- The message must come from a chat group
if msg.to.type == 'chat' then
local chat = 'chat#id'..msg.to.id
chat_add_user(chat, user, callback, false)
return "Add: "..user.." to "..chat
else
return 'This isnt a chat group!'
end
end
return {
description = "Invite other user to the chat group",
usage = {
"!invite name [user_name]",
"!invite id [user_id]" },
patterns = {
"^!invite (name) (.*)$",
"^!invite (id) (%d+)$"
},
run = run,
moderation = true
}
end | gpl-2.0 |
Arashbrsh/trea | plugins/invite.lua | 299 | 1025 | -- Invite other user to the chat group.
-- Use !invite name User_name or !invite id id_number
-- The User_name is the print_name (there are no spaces but _)
do
local function callback(extra, success, result)
vardump(success)
vardump(result)
end
local function run(msg, matches)
local user = matches[2]
-- User submitted a user name
if matches[1] == "name" then
user = string.gsub(user," ","_")
end
-- User submitted an id
if matches[1] == "id" then
user = 'user#id'..user
end
-- The message must come from a chat group
if msg.to.type == 'chat' then
local chat = 'chat#id'..msg.to.id
chat_add_user(chat, user, callback, false)
return "Add: "..user.." to "..chat
else
return 'This isnt a chat group!'
end
end
return {
description = "Invite other user to the chat group",
usage = {
"!invite name [user_name]",
"!invite id [user_id]" },
patterns = {
"^!invite (name) (.*)$",
"^!invite (id) (%d+)$"
},
run = run,
moderation = true
}
end | gpl-2.0 |
bn7/darkstar | scripts/zones/Port_San_dOria/npcs/Liloune.lua | 17 | 1400 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Liloune
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_San_dOria/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x252);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
bn7/darkstar | scripts/zones/Northern_San_dOria/npcs/Morunaude.lua | 17 | 1453 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Morunaude
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Northern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x027a);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
bn7/darkstar | scripts/globals/items/wild_steak.lua | 12 | 1379 | -----------------------------------------
-- ID: 4519
-- Item: wild_steak
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Strength 4
-- Intelligence -2
-- Attack % 25
-- Attack Cap 50
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4519);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 4);
target:addMod(MOD_INT, -2);
target:addMod(MOD_FOOD_ATTP, 25);
target:addMod(MOD_FOOD_ATT_CAP, 50);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 4);
target:delMod(MOD_INT, -2);
target:delMod(MOD_FOOD_ATTP, 25);
target:delMod(MOD_FOOD_ATT_CAP, 50);
end;
| gpl-3.0 |
bn7/darkstar | scripts/globals/items/chunk_of_sweet_lizard.lua | 12 | 1408 | -----------------------------------------
-- ID: 5738
-- Item: chunk_of_sweet_lizard
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP 5
-- MP 5
-- Dexterity 1
-- hHP +2
-- hMP +2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5738);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 5);
target:addMod(MOD_MP, 5);
target:addMod(MOD_DEX, 1);
target:addMod(MOD_HPHEAL, 2);
target:addMod(MOD_MPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 5);
target:delMod(MOD_MP, 5);
target:delMod(MOD_DEX, 1);
target:delMod(MOD_HPHEAL, 2);
target:delMod(MOD_MPHEAL, 2);
end;
| gpl-3.0 |
bn7/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5fh.lua | 2 | 1248 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: Shiva's Gate
-- @pos 110 -34 100 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
if (player:hasKeyItem(MAGICKED_ASTROLABE)) then
npc:openDoor(8);
else
player:messageSpecial(SOLID_STONE);
end
end
return 0;
end;
--
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
AntonioModer/Algorithm-Implementations | Egyptian_Fractions/Lua/Yonaba/egyptian_fractions_test.lua | 26 | 1335 | -- Tests for egyptian_fractions.lua
local egypt = require 'egyptian_fractions'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
-- Checks if two given fractions are the same
-- Note, f2 has a simplified representation: f2[1] is num, f2[2] is denum
local function sameFract(f1, f2)
return (f1.num == f2[1] and f1.denum == f2[2])
end
-- Compares two Egyptian fractions
-- Note: see sameFract definition
local function same(t1, t2)
for k, v in ipairs(t1) do
if not sameFract(v, t2[k]) then return false end
end
return true
end
run('Egyptian fractions test', function()
assert(same(egypt(2, 5), {{1,3},{1,15}}))
assert(same(egypt(2, 7), {{1,4},{1,28}}))
assert(same(egypt(2, 9), {{1,5},{1,45}}))
assert(same(egypt(2,11), {{1,6},{1,66}}))
assert(same(egypt(1023,1024), {{1,2},{1,3},{1,7},{1,44},{1,9462},{1,373029888}}))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
bn7/darkstar | scripts/globals/weaponskills/mordant_rime.lua | 18 | 2236 | -----------------------------------
-- Mordant Rime
-- Dagger weapon skill
-- Skill level: N/A
-- Description: Delivers a twofold attack that decreases target's movement speed. Chance of decreasing movement speed varies with TP. Carnwenhan: Aftermath effect varies with TP.
-- Aligned with the Breeze Gorget, Thunder Gorget, Aqua Gorget & Snow Gorget.
-- Aligned with the Breeze Belt, Thunder Belt, Aqua Belt & Snow Belt.
-- Element: None
-- Skillchain Properties: Fragmentation/Distortion
-- Modifiers: DEX:30% ; CHR:70%
-- Damage Multipliers by TP:
-- 100%TP 200%TP 300%TP
-- 5.0 5.0 5.0
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 2;
params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3;
params.str_wsc = 0.0; params.dex_wsc = 0.3; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0;
params.mnd_wsc = 0.0; params.chr_wsc = 0.5;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 5; params.ftp200 = 5; params.ftp300 = 5;
params.chr_wsc = 0.7;
end
local chance = tp-1000 > math.random()*150;
if (damage > 0 and chance) and (target:hasStatusEffect(EFFECT_WEIGHT) == false) then
target:addStatusEffect(EFFECT_WEIGHT, 50, 0, 60);
end
if ((player:getEquipID(SLOT_MAIN) == 19000) and (player:getMainJob() == JOBS.BRD)) then
if (damage > 0) then
local params = initAftermathParams()
params.subpower.lv1 = 2
params.subpower.lv2 = 2
params.subpower.lv3 = 1
applyAftermathEffect(player, tp, params)
end
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
bn7/darkstar | scripts/globals/weaponskills/atonement.lua | 9 | 4322 | -----------------------------------
-- Atonement
-- TODO: This needs to be reworked, as this weapon skill does damage based on current enmity, not based on stat modifiers. http://wiki.ffxiclopedia.org/wiki/Atonement http://www.bg-wiki.com/bg/Atonement
-- Sword weapon skill
-- Skill Level: N/A
-- Delivers a Twofold attack. Damage varies with TP. Conqueror: Aftermath effect varies with TP.
-- Available only after completing the Unlocking a Myth (Paladin) quest.
-- Aligned with the Aqua Gorget, Flame Gorget & Light Gorget.
-- Aligned with the Aqua Belt, Flame Belt & Light Belt.
-- Element: None
-- Modifiers (old): damage varies with enmity
-- 100%TP 200%TP 300%TP
-- 0.09 0.11 0.20 -CE
-- 0.11 0.14 0.25 -VE
-- Modifiers (new): enmity from damage varies with TP
-- 100%TP 200%TP 300%TP
-- 1.00 1.5 2.0
-- Modifiers (non-mob, wrong): STR:40% VIT:50%
-- 100%TP 200%TP 300%TP
-- 1.00 1.25 1.50
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 2;
params.ftp100 = 1; params.ftp200 = 1.25; params.ftp300 = 1.5;
params.str_wsc = 0.4; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0;
params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
local tpHits = 0;
local extraHits = 0;
local criticalHit = false;
local enmityMult = 1;
local damage = 0;
if (target:getObjType() ~= TYPE_MOB) then -- this isn't correct but might as well use what was originally here if someone uses this on a non-mob
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2.0;
end
damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
else
local dmg;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
dmg = (target:getCE(player) + target:getVE(player))/6;
-- tp affects enmity multiplier, 1.0 at 1k, 1.5 at 2k, 2.0 at 3k. Gorget/Belt adds 100 tp each.
enmityMult = enmityMult + (tp + (handleWSGorgetBelt(player) * 1000) - 1000)/2000;
enmityMult = utils.clamp(enmityMult, 1, 2); -- necessary because of Gorget/Belt bonus
else
local effectiveTP = tp + handleWSGorgetBelt(player) * 1000;
effectiveTP = utils.clamp(effectiveTP, 0, 3000); -- necessary because of Gorget/Belt bonus
local ceMod = fTP(effectiveTP, 0.09, 0.11, 0.20); -- CE portion of Atonement
local veMod = fTP(effectiveTP, 0.11, 0.14, 0.25); -- VE portion of Atonement
dmg = math.floor(target:getCE(player) * ceMod) + math.floor(target:getVE(player) * veMod);
end
dmg = utils.clamp(dmg, 0, player:getMainLvl() * 10); -- Damage is capped to player's level * 10, before WS damage mods
damage = target:breathDmgTaken(dmg);
if (player:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID) > 0) then
damage = damage * (100 + player:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID))/100
end
damage = damage * WEAPON_SKILL_POWER;
if (damage > 0) then
if (player:getOffhandDmg() > 0) then
tpHits = 2;
else
tpHits = 1;
end
extraHits = 1; -- for whatever reason, Atonement always yields the a TP return of a 2 hit WS, unless it does 0 damage.
end
local wsParams = {}
wsParams.enmityMult = enmityMult
damage = takeWeaponskillDamage(target, player, wsParams, primary, damage, SLOT_MAIN, tpHits, extraHits, nil)
end
if ((player:getEquipID(SLOT_MAIN) == 18997) and (player:getMainJob() == JOBS.PLD)) then
if (damage > 0) then
applyAftermathEffect(player, tp)
end
end
return tpHits, extraHits, criticalHit, damage;
end;
| gpl-3.0 |
WalkWifi/Openwrt | package/ramips/ui/luci-mtk/src/modules/admin-full/luasrc/model/cbi/admin_network/vlan.lua | 55 | 8246 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org>
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
]]--
m = Map("network", translate("Switch"), translate("The network ports on this device can be combined to several <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s in which computers can communicate directly with each other. <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s are often used to separate different network segments. Often there is by default one Uplink port for a connection to the next greater network like the internet and other ports for a local network."))
local fs = require "nixio.fs"
local switches = { }
m.uci:foreach("network", "switch",
function(x)
local sid = x['.name']
local switch_name = x.name or sid
local has_vlan = nil
local has_learn = nil
local has_vlan4k = nil
local has_jumbo3 = nil
local min_vid = 0
local max_vid = 16
local num_vlans = 16
local cpu_port = tonumber(fs.readfile("/proc/switch/eth0/cpuport") or 5)
local num_ports = cpu_port + 1
local switch_title
local enable_vlan4k = false
-- Parse some common switch properties from swconfig help output.
local swc = io.popen("swconfig dev %q help 2>/dev/null" % switch_name)
if swc then
local is_port_attr = false
local is_vlan_attr = false
while true do
local line = swc:read("*l")
if not line then break end
if line:match("^%s+%-%-vlan") then
is_vlan_attr = true
elseif line:match("^%s+%-%-port") then
is_vlan_attr = false
is_port_attr = true
elseif line:match("cpu @") then
switch_title = line:match("^switch%d: %w+%((.-)%)")
num_ports, cpu_port, num_vlans =
line:match("ports: (%d+) %(cpu @ (%d+)%), vlans: (%d+)")
num_ports = tonumber(num_ports) or 6
num_vlans = tonumber(num_vlans) or 16
cpu_port = tonumber(cpu_port) or 5
min_vid = 1
elseif line:match(": pvid") or line:match(": tag") or line:match(": vid") then
if is_vlan_attr then has_vlan4k = line:match(": (%w+)") end
elseif line:match(": enable_vlan4k") then
enable_vlan4k = true
elseif line:match(": enable_vlan") then
has_vlan = "enable_vlan"
elseif line:match(": enable_learning") then
has_learn = "enable_learning"
elseif line:match(": max_length") then
has_jumbo3 = "max_length"
end
end
swc:close()
end
-- Switch properties
s = m:section(NamedSection, x['.name'], "switch",
switch_title and translatef("Switch %q (%s)", switch_name, switch_title)
or translatef("Switch %q", switch_name))
s.addremove = false
if has_vlan then
s:option(Flag, has_vlan, translate("Enable VLAN functionality"))
end
if has_learn then
x = s:option(Flag, has_learn, translate("Enable learning and aging"))
x.default = x.enabled
end
if has_jumbo3 then
x = s:option(Flag, has_jumbo3, translate("Enable Jumbo Frame passthrough"))
x.enabled = "3"
x.rmempty = true
end
-- VLAN table
s = m:section(TypedSection, "switch_vlan",
switch_title and translatef("VLANs on %q (%s)", switch_name, switch_title)
or translatef("VLANs on %q", switch_name))
s.template = "cbi/tblsection"
s.addremove = true
s.anonymous = true
-- Filter by switch
s.filter = function(self, section)
local device = m:get(section, "device")
return (device and device == switch_name)
end
-- Override cfgsections callback to enforce row ordering by vlan id.
s.cfgsections = function(self)
local osections = TypedSection.cfgsections(self)
local sections = { }
local section
for _, section in luci.util.spairs(
osections,
function(a, b)
return (tonumber(m:get(osections[a], has_vlan4k or "vlan")) or 9999)
< (tonumber(m:get(osections[b], has_vlan4k or "vlan")) or 9999)
end
) do
sections[#sections+1] = section
end
return sections
end
-- When creating a new vlan, preset it with the highest found vid + 1.
s.create = function(self, section, origin)
-- Filter by switch
if m:get(origin, "device") ~= switch_name then
return
end
local sid = TypedSection.create(self, section)
local max_nr = 0
local max_id = 0
m.uci:foreach("network", "switch_vlan",
function(s)
if s.device == switch_name then
local nr = tonumber(s.vlan)
local id = has_vlan4k and tonumber(s[has_vlan4k])
if nr ~= nil and nr > max_nr then max_nr = nr end
if id ~= nil and id > max_id then max_id = id end
end
end)
m:set(sid, "device", switch_name)
m:set(sid, "vlan", max_nr + 1)
if has_vlan4k then
m:set(sid, has_vlan4k, max_id + 1)
end
return sid
end
local port_opts = { }
local untagged = { }
-- Parse current tagging state from the "ports" option.
local portvalue = function(self, section)
local pt
for pt in (m:get(section, "ports") or ""):gmatch("%w+") do
local pc, tu = pt:match("^(%d+)([tu]*)")
if pc == self.option then return (#tu > 0) and tu or "u" end
end
return ""
end
-- Validate port tagging. Ensure that a port is only untagged once,
-- bail out if not.
local portvalidate = function(self, value, section)
-- ensure that the ports appears untagged only once
if value == "u" then
if not untagged[self.option] then
untagged[self.option] = true
elseif min_vid > 0 or tonumber(self.option) ~= cpu_port then -- enable multiple untagged cpu ports due to weird broadcom default setup
return nil,
translatef("Port %d is untagged in multiple VLANs!", tonumber(self.option) + 1)
end
end
return value
end
local vid = s:option(Value, has_vlan4k or "vlan", "VLAN ID", "<div id='portstatus-%s'></div>" % switch_name)
local mx_vid = has_vlan4k and 4094 or (num_vlans - 1)
vid.rmempty = false
vid.forcewrite = true
vid.vlan_used = { }
vid.datatype = "and(uinteger,range("..min_vid..","..mx_vid.."))"
-- Validate user provided VLAN ID, make sure its within the bounds
-- allowed by the switch.
vid.validate = function(self, value, section)
local v = tonumber(value)
local m = has_vlan4k and 4094 or (num_vlans - 1)
if v ~= nil and v >= min_vid and v <= m then
if not self.vlan_used[v] then
self.vlan_used[v] = true
return value
else
return nil,
translatef("Invalid VLAN ID given! Only unique IDs are allowed")
end
else
return nil,
translatef("Invalid VLAN ID given! Only IDs between %d and %d are allowed.", min_vid, m)
end
end
-- When writing the "vid" or "vlan" option, serialize the port states
-- as well and write them as "ports" option to uci.
vid.write = function(self, section, value)
local o
local p = { }
for _, o in ipairs(port_opts) do
local v = o:formvalue(section)
if v == "t" then
p[#p+1] = o.option .. v
elseif v == "u" then
p[#p+1] = o.option
end
end
if enable_vlan4k then
m:set(sid, "enable_vlan4k", "1")
end
m:set(section, "ports", table.concat(p, " "))
return Value.write(self, section, value)
end
-- Fallback to "vlan" option if "vid" option is supported but unset.
vid.cfgvalue = function(self, section)
return m:get(section, has_vlan4k or "vlan")
or m:get(section, "vlan")
end
-- Build per-port off/untagged/tagged choice lists.
local pt
for pt = 0, num_ports - 1 do
local title
if pt == cpu_port then
title = translate("CPU")
else
title = translatef("Port %d", pt)
end
local po = s:option(ListValue, tostring(pt), title)
po:value("", translate("off"))
po:value("u", translate("untagged"))
po:value("t", translate("tagged"))
po.cfgvalue = portvalue
po.validate = portvalidate
po.write = function() end
port_opts[#port_opts+1] = po
end
switches[#switches+1] = switch_name
end
)
-- Switch status template
s = m:section(SimpleSection)
s.template = "admin_network/switch_status"
s.switches = switches
return m
| gpl-2.0 |
shizhai/wprobe | build_dir/target-mips_r2_uClibc-0.9.33.2/luci/ipkg-ar71xx/luci-mod-admin-full/usr/lib/lua/luci/model/cbi/admin_network/vlan.lua | 55 | 8246 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org>
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
]]--
m = Map("network", translate("Switch"), translate("The network ports on this device can be combined to several <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s in which computers can communicate directly with each other. <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s are often used to separate different network segments. Often there is by default one Uplink port for a connection to the next greater network like the internet and other ports for a local network."))
local fs = require "nixio.fs"
local switches = { }
m.uci:foreach("network", "switch",
function(x)
local sid = x['.name']
local switch_name = x.name or sid
local has_vlan = nil
local has_learn = nil
local has_vlan4k = nil
local has_jumbo3 = nil
local min_vid = 0
local max_vid = 16
local num_vlans = 16
local cpu_port = tonumber(fs.readfile("/proc/switch/eth0/cpuport") or 5)
local num_ports = cpu_port + 1
local switch_title
local enable_vlan4k = false
-- Parse some common switch properties from swconfig help output.
local swc = io.popen("swconfig dev %q help 2>/dev/null" % switch_name)
if swc then
local is_port_attr = false
local is_vlan_attr = false
while true do
local line = swc:read("*l")
if not line then break end
if line:match("^%s+%-%-vlan") then
is_vlan_attr = true
elseif line:match("^%s+%-%-port") then
is_vlan_attr = false
is_port_attr = true
elseif line:match("cpu @") then
switch_title = line:match("^switch%d: %w+%((.-)%)")
num_ports, cpu_port, num_vlans =
line:match("ports: (%d+) %(cpu @ (%d+)%), vlans: (%d+)")
num_ports = tonumber(num_ports) or 6
num_vlans = tonumber(num_vlans) or 16
cpu_port = tonumber(cpu_port) or 5
min_vid = 1
elseif line:match(": pvid") or line:match(": tag") or line:match(": vid") then
if is_vlan_attr then has_vlan4k = line:match(": (%w+)") end
elseif line:match(": enable_vlan4k") then
enable_vlan4k = true
elseif line:match(": enable_vlan") then
has_vlan = "enable_vlan"
elseif line:match(": enable_learning") then
has_learn = "enable_learning"
elseif line:match(": max_length") then
has_jumbo3 = "max_length"
end
end
swc:close()
end
-- Switch properties
s = m:section(NamedSection, x['.name'], "switch",
switch_title and translatef("Switch %q (%s)", switch_name, switch_title)
or translatef("Switch %q", switch_name))
s.addremove = false
if has_vlan then
s:option(Flag, has_vlan, translate("Enable VLAN functionality"))
end
if has_learn then
x = s:option(Flag, has_learn, translate("Enable learning and aging"))
x.default = x.enabled
end
if has_jumbo3 then
x = s:option(Flag, has_jumbo3, translate("Enable Jumbo Frame passthrough"))
x.enabled = "3"
x.rmempty = true
end
-- VLAN table
s = m:section(TypedSection, "switch_vlan",
switch_title and translatef("VLANs on %q (%s)", switch_name, switch_title)
or translatef("VLANs on %q", switch_name))
s.template = "cbi/tblsection"
s.addremove = true
s.anonymous = true
-- Filter by switch
s.filter = function(self, section)
local device = m:get(section, "device")
return (device and device == switch_name)
end
-- Override cfgsections callback to enforce row ordering by vlan id.
s.cfgsections = function(self)
local osections = TypedSection.cfgsections(self)
local sections = { }
local section
for _, section in luci.util.spairs(
osections,
function(a, b)
return (tonumber(m:get(osections[a], has_vlan4k or "vlan")) or 9999)
< (tonumber(m:get(osections[b], has_vlan4k or "vlan")) or 9999)
end
) do
sections[#sections+1] = section
end
return sections
end
-- When creating a new vlan, preset it with the highest found vid + 1.
s.create = function(self, section, origin)
-- Filter by switch
if m:get(origin, "device") ~= switch_name then
return
end
local sid = TypedSection.create(self, section)
local max_nr = 0
local max_id = 0
m.uci:foreach("network", "switch_vlan",
function(s)
if s.device == switch_name then
local nr = tonumber(s.vlan)
local id = has_vlan4k and tonumber(s[has_vlan4k])
if nr ~= nil and nr > max_nr then max_nr = nr end
if id ~= nil and id > max_id then max_id = id end
end
end)
m:set(sid, "device", switch_name)
m:set(sid, "vlan", max_nr + 1)
if has_vlan4k then
m:set(sid, has_vlan4k, max_id + 1)
end
return sid
end
local port_opts = { }
local untagged = { }
-- Parse current tagging state from the "ports" option.
local portvalue = function(self, section)
local pt
for pt in (m:get(section, "ports") or ""):gmatch("%w+") do
local pc, tu = pt:match("^(%d+)([tu]*)")
if pc == self.option then return (#tu > 0) and tu or "u" end
end
return ""
end
-- Validate port tagging. Ensure that a port is only untagged once,
-- bail out if not.
local portvalidate = function(self, value, section)
-- ensure that the ports appears untagged only once
if value == "u" then
if not untagged[self.option] then
untagged[self.option] = true
elseif min_vid > 0 or tonumber(self.option) ~= cpu_port then -- enable multiple untagged cpu ports due to weird broadcom default setup
return nil,
translatef("Port %d is untagged in multiple VLANs!", tonumber(self.option) + 1)
end
end
return value
end
local vid = s:option(Value, has_vlan4k or "vlan", "VLAN ID", "<div id='portstatus-%s'></div>" % switch_name)
local mx_vid = has_vlan4k and 4094 or (num_vlans - 1)
vid.rmempty = false
vid.forcewrite = true
vid.vlan_used = { }
vid.datatype = "and(uinteger,range("..min_vid..","..mx_vid.."))"
-- Validate user provided VLAN ID, make sure its within the bounds
-- allowed by the switch.
vid.validate = function(self, value, section)
local v = tonumber(value)
local m = has_vlan4k and 4094 or (num_vlans - 1)
if v ~= nil and v >= min_vid and v <= m then
if not self.vlan_used[v] then
self.vlan_used[v] = true
return value
else
return nil,
translatef("Invalid VLAN ID given! Only unique IDs are allowed")
end
else
return nil,
translatef("Invalid VLAN ID given! Only IDs between %d and %d are allowed.", min_vid, m)
end
end
-- When writing the "vid" or "vlan" option, serialize the port states
-- as well and write them as "ports" option to uci.
vid.write = function(self, section, value)
local o
local p = { }
for _, o in ipairs(port_opts) do
local v = o:formvalue(section)
if v == "t" then
p[#p+1] = o.option .. v
elseif v == "u" then
p[#p+1] = o.option
end
end
if enable_vlan4k then
m:set(sid, "enable_vlan4k", "1")
end
m:set(section, "ports", table.concat(p, " "))
return Value.write(self, section, value)
end
-- Fallback to "vlan" option if "vid" option is supported but unset.
vid.cfgvalue = function(self, section)
return m:get(section, has_vlan4k or "vlan")
or m:get(section, "vlan")
end
-- Build per-port off/untagged/tagged choice lists.
local pt
for pt = 0, num_ports - 1 do
local title
if pt == cpu_port then
title = translate("CPU")
else
title = translatef("Port %d", pt)
end
local po = s:option(ListValue, tostring(pt), title)
po:value("", translate("off"))
po:value("u", translate("untagged"))
po:value("t", translate("tagged"))
po.cfgvalue = portvalue
po.validate = portvalidate
po.write = function() end
port_opts[#port_opts+1] = po
end
switches[#switches+1] = switch_name
end
)
-- Switch status template
s = m:section(SimpleSection)
s.template = "admin_network/switch_status"
s.switches = switches
return m
| gpl-2.0 |
shizhai/wprobe | build_dir/target-mips_r2_uClibc-0.9.33.2/luci/modules/admin-full/dist/usr/lib/lua/luci/model/cbi/admin_network/vlan.lua | 55 | 8246 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org>
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
]]--
m = Map("network", translate("Switch"), translate("The network ports on this device can be combined to several <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s in which computers can communicate directly with each other. <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s are often used to separate different network segments. Often there is by default one Uplink port for a connection to the next greater network like the internet and other ports for a local network."))
local fs = require "nixio.fs"
local switches = { }
m.uci:foreach("network", "switch",
function(x)
local sid = x['.name']
local switch_name = x.name or sid
local has_vlan = nil
local has_learn = nil
local has_vlan4k = nil
local has_jumbo3 = nil
local min_vid = 0
local max_vid = 16
local num_vlans = 16
local cpu_port = tonumber(fs.readfile("/proc/switch/eth0/cpuport") or 5)
local num_ports = cpu_port + 1
local switch_title
local enable_vlan4k = false
-- Parse some common switch properties from swconfig help output.
local swc = io.popen("swconfig dev %q help 2>/dev/null" % switch_name)
if swc then
local is_port_attr = false
local is_vlan_attr = false
while true do
local line = swc:read("*l")
if not line then break end
if line:match("^%s+%-%-vlan") then
is_vlan_attr = true
elseif line:match("^%s+%-%-port") then
is_vlan_attr = false
is_port_attr = true
elseif line:match("cpu @") then
switch_title = line:match("^switch%d: %w+%((.-)%)")
num_ports, cpu_port, num_vlans =
line:match("ports: (%d+) %(cpu @ (%d+)%), vlans: (%d+)")
num_ports = tonumber(num_ports) or 6
num_vlans = tonumber(num_vlans) or 16
cpu_port = tonumber(cpu_port) or 5
min_vid = 1
elseif line:match(": pvid") or line:match(": tag") or line:match(": vid") then
if is_vlan_attr then has_vlan4k = line:match(": (%w+)") end
elseif line:match(": enable_vlan4k") then
enable_vlan4k = true
elseif line:match(": enable_vlan") then
has_vlan = "enable_vlan"
elseif line:match(": enable_learning") then
has_learn = "enable_learning"
elseif line:match(": max_length") then
has_jumbo3 = "max_length"
end
end
swc:close()
end
-- Switch properties
s = m:section(NamedSection, x['.name'], "switch",
switch_title and translatef("Switch %q (%s)", switch_name, switch_title)
or translatef("Switch %q", switch_name))
s.addremove = false
if has_vlan then
s:option(Flag, has_vlan, translate("Enable VLAN functionality"))
end
if has_learn then
x = s:option(Flag, has_learn, translate("Enable learning and aging"))
x.default = x.enabled
end
if has_jumbo3 then
x = s:option(Flag, has_jumbo3, translate("Enable Jumbo Frame passthrough"))
x.enabled = "3"
x.rmempty = true
end
-- VLAN table
s = m:section(TypedSection, "switch_vlan",
switch_title and translatef("VLANs on %q (%s)", switch_name, switch_title)
or translatef("VLANs on %q", switch_name))
s.template = "cbi/tblsection"
s.addremove = true
s.anonymous = true
-- Filter by switch
s.filter = function(self, section)
local device = m:get(section, "device")
return (device and device == switch_name)
end
-- Override cfgsections callback to enforce row ordering by vlan id.
s.cfgsections = function(self)
local osections = TypedSection.cfgsections(self)
local sections = { }
local section
for _, section in luci.util.spairs(
osections,
function(a, b)
return (tonumber(m:get(osections[a], has_vlan4k or "vlan")) or 9999)
< (tonumber(m:get(osections[b], has_vlan4k or "vlan")) or 9999)
end
) do
sections[#sections+1] = section
end
return sections
end
-- When creating a new vlan, preset it with the highest found vid + 1.
s.create = function(self, section, origin)
-- Filter by switch
if m:get(origin, "device") ~= switch_name then
return
end
local sid = TypedSection.create(self, section)
local max_nr = 0
local max_id = 0
m.uci:foreach("network", "switch_vlan",
function(s)
if s.device == switch_name then
local nr = tonumber(s.vlan)
local id = has_vlan4k and tonumber(s[has_vlan4k])
if nr ~= nil and nr > max_nr then max_nr = nr end
if id ~= nil and id > max_id then max_id = id end
end
end)
m:set(sid, "device", switch_name)
m:set(sid, "vlan", max_nr + 1)
if has_vlan4k then
m:set(sid, has_vlan4k, max_id + 1)
end
return sid
end
local port_opts = { }
local untagged = { }
-- Parse current tagging state from the "ports" option.
local portvalue = function(self, section)
local pt
for pt in (m:get(section, "ports") or ""):gmatch("%w+") do
local pc, tu = pt:match("^(%d+)([tu]*)")
if pc == self.option then return (#tu > 0) and tu or "u" end
end
return ""
end
-- Validate port tagging. Ensure that a port is only untagged once,
-- bail out if not.
local portvalidate = function(self, value, section)
-- ensure that the ports appears untagged only once
if value == "u" then
if not untagged[self.option] then
untagged[self.option] = true
elseif min_vid > 0 or tonumber(self.option) ~= cpu_port then -- enable multiple untagged cpu ports due to weird broadcom default setup
return nil,
translatef("Port %d is untagged in multiple VLANs!", tonumber(self.option) + 1)
end
end
return value
end
local vid = s:option(Value, has_vlan4k or "vlan", "VLAN ID", "<div id='portstatus-%s'></div>" % switch_name)
local mx_vid = has_vlan4k and 4094 or (num_vlans - 1)
vid.rmempty = false
vid.forcewrite = true
vid.vlan_used = { }
vid.datatype = "and(uinteger,range("..min_vid..","..mx_vid.."))"
-- Validate user provided VLAN ID, make sure its within the bounds
-- allowed by the switch.
vid.validate = function(self, value, section)
local v = tonumber(value)
local m = has_vlan4k and 4094 or (num_vlans - 1)
if v ~= nil and v >= min_vid and v <= m then
if not self.vlan_used[v] then
self.vlan_used[v] = true
return value
else
return nil,
translatef("Invalid VLAN ID given! Only unique IDs are allowed")
end
else
return nil,
translatef("Invalid VLAN ID given! Only IDs between %d and %d are allowed.", min_vid, m)
end
end
-- When writing the "vid" or "vlan" option, serialize the port states
-- as well and write them as "ports" option to uci.
vid.write = function(self, section, value)
local o
local p = { }
for _, o in ipairs(port_opts) do
local v = o:formvalue(section)
if v == "t" then
p[#p+1] = o.option .. v
elseif v == "u" then
p[#p+1] = o.option
end
end
if enable_vlan4k then
m:set(sid, "enable_vlan4k", "1")
end
m:set(section, "ports", table.concat(p, " "))
return Value.write(self, section, value)
end
-- Fallback to "vlan" option if "vid" option is supported but unset.
vid.cfgvalue = function(self, section)
return m:get(section, has_vlan4k or "vlan")
or m:get(section, "vlan")
end
-- Build per-port off/untagged/tagged choice lists.
local pt
for pt = 0, num_ports - 1 do
local title
if pt == cpu_port then
title = translate("CPU")
else
title = translatef("Port %d", pt)
end
local po = s:option(ListValue, tostring(pt), title)
po:value("", translate("off"))
po:value("u", translate("untagged"))
po:value("t", translate("tagged"))
po.cfgvalue = portvalue
po.validate = portvalidate
po.write = function() end
port_opts[#port_opts+1] = po
end
switches[#switches+1] = switch_name
end
)
-- Switch status template
s = m:section(SimpleSection)
s.template = "admin_network/switch_status"
s.switches = switches
return m
| gpl-2.0 |
Cloudef/darkstar | scripts/zones/Lufaise_Meadows/npcs/qm4.lua | 2 | 1213 | -----------------------------------
-- Area: Lufaise Meadows
-- NPC: ??? - spawns Splinterspine Grukjuk for quest "A Hard Day's Knight"
-- !pos -38.605 -9.022 -290.700 24
-----------------------------------
package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Lufaise_Meadows/TextIDs");
require("scripts/zones/Lufaise_Meadows/MobIDs");
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
-- NOTE: uncertain of retailness of messages. Had expected but did not find any csid.
if (
player:getQuestStatus(OTHER_AREAS,A_HARD_DAY_S_KNIGHT) == QUEST_ACCEPTED and
player:getVar("SPLINTERSPINE_GRUKJUK") <= 1 and
not GetMobByID(SPLINTERSPINE_GRUKJUK):isSpawned()
) then
player:messageSpecial(SURVEY_THE_SURROUNDINGS);
player:messageSpecial(MURDEROUS_PRESENCE);
player:setVar("SPLINTERSPINE_GRUKJUK",1);
SpawnMob(SPLINTERSPINE_GRUKJUK):updateClaim(player);
else
player:messageSpecial(YOU_CAN_SEE_FOR_MALMS);
player:messageSpecial(NOTHING_OUT_OF_THE_ORDINARY);
end
end;
| gpl-3.0 |
Cloudef/darkstar | scripts/zones/Port_San_dOria/npcs/Fiva.lua | 5 | 1634 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Fiva
-- only sells when San d'Oria controls Kolshushu
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_San_dOria/TextIDs");
require("scripts/globals/conquest");
require("scripts/globals/quests");
require("scripts/globals/shop");
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
function onTrigger(player,npc)
local RegionOwner = GetRegionOwner(KOLSHUSHU);
if (RegionOwner ~= NATION_SANDORIA) then
player:showText(npc,FIVA_CLOSED_DIALOG);
else
player:showText(npc,FIVA_OPEN_DIALOG);
local stock =
{
4503, 184, -- Buburimu Grape
1120, 1620, -- Casablanca
4359, 220, -- Dhalmel Meat
614, 72, -- Mhaura Garlic
4445, 40 -- Yagudo Cherry
}
showShop(player,SANDORIA,stock);
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
NiLSPACE/Chatter | api.lua | 1 | 1174 |
-- This file contains all the chatter-api related functions.
-- Contains all the plugins that want to change something in chat.
g_Plugins = {}
-- Registers a plugin.
-- a_Tag is the tag you want to replace for example {FACTION}
-- a_PluginName is the name of the plugin who is calling
-- a_CallbackName is the name of the function that Chatter will call when someone is talking.
function RegisterPlugin(a_Tag, a_PluginName, a_CallbackName)
assert(
(type(a_Tag) == 'string') and
(type(a_PluginName) == 'string') and
(type(a_CallbackName) == 'string')
)
table.insert(g_Plugins, {Tag = "{" .. a_Tag:upper() .. "}", PluginName = a_PluginName, CallbackName = a_CallbackName})
end
-- Calls a plugin if the tag he wants to replace is in the chat message.
function CallPlugins(a_TempMessage, a_Player)
for Idx, PluginData in ipairs(g_Plugins) do
if (a_TempMessage:find(PluginData.Tag) ~= nil) then
local NewTag = cPluginManager:CallPlugin(PluginData.PluginName, PluginData.CallbackName, a_Player)
if (type(NewTag) == 'string') then
a_TempMessage = a_TempMessage:gsub(PluginData.Tag, NewTag)
end
end
end
return a_TempMessage
end
| apache-2.0 |
nyasukun/openstackcraft | world/Plugins/ProtectionAreas/CurrentLng.lua | 5 | 3025 |
-- CurrentLng.lua
-- This file provides all the translatable strings
-- The expectation is that the translators will create copies of this file, translate the texts and then the users will overwrite this file with a specific language version
-- Note that the individual languages must not have ".lua" extension, otherwise MCServer will load them and the plugin won't work!
--- Messages sent to players
g_Msgs =
{
AllUsersAlreadyAllowed = "All the specified users were already allowed.";
AreaAdded = "Area added, ID %s";
AreaAllowed = "Allowed";
AreaDeleted = "Area ID %s deleted";
AreaNotAllowed = "NOT allowed";
Coords1Set = "Coords1 set as {%d, %d}";
Coords2Set = "Coords2 set as {%d, %d}";
ErrCmdStateNilAddArea = "Cannot add area, internal plugin error (CmdState == nil)";
ErrCmdStateNilListAreas = "Cannot list areas, internal plugin error (CmdState == nil)";
ErrDBFailAddUsers = "Cannot add users, DB failure";
ErrExpectedAreaID = "Parameter mismatch. Expected <AreaID>.";
ErrExpectedAreaIDUserName = "Parameter mismatch. Expected <AreaID> <UserName>.";
ErrExpectedAreaIDUsernames = "Not enough parameters. Expected <AreaID> and a list of usernames.";
ErrExpectedCoordsUsernames = "Not enough parameters. Expected <x1> <z1> <x2> <z2> coords and a list of usernames.";
ErrExpectedListOfUsernames = "Not enough parameters. Expected a list of usernames.";
ErrExpectedUserName = "Parameter mismatch. Expected <UserName>.";
ErrListNotWanded = "Cannot list areas, no query point has been selected. Use a ProtWand lclk / rclk to select a point first";
ErrNoAreaWanded = "Cannot add area, no area has been selected. Use a ProtWand lclk / rclk to select area first";
ErrNoSpaceForWand = "Cannot give wand, no space in your inventory";
ErrNoSuchArea = "No such area: %s";
ErrParseAreaID = "Cannot parse <AreaID>.";
ErrParseCoords = "Cannot parse coords.";
ErrParseCoordsListAreas = "Cannot list areas, cannot parse coords in params";
ErrSyntaxErrorListAreas = "Cannot list areas, syntax error. Expected either no params or <x> <z>.";
ListAreasFooter = "Area list finished";
ListAreasHeader = "Listing protection areas intersecting block column {%d, %d}:";
ListAreasRow = " %s, %s, created by %s";
ListUsersFooter = "End of area %s user list, total %d users";
ListUsersHeader = "Area ID %s: {%d, %d} - {%d, %d}, created by %s; allowed users:";
ListUsersRow = " %s";
NotAllowedToBuild = "You are not allowed to build here!";
NotAllowedToDig = "You are not allowed to dig here!";
RemovedUser = "Removed %s from area %d";
RemovedUserAll = "Removed %s from all areas";
UsersAdded = "Users added: %s";
WandGiven = "Wand given";
} ;
| apache-2.0 |
Cloudef/darkstar | scripts/globals/items/plate_of_mushroom_paella_+1.lua | 2 | 1137 | -----------------------------------------
-- ID: 5971
-- Item: Plate of Mushroom Paella +1
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- HP 43
-- Mind 6
-- Magic Accuracy 6
-- Undead Killer 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(dsp.effects.FOOD) == true or target:hasStatusEffect(dsp.effects.FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
function onItemUse(target)
target:addStatusEffect(dsp.effects.FOOD,0,0,14400,5971);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 45);
target:addMod(MOD_MND, 6);
target:addMod(MOD_MACC, 6);
target:addMod(MOD_UNDEAD_KILLER, 6);
end;
function onEffectLose(target, effect)
target:delMod(MOD_HP, 45);
target:delMod(MOD_MND, 6);
target:delMod(MOD_MACC, 6);
target:delMod(MOD_UNDEAD_KILLER, 6);
end;
| gpl-3.0 |
fiallo1313veeee/Anti_bot | plugins/pvs.lua | 1 | 3090 |
local function usernameinfo (user)
if user.username then
return '@'..user.username
end
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
local function whoisname(cb_extra, success, result)
chat_type = cb_extra.chat_type
chat_id = cb_extra.chat_id
user_id = result.peer_id
user_username = result.username
if chat_type == 'chat' then
send_msg('chat#id'..chat_id, user_id, ok_cb, false)
elseif chat_type == 'channel' then
send_msg('channel#id'..chat_id, user_id, ok_cb, false)
end
end
local function whoisid(cb_extra, success, result)
chat_id = cb_extra.chat_id
user_id = cb_extra.user_id
if cb_extra.chat_type == 'chat' then
send_msg('chat#id'..chat_id, user_id, ok_cb, false)
elseif cb_extra.chat_type == 'channel' then
send_msg('channel#id'..chat_id, user_id, ok_cb, false)
end
end
local function get_id_who(extra, success, result)
result = backward_msg_format(result)
local msg = result
local chat = msg.to.id
local user = msg.from.id
if msg.to.type == 'chat' then
send_msg('chat#id'..msg.to.id, msg.from.id, ok_cb, false)
elseif msg.to.type == 'channel' then
send_msg('channel#id'..msg.to.id, msg.from.id, ok_cb, false)
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local chat = msg.to.id
-- Id of the user and info about group / channel
if matches[1] == "gid" or matches[1] == 'Gid' then
if not is_sudo(msg) then
return nil
end
if permissions(msg.from.id, msg.to.id, "id") then
if msg.to.type == 'channel' then
send_msg(msg.to.peer_id, 'SuperGroup ID: '..msg.to.id, ok_cb, false)
elseif msg.to.type == 'chat' then
send_msg(msg.to.peer_id, 'Group ID: '..msg.to.id, ok_cb, false)
end
end
elseif matches[1] == 'id' or matches[1] == 'Id' then
if not is_sudo(msg) then
return nil
end
if permissions(msg.from.id, msg.to.id, "id") then
chat_type = msg.to.type
chat_id = msg.to.id
if msg.reply_id then
get_message(msg.reply_id, get_id_who, {receiver=get_receiver(msg)})
return
end
if is_id(matches[2]) then
print(1)
user_info('user#id'..matches[2], whoisid, {chat_type=chat_type, chat_id=chat_id, user_id=matches[2]})
return
else
local member = string.gsub(matches[2], '@', '')
resolve_username(member, whoisname, {chat_id=chat_id, member=member, chat_type=chat_type})
return
end
else
return
end
end
end
return {
patterns = {
"^([Ii]d)$",
"^([Gg]id)$",
"^([Ii]d) (.*)$"
},
run = run
}
| gpl-2.0 |
ryanjmulder/premake-4.x | src/base/string.lua | 31 | 1025 | --
-- string.lua
-- Additions to Lua's built-in string functions.
-- Copyright (c) 2002-2008 Jason Perkins and the Premake project
--
--
-- Returns an array of strings, each of which is a substring of s
-- formed by splitting on boundaries formed by `pattern`.
--
function string.explode(s, pattern, plain)
if (pattern == '') then return false end
local pos = 0
local arr = { }
for st,sp in function() return s:find(pattern, pos, plain) end do
table.insert(arr, s:sub(pos, st-1))
pos = sp + 1
end
table.insert(arr, s:sub(pos))
return arr
end
--
-- Find the last instance of a pattern in a string.
--
function string.findlast(s, pattern, plain)
local curr = 0
repeat
local next = s:find(pattern, curr + 1, plain)
if (next) then curr = next end
until (not next)
if (curr > 0) then
return curr
end
end
--
-- Returns true if `haystack` starts with the sequence `needle`.
--
function string.startswith(haystack, needle)
return (haystack:find(needle, 1, true) == 1)
end
| bsd-3-clause |
Cloudef/darkstar | scripts/globals/spells/cursna.lua | 2 | 2366 | -----------------------------------------
-- Spell: Cursna
-- Removes curse and bane from target.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/msg");
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local curse = target:getStatusEffect(dsp.effects.CURSE_I);
local curse2 = target:getStatusEffect(dsp.effects.CURSE_II);
local bane = target:getStatusEffect(dsp.effects.BANE);
local bonus = caster:getMod(MOD_ENHANCES_CURSNA) + target:getMod(MOD_ENHANCES_CURSNA_RCVD);
local power = 25*((100+bonus)/100); -- This 25 is temp until the skill calculation is in.
spell:setMsg(msgBasic.MAGIC_NO_EFFECT);
if (target:hasStatusEffect(dsp.effects.DOOM) and power > math.random(1, 100)) then
-- remove doom
final = dsp.effects.DOOM;
target:delStatusEffect(dsp.effects.DOOM);
spell:setMsg(msgBasic.NARROWLY_ESCAPE);
elseif (curse ~= nil and curse2 ~= nil and bane ~= nil) then
target:delStatusEffect(dsp.effects.CURSE_I);
target:delStatusEffect(dsp.effects.CURSE_II);
target:delStatusEffect(dsp.effects.BANE);
final = dsp.effects.CURSE_II;
spell:setMsg(msgBasic.MAGIC_REMOVE_EFFECT);
elseif (curse ~= nil and bane ~= nil) then
target:delStatusEffect(dsp.effects.CURSE_I);
target:delStatusEffect(dsp.effects.BANE);
final = dsp.effects.CURSE_I;
spell:setMsg(msgBasic.MAGIC_REMOVE_EFFECT);
elseif (curse2 ~= nil and bane ~= nil) then
target:delStatusEffect(dsp.effects.CURSE_II);
target:delStatusEffect(dsp.effects.BANE);
final = dsp.effects.CURSE_II;
spell:setMsg(msgBasic.MAGIC_REMOVE_EFFECT);
elseif (curse ~= nil) then
target:delStatusEffect(dsp.effects.CURSE_I);
final = dsp.effects.CURSE_I;
spell:setMsg(msgBasic.MAGIC_REMOVE_EFFECT);
elseif (curse2 ~= nil) then
target:delStatusEffect(dsp.effects.CURSE_II);
final = dsp.effects.CURSE_II;
spell:setMsg(msgBasic.MAGIC_REMOVE_EFFECT);
elseif (bane ~= nil) then
target:delStatusEffect(dsp.effects.BANE);
final = dsp.effects.BANE;
spell:setMsg(msgBasic.MAGIC_REMOVE_EFFECT);
end
return final;
end;
| gpl-3.0 |
Cloudef/darkstar | scripts/globals/abilities/dark_arts.lua | 2 | 1508 | -----------------------------------
-- Ability: Dark Arts
-- Optimizes black magic capability while lowering white magic proficiency. Grants a bonus to enfeebling, elemental, and dark magic. Also grants access to Stratagems.
-- Obtained: Scholar Level 10
-- Recast Time: 1:00
-- Duration: 2:00:00
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/msg");
-----------------------------------
function onAbilityCheck(player,target,ability)
if player:hasStatusEffect(dsp.effects.DARK_ARTS) or player:hasStatusEffect(dsp.effects.ADDENDUM_BLACK) then
return msgBasic.EFFECT_ALREADY_ACTIVE, 0;
end
return 0,0;
end;
function onUseAbility(player,target,ability)
player:delStatusEffectSilent(dsp.effects.LIGHT_ARTS);
player:delStatusEffect(dsp.effects.ADDENDUM_WHITE);
player:delStatusEffect(dsp.effects.PENURY);
player:delStatusEffect(dsp.effects.CELERITY);
player:delStatusEffect(dsp.effects.ACCESSION);
player:delStatusEffect(dsp.effects.RAPTURE);
player:delStatusEffect(dsp.effects.ALTRUISM);
player:delStatusEffect(dsp.effects.TRANQUILITY);
player:delStatusEffect(dsp.effects.PERPETUANCE);
local helixbonus = 0;
if (player:getMainJob() == JOBS.SCH and player:getMainLvl() >= 20) then
helixbonus = math.floor(player:getMainLvl() / 4);
end
player:addStatusEffect(dsp.effects.DARK_ARTS,1,0,7200,0,helixbonus);
return dsp.effects.DARK_ARTS;
end; | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.