Dataset Viewer
commit
stringlengths 40
40
| old_file
stringlengths 6
181
| new_file
stringlengths 6
181
| old_contents
stringlengths 448
7.17k
| new_contents
stringlengths 449
7.17k
| subject
stringlengths 0
450
| message
stringlengths 6
4.92k
| lang
stringclasses 1
value | license
stringclasses 12
values | repos
stringlengths 9
33.9k
|
---|---|---|---|---|---|---|---|---|---|
92ec33e4cd95ec01ed087ff85fc0c27069270a3d
|
fblualib/ffivector/test/ffivector_test.lua
|
fblualib/ffivector/test/ffivector_test.lua
|
--
-- Copyright (c) 2014, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
require('fb.luaunit')
local ffivector = require('fb.ffivector')
local gettorch = require('torch')
function testIntFFIVector()
local v = ffivector.new_int()
v:resize(42)
assertEquals(42, #v)
assertTrue(v:capacity() >= 42)
for i = 1, 42 do
assertEquals(0, v[i])
end
assertError(function() return v[0] end)
assertError(function() return v[43] end)
for i = 1, 42 do
v[i] = i * 10
end
for i = 1, 42 do
assertEquals(i * 10, v[i])
end
end
function testStructFFIVector()
local v = ffivector.new('struct { int a; int64_t b; }')
v:resize(42)
for i = 1, 42 do
p = v[i] -- it's a reference!
p.a = i * 10
p.b = i * 100
end
for i = 1, 42 do
assertEquals(i * 10, v[i].a)
assertEquals(i * 100, tonumber(v[i].b))
end
end
function testStringFFIVector()
local v = ffivector.new_string()
v:resize(42)
for i = 1, 42 do
v[i] = 'hello ' .. tostring(i)
end
collectgarbage() -- temp strings should no longer be allocated
for i = 1, 42 do
assertEquals('hello ' .. tostring(i), v[i])
end
end
function testStringFFIVectorDestruction()
do
local v = ffivector.new_string()
end
collectgarbage()
end
function testFFIVectorDestruction()
local destructor_count = 0
do
local v = ffivector.new(
'int', 0, tonumber, nil,
function(x) destructor_count = destructor_count + 1 end)
v:resize(42)
assertEquals(0, destructor_count)
v[10] = 10
assertEquals(1, destructor_count)
v[42] = 10
assertEquals(2, destructor_count)
v[43] = 10
assertEquals(2, destructor_count)
assertEquals(43, #v)
v:resize(50)
assertEquals(2, destructor_count)
assertEquals(50, #v)
v:resize(40)
assertEquals(12, destructor_count)
assertEquals(40, #v)
end
collectgarbage()
assertEquals(52, destructor_count)
end
LuaUnit:main()
|
--
-- Copyright (c) 2014, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
require('fb.luaunit')
local ffivector = require('fb.ffivector')
function testIntFFIVector()
local v = ffivector.new_int()
v:resize(42)
assertEquals(42, #v)
assertTrue(v:capacity() >= 42)
for i = 1, 42 do
assertEquals(0, v[i])
end
assertError(function() return v[0] end)
assertError(function() return v[43] end)
for i = 1, 42 do
v[i] = i * 10
end
for i = 1, 42 do
assertEquals(i * 10, v[i])
end
end
function testStructFFIVector()
local v = ffivector.new('struct { int a; int64_t b; }')
v:resize(42)
for i = 1, 42 do
p = v[i] -- it's a reference!
p.a = i * 10
p.b = i * 100
end
for i = 1, 42 do
assertEquals(i * 10, v[i].a)
assertEquals(i * 100, tonumber(v[i].b))
end
end
function testStringFFIVector()
local v = ffivector.new_string()
v:resize(42)
for i = 1, 42 do
v[i] = 'hello ' .. tostring(i)
end
collectgarbage() -- temp strings should no longer be allocated
for i = 1, 42 do
assertEquals('hello ' .. tostring(i), v[i])
end
end
function testStringFFIVectorDestruction()
do
local v = ffivector.new_string()
end
collectgarbage()
end
function testFFIVectorDestruction()
local destructor_count = 0
do
local v = ffivector.new(
'int', 0, tonumber, nil,
function(x) destructor_count = destructor_count + 1 end)
v:resize(42)
assertEquals(0, destructor_count)
v[10] = 10
assertEquals(1, destructor_count)
v[42] = 10
assertEquals(2, destructor_count)
v[43] = 10
assertEquals(2, destructor_count)
assertEquals(43, #v)
v:resize(50)
assertEquals(2, destructor_count)
assertEquals(50, #v)
v:resize(40)
assertEquals(12, destructor_count)
assertEquals(40, #v)
end
collectgarbage()
assertEquals(52, destructor_count)
end
LuaUnit:main()
|
Fix ffivector_test.
|
Fix ffivector_test.
Summary: I broke this for no good reason at all. Sorry.
Test Plan: fbconfig fblualib/ffivector/test && fbmake runtests
Reviewed By: [email protected]
FB internal diff: D1588036
Tasks: 5096599
|
Lua
|
bsd-3-clause
|
facebook/fblualib,raphaelamorim/fblualib,soumith/fblualib,szagoruyko/fblualib,soumith/fblualib,facebook/fblualib,raphaelamorim/fblualib,szagoruyko/fblualib
|
eb85fd7974acee779212ba0e2d5b9483aef65ed2
|
onmt/Seq2Seq.lua
|
onmt/Seq2Seq.lua
|
--[[ Sequence to sequence model with attention. ]]
local Seq2Seq, parent = torch.class('Seq2Seq', 'Model')
local options = {
{
'-enc_layers', 0,
[[If > 0, number of layers of the encode. This overrides the global `-layers` option.]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
},
{
'-dec_layers', 0,
[[If > 0, number of layers of the decoder. This overrides the global `-layers` option.]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
},
{
'-word_vec_size', 0,
[[Shared word embedding size. If set, this overrides `-src_word_vec_size` and `-tgt_word_vec_size`.]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
},
{
'-src_word_vec_size', '500',
[[Comma-separated list of source embedding sizes: `word[,feat1[,feat2[,...] ] ]`.]],
{
structural = 0
}
},
{
'-tgt_word_vec_size', '500',
[[Comma-separated list of target embedding sizes: `word[,feat1[,feat2[,...] ] ]`.]],
{
structural = 0
}
},
{
'-pre_word_vecs_enc', '',
[[Path to pretrained word embeddings on the encoder side serialized as a Torch tensor.]],
{
valid = onmt.utils.ExtendedCmdLine.fileNullOrExists,
init_only = true
}
},
{
'-pre_word_vecs_dec', '',
[[Path to pretrained word embeddings on the decoder side serialized as a Torch tensor.]],
{
valid = onmt.utils.ExtendedCmdLine.fileNullOrExists,
init_only = true
}
},
{
'-fix_word_vecs_enc', 0,
[[Fix word embeddings on the encoder side.]],
{
enum = {0, 1},
structural = 1
}
},
{
'-fix_word_vecs_dec', 0,
[[Fix word embeddings on the decoder side.]],
{
enum = {0, 1},
structural = 1
}
},
{
'-feat_merge', 'concat',
[[Merge action for the features embeddings.]],
{
enum = {'concat', 'sum'},
structural = 0
}
},
{
'-feat_vec_exponent', 0.7,
[[When features embedding sizes are not set and using `-feat_merge concat`, their dimension
will be set to `N^feat_vec_exponent` where `N` is the number of values the feature takes.]],
{
structural = 0
}
},
{
'-feat_vec_size', 20,
[[When features embedding sizes are not set and using `-feat_merge sum`,
this is the common embedding size of the features]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
}
}
function Seq2Seq.declareOpts(cmd)
cmd:setCmdLineOptions(options, Seq2Seq.modelName())
onmt.Encoder.declareOpts(cmd)
onmt.Bridge.declareOpts(cmd)
onmt.Decoder.declareOpts(cmd)
onmt.Factory.declareOpts(cmd)
end
function Seq2Seq:__init(args, dicts)
parent.__init(self, args)
onmt.utils.Table.merge(self.args, onmt.utils.ExtendedCmdLine.getModuleOpts(args, options))
self.args.uneven_batches = args.uneven_batches
if not dicts.src then
-- the input is already a vector
args.dimInputSize = dicts.srcInputSize
end
local encArgs = onmt.utils.Tensor.deepClone(args)
encArgs.layers = encArgs.enc_layers > 0 and encArgs.enc_layers or encArgs.layers
self.models.encoder = onmt.Factory.buildWordEncoder(encArgs, dicts.src)
local decArgs = onmt.utils.Tensor.deepClone(args)
decArgs.layers = decArgs.dec_layers > 0 and decArgs.dec_layers or decArgs.layers
self.models.decoder = onmt.Factory.buildWordDecoder(decArgs, dicts.tgt)
self.models.bridge = onmt.Bridge(args.bridge,
self.models.encoder.args.rnnSize,
self.models.encoder.args.numEffectiveLayers,
self.models.decoder.args.rnnSize,
self.models.decoder.args.numEffectiveLayers)
self.criterion = onmt.ParallelClassNLLCriterion(onmt.Factory.getOutputSizes(dicts.tgt))
end
function Seq2Seq.load(args, models, dicts)
local self = torch.factory('Seq2Seq')()
parent.__init(self, args)
onmt.utils.Table.merge(self.args, onmt.utils.ExtendedCmdLine.getModuleOpts(args, options))
self.args.uneven_batches = args.uneven_batches
self.models.encoder = onmt.Factory.loadEncoder(models.encoder)
self.models.decoder = onmt.Factory.loadDecoder(models.decoder)
self.models.bridge = onmt.Bridge.load(models.bridge)
self.criterion = onmt.ParallelClassNLLCriterion(onmt.Factory.getOutputSizes(dicts.tgt))
return self
end
-- Returns model name.
function Seq2Seq.modelName()
return 'Sequence to Sequence with Attention'
end
-- Returns expected dataMode.
function Seq2Seq.dataType()
return 'bitext'
end
function Seq2Seq:returnIndividualLosses(enable)
if not self.models.decoder.returnIndividualLosses then
_G.logger:info('Current Seq2Seq model does not support training with sample_w_ppl option')
return false
else
self.models.decoder:returnIndividualLosses(enable)
end
return true
end
function Seq2Seq:enableProfiling()
_G.profiler.addHook(self.models.encoder, 'encoder')
_G.profiler.addHook(self.models.decoder, 'decoder')
_G.profiler.addHook(self.models.decoder.modules[2], 'generator')
_G.profiler.addHook(self.criterion, 'criterion')
end
function Seq2Seq:getOutput(batch)
return batch.targetOutput
end
function Seq2Seq:maskPadding(batch)
self.models.encoder:maskPadding()
if batch and batch.uneven then
self.models.decoder:maskPadding(self.models.encoder:contextSize(batch.sourceSize, batch.sourceLength))
else
self.models.decoder:maskPadding()
end
end
function Seq2Seq:forwardComputeLoss(batch)
if self.args.uneven_batches then
self:maskPadding(batch)
end
local encoderStates, context = self.models.encoder:forward(batch)
local decoderInitStates = self.models.bridge:forward(encoderStates)
return self.models.decoder:computeLoss(batch, decoderInitStates, context, self.criterion)
end
function Seq2Seq:trainNetwork(batch, dryRun)
if self.args.uneven_batches then
self:maskPadding(batch)
end
local encStates, context = self.models.encoder:forward(batch)
local decInitStates = self.models.bridge:forward(encStates)
local decOutputs = self.models.decoder:forward(batch, decInitStates, context)
if dryRun then
decOutputs = onmt.utils.Tensor.recursiveClone(decOutputs)
end
local decGradInputStates, gradContext, loss, indvLoss = self.models.decoder:backward(batch, decOutputs, self.criterion)
local encGradOutputStates = self.models.bridge:backward(encStates, decGradInputStates)
self.models.encoder:backward(batch, encGradOutputStates, gradContext)
return loss, indvLoss
end
return Seq2Seq
|
--[[ Sequence to sequence model with attention. ]]
local Seq2Seq, parent = torch.class('Seq2Seq', 'Model')
local options = {
{
'-enc_layers', 0,
[[If > 0, number of layers of the encode. This overrides the global `-layers` option.]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
},
{
'-dec_layers', 0,
[[If > 0, number of layers of the decoder. This overrides the global `-layers` option.]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
},
{
'-word_vec_size', 0,
[[Shared word embedding size. If set, this overrides `-src_word_vec_size` and `-tgt_word_vec_size`.]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
},
{
'-src_word_vec_size', '500',
[[Comma-separated list of source embedding sizes: `word[,feat1[,feat2[,...] ] ]`.]],
{
structural = 0
}
},
{
'-tgt_word_vec_size', '500',
[[Comma-separated list of target embedding sizes: `word[,feat1[,feat2[,...] ] ]`.]],
{
structural = 0
}
},
{
'-pre_word_vecs_enc', '',
[[Path to pretrained word embeddings on the encoder side serialized as a Torch tensor.]],
{
valid = onmt.utils.ExtendedCmdLine.fileNullOrExists,
init_only = true
}
},
{
'-pre_word_vecs_dec', '',
[[Path to pretrained word embeddings on the decoder side serialized as a Torch tensor.]],
{
valid = onmt.utils.ExtendedCmdLine.fileNullOrExists,
init_only = true
}
},
{
'-fix_word_vecs_enc', 0,
[[Fix word embeddings on the encoder side.]],
{
enum = {0, 1},
structural = 1
}
},
{
'-fix_word_vecs_dec', 0,
[[Fix word embeddings on the decoder side.]],
{
enum = {0, 1},
structural = 1
}
},
{
'-feat_merge', 'concat',
[[Merge action for the features embeddings.]],
{
enum = {'concat', 'sum'},
structural = 0
}
},
{
'-feat_vec_exponent', 0.7,
[[When features embedding sizes are not set and using `-feat_merge concat`, their dimension
will be set to `N^feat_vec_exponent` where `N` is the number of values the feature takes.]],
{
structural = 0
}
},
{
'-feat_vec_size', 20,
[[When features embedding sizes are not set and using `-feat_merge sum`,
this is the common embedding size of the features]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
}
}
function Seq2Seq.declareOpts(cmd)
cmd:setCmdLineOptions(options, Seq2Seq.modelName())
onmt.Encoder.declareOpts(cmd)
onmt.Bridge.declareOpts(cmd)
onmt.Decoder.declareOpts(cmd)
onmt.Factory.declareOpts(cmd)
end
function Seq2Seq:__init(args, dicts)
parent.__init(self, args)
onmt.utils.Table.merge(self.args, onmt.utils.ExtendedCmdLine.getModuleOpts(args, options))
self.args.uneven_batches = args.uneven_batches
if not dicts.src then
-- the input is already a vector
args.dimInputSize = dicts.srcInputSize
end
local encArgs = onmt.utils.Tensor.deepClone(args)
encArgs.layers = encArgs.enc_layers > 0 and encArgs.enc_layers or encArgs.layers
self.models.encoder = onmt.Factory.buildWordEncoder(encArgs, dicts.src)
local decArgs = onmt.utils.Tensor.deepClone(args)
decArgs.layers = decArgs.dec_layers > 0 and decArgs.dec_layers or decArgs.layers
self.models.decoder = onmt.Factory.buildWordDecoder(decArgs, dicts.tgt)
self.models.bridge = onmt.Bridge(args.bridge,
encArgs.rnn_size,
self.models.encoder.args.numEffectiveLayers,
decArgs.rnn_size,
self.models.decoder.args.numEffectiveLayers)
self.criterion = onmt.ParallelClassNLLCriterion(onmt.Factory.getOutputSizes(dicts.tgt))
end
function Seq2Seq.load(args, models, dicts)
local self = torch.factory('Seq2Seq')()
parent.__init(self, args)
onmt.utils.Table.merge(self.args, onmt.utils.ExtendedCmdLine.getModuleOpts(args, options))
self.args.uneven_batches = args.uneven_batches
self.models.encoder = onmt.Factory.loadEncoder(models.encoder)
self.models.decoder = onmt.Factory.loadDecoder(models.decoder)
self.models.bridge = onmt.Bridge.load(models.bridge)
self.criterion = onmt.ParallelClassNLLCriterion(onmt.Factory.getOutputSizes(dicts.tgt))
return self
end
-- Returns model name.
function Seq2Seq.modelName()
return 'Sequence to Sequence with Attention'
end
-- Returns expected dataMode.
function Seq2Seq.dataType()
return 'bitext'
end
function Seq2Seq:returnIndividualLosses(enable)
if not self.models.decoder.returnIndividualLosses then
_G.logger:info('Current Seq2Seq model does not support training with sample_w_ppl option')
return false
else
self.models.decoder:returnIndividualLosses(enable)
end
return true
end
function Seq2Seq:enableProfiling()
_G.profiler.addHook(self.models.encoder, 'encoder')
_G.profiler.addHook(self.models.decoder, 'decoder')
_G.profiler.addHook(self.models.decoder.modules[2], 'generator')
_G.profiler.addHook(self.criterion, 'criterion')
end
function Seq2Seq:getOutput(batch)
return batch.targetOutput
end
function Seq2Seq:maskPadding(batch)
self.models.encoder:maskPadding()
if batch and batch.uneven then
self.models.decoder:maskPadding(self.models.encoder:contextSize(batch.sourceSize, batch.sourceLength))
else
self.models.decoder:maskPadding()
end
end
function Seq2Seq:forwardComputeLoss(batch)
if self.args.uneven_batches then
self:maskPadding(batch)
end
local encoderStates, context = self.models.encoder:forward(batch)
local decoderInitStates = self.models.bridge:forward(encoderStates)
return self.models.decoder:computeLoss(batch, decoderInitStates, context, self.criterion)
end
function Seq2Seq:trainNetwork(batch, dryRun)
if self.args.uneven_batches then
self:maskPadding(batch)
end
local encStates, context = self.models.encoder:forward(batch)
local decInitStates = self.models.bridge:forward(encStates)
local decOutputs = self.models.decoder:forward(batch, decInitStates, context)
if dryRun then
decOutputs = onmt.utils.Tensor.recursiveClone(decOutputs)
end
local decGradInputStates, gradContext, loss, indvLoss = self.models.decoder:backward(batch, decOutputs, self.criterion)
local encGradOutputStates = self.models.bridge:backward(encStates, decGradInputStates)
self.models.encoder:backward(batch, encGradOutputStates, gradContext)
return loss, indvLoss
end
return Seq2Seq
|
Rely on option value to define the encoder output size
|
Rely on option value to define the encoder output size
Fixes #234.
|
Lua
|
mit
|
monsieurzhang/OpenNMT,OpenNMT/OpenNMT,jungikim/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,jungikim/OpenNMT,da03/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT
|
3bad170979ccbce8c9a3bb3dbfcbb9c9e0bef3de
|
Quadtastic/Frame.lua
|
Quadtastic/Frame.lua
|
local Rectangle = require("Rectangle")
local renderutils = require("Renderutils")
local Layout = require("Layout")
local Frame = {}
local transform = require("transform")
local quads = renderutils.border_quads(48, 0, 16, 16, 128, 128, 2)
Frame.start = function(state, x, y, w, h)
x = x or state.layout.next_x
y = y or state.layout.next_y
w = w or state.layout.max_w
h = h or state.layout.max_h
-- Draw border
love.graphics.setColor(255, 255, 255, 255)
renderutils.draw_border(state.style.stylesheet, quads, x, y, w, h, 2)
Layout.start(state, x+2, y+2, w - 4, h - 4)
end
Frame.finish = function(state, w, h)
Layout.finish(state)
state.layout.adv_x = w or state.layout.max_w
state.layout.adv_y = h or state.layout.max_h
end
return Frame
|
local Rectangle = require("Rectangle")
local renderutils = require("Renderutils")
local Layout = require("Layout")
local Frame = {}
local transform = require("transform")
local quads = renderutils.border_quads(48, 0, 16, 16, 128, 128, 2)
Frame.start = function(state, x, y, w, h)
x = x or state.layout.next_x
y = y or state.layout.next_y
w = w or state.layout.max_w
h = h or state.layout.max_h
-- Draw border
love.graphics.setColor(255, 255, 255, 255)
renderutils.draw_border(state.style.stylesheet, quads, x, y, w, h, 2)
Layout.start(state, x+2, y+2, w - 4, h - 4)
end
Frame.finish = function(state, w, h)
state.layout.adv_x = w or state.layout.max_w + 4
state.layout.adv_y = h or state.layout.max_h + 4
Layout.finish(state)
end
return Frame
|
Fix Frame not setting its layout advances correctly
|
Fix Frame not setting its layout advances correctly
|
Lua
|
mit
|
25A0/Quadtastic,25A0/Quadtastic
|
ab68863ee638ff0f6134fc3be3e41ad9f22c2d7f
|
lua/mediaplayer/services/resource/init.lua
|
lua/mediaplayer/services/resource/init.lua
|
AddCSLuaFile "shared.lua"
include "shared.lua"
local urllib = url
local FilenamePattern = "([^/]+)%.%S+$"
local FilenameExtPattern = "([^/]+%.%S+)$"
SERVICE.TitleIncludeExtension = true -- include extension in title
function SERVICE:GetMetadata( callback )
if not self._metadata then
local title
local pattern = self.TitleIncludeExtension and
FilenameExtPattern or FilenamePattern
local path = self.urlinfo.path
path = string.match( path, pattern ) -- get filename
title = urllib.unescape( path )
self._metadata = {
title = title or self.Name,
url = self.url
}
end
if callback then
callback(self._metadata)
end
end
|
AddCSLuaFile "shared.lua"
include "shared.lua"
local urllib = url
local FilenamePattern = "([^/]+)%.%S+$"
local FilenameExtPattern = "([^/]+%.%S+)$"
SERVICE.TitleIncludeExtension = true -- include extension in title
function SERVICE:GetMetadata( callback )
if not self._metadata then
local title
local pattern = self.TitleIncludeExtension and
FilenameExtPattern or FilenamePattern
if self.urlinfo.path then
local path = self.urlinfo.path
path = string.match( path, pattern ) -- get filename
if path then
title = urllib.unescape( path )
else
title = self.url
end
else
title = self.url
end
self._metadata = {
title = title or self.Name,
url = self.url
}
end
if callback then
callback(self._metadata)
end
end
|
Fixed error when grabbing the path string from a resource URL.
|
Fixed error when grabbing the path string from a resource URL.
|
Lua
|
mit
|
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
|
0f64df3ae71795b8a9371f95f39c9c006fa7bccf
|
UCDwanted/server.lua
|
UCDwanted/server.lua
|
local wantedPoints = {}
addEventHandler("onResourceStart", resourceRoot,
function ()
for _, plr in ipairs(Element.getAllByType("player")) do
if (not plr.account.guest) then
setWantedPoints(plr, exports.UCDaccounts:GAD(plr, "wp"))
end
end
end
)
addEventHandler("onResourceStop", resourceRoot,
function ()
for _, plr in ipairs(Element.getAllByType("player")) do
if (not plr.account.guest) then
exports.UCDaccounts:GAD(plr, "wp", getWantedPoints(plr))
end
end
end
)
function addWantedPoints(plr, wp)
if (plr and wp and not plr.account.guest and tonumber(wp)) then
wp = tonumber(wp)
local a = plr.account.name
if (not wantedPoints[a]) then
wantedPoints[a] = 0
end
setWantedPoints(plr, wantedPoints[a] + wp)
return true
end
end
function getWantedPoints(plr)
if (plr and not plr.account.guest) then
local a = plr.account.name
if (not wantedPoints[a]) then
wantedPoints[a] = 0
end
return wantedPoints[a]
end
end
function setWantedPoints(plr, wp)
if (plr and wp and not plr.account.guest and tonumber(wp)) then
wp = tonumber(wp)
local a = plr.account.name
if (not wantedPoints[a]) then
wantedPoints[a] = wp
return true
end
wantedPoints[a] = wp
plr:setData("w", wantedPoints[a])
triggerEvent("onPlayerWPChange", plr, wantedPoints[a])
return true
end
end
function onPlayerWPChange(wp)
-- Stars
if (wp > 0 and wp <= 10) then
source.wantedLevel = 1
elseif (wp > 10 and wp <= 20) then
source.wantedLevel = 2
elseif (wp > 20 and wp <= 30) then
source.wantedLevel = 3
elseif (wp > 30 and wp <= 40) then
source.wantedLevel = 4
elseif (wp > 40 and wp <= 50) then
source.wantedLevel = 5
elseif (wp > 50) then
--if (source.wantedLevel ~= 60) then
source.wantedLevel = 6
--end
else
source.wantedLevel = 0
end
-- Nametag
if (wp > 0) then
source.nametagText = "["..tostring(source.wantedLevel).."] "..tostring(source.name)
else
source.nametagText = source.name
end
if (wp > 0) then
if (source.team.name == "Law") then
exports.UCDjobs:setPlayerJob(source, "Criminal")
end
end
end
addEvent("onPlayerWPChange")
addEventHandler("onPlayerWPChange", root, onPlayerWPChange)
|
local wantedPoints = {}
addEventHandler("onResourceStart", resourceRoot,
function ()
for _, plr in ipairs(Element.getAllByType("player")) do
if (not plr.account.guest) then
setWantedPoints(plr, exports.UCDaccounts:GAD(plr, "wp"))
end
end
end
)
addEventHandler("onResourceStop", resourceRoot,
function ()
for _, plr in ipairs(Element.getAllByType("player")) do
if (not plr.account.guest) then
exports.UCDaccounts:SAD(plr, "wp", getWantedPoints(plr))
end
end
end
)
function addWantedPoints(plr, wp)
if (plr and wp and not plr.account.guest and tonumber(wp)) then
wp = tonumber(wp)
local a = plr.account.name
if (not wantedPoints[a]) then
wantedPoints[a] = 0
end
setWantedPoints(plr, wantedPoints[a] + wp)
exports.UCDstats:setPlayerAccountStat(plr, "lifetimeWanted", exports.UCDstats:getPlayerAccountStat(plr, "lifetimeWanted") + wp)
return true
end
end
function getWantedPoints(plr)
if (plr and not plr.account.guest) then
local a = plr.account.name
if (not wantedPoints[a]) then
wantedPoints[a] = 0
end
return wantedPoints[a]
end
end
function setWantedPoints(plr, wp)
if (plr and wp and not plr.account.guest and tonumber(wp)) then
wp = tonumber(wp)
local a = plr.account.name
if (not wantedPoints[a]) then
wantedPoints[a] = wp
return true
end
wantedPoints[a] = wp
plr:setData("w", wantedPoints[a])
triggerEvent("onPlayerWPChange", plr, wantedPoints[a])
return true
end
end
function onPlayerWPChange(wp)
-- Stars
if (wp > 0 and wp <= 10) then
source.wantedLevel = 1
elseif (wp > 10 and wp <= 20) then
source.wantedLevel = 2
elseif (wp > 20 and wp <= 30) then
source.wantedLevel = 3
elseif (wp > 30 and wp <= 40) then
source.wantedLevel = 4
elseif (wp > 40 and wp <= 50) then
source.wantedLevel = 5
elseif (wp > 50) then
--if (source.wantedLevel ~= 60) then
source.wantedLevel = 6
--end
else
source.wantedLevel = 0
end
-- Nametag
if (wp > 0) then
source.nametagText = "["..tostring(source.wantedLevel).."] "..tostring(source.name)
else
source.nametagText = source.name
end
if (wp > 0) then
if (source.team.name == "Law") then
exports.UCDjobs:setPlayerJob(source, "Criminal")
end
end
end
addEvent("onPlayerWPChange")
addEventHandler("onPlayerWPChange", root, onPlayerWPChange)
|
UCDwanted
|
UCDwanted
- Added a wanted counter stat every time wp gets added
- Fixed a simple error with saving stats
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
1a6d1715ad377f4ebe6ce29bde5a97badd98fc66
|
premakeUtils.lua
|
premakeUtils.lua
|
function coInitParams(_params)
co_baseAbsPath = os.getcwd()
print("co_baseAbsPath: "..co_baseAbsPath)
co_externalAbsPath = co_baseAbsPath .. "/external"
co_buildPath = "build/" .. _ACTION
local coreRelativePath = "."
if _params.coreRelativePath then
coreRelativePath = _params.coreRelativePath
end
local coreAbsolutePath = path.getabsolute(coreRelativePath)
co_prebuildPath = coreAbsolutePath .. "/build/prebuild.exe"
co_versionMajor = 0
co_versionMinor = 0
co_versionBuild = 0
end
function coSetWorkspaceDefaults(_name)
print("Generating workspace ".._name.."... (in "..co_buildPath..")")
workspace(_name)
co_allConfigurations = {"debug", "dev", "release", "prebuildDebug", "prebuildRelease"}
configurations(co_allConfigurations)
location(co_buildPath)
end
function coSetPCH(_dir, _projectName, _fileName)
pchheader(_projectName .. "/".. _fileName .. '.h')
pchsource(_fileName .. '.cpp')
--[[
filter { "action:vs*" }
pchheader(_fileName .. '.h')
pchsource(_fileName .. '.cpp')
filter { "action:not vs*" }
pchheader(_dir .. '/' .. _fileName .. '.h')
filter {}
--]]
end
function coSetProjectDefaults(_name, _options)
local projectBasePath = "../.."
local buildAbsPath = projectBasePath .. "/" .. co_buildPath
local buildLocation = buildAbsPath.."/projects"
print("Generating project ".._name.."... (in "..buildLocation..")")
project(_name)
location(buildLocation)
architecture "x86_64"
warnings "Extra"
kind "StaticLib"
objdir(buildAbsPath .. "/obj")
targetdir(buildAbsPath .. "/bin/$(Configuration)")
libdirs { "$(OutDir)" }
defines { "coVERSION_MAJOR="..co_versionMajor, "coVERSION_MINOR="..co_versionMinor, "coVERSION_BUILD="..co_versionBuild }
includedirs { projectBasePath.."/build/gen", co_externalAbsPath }
includedirs(co_srcDirs)
debugdir "$(OutDir)"
defines { "coPROJECT_NAME=".._name }
if not (_options and _options.prebuildDependency) then
--removeconfigurations {"prebuild*"}
configurations { "debug", "dev", "release" }
end
filter{"configurations:debug or dev or prebuildDebug"}
defines {"coDEBUG", "coDEV"}
filter{"configurations:debug or dev or release"}
defines {"coREFLECT_ENABLED"}
filter { "configurations:dev or release or prebuildRelease" }
optimize "On"
filter {}
end
function coSetCppProjectDefaults(_name)
coSetProjectDefaults(_name)
rtti "Off"
language "C++"
exceptionhandling "Off"
vectorextensions "SSE2"
floatingpoint "Strict" -- Not slower than Fast, and helps for cross-platform/compiler determinism.
editandcontinue "Off"
symbols "On"
cppdialect "C++17"
runtime "Release" -- Even on debug builds, Unreal is setup this way anyway.
flags { "NoMinimalRebuild", "FatalWarnings", "MultiProcessorCompile" }
files { "**.cpp", "**.h", "**.inl", "**.frag", "**.vert", "**.comp", "**.tesc", "**.tese", "**.geom", "**.importShaders"}
if os.isfile("pch.h") then
coSetPCH(co_projectDir, _name, "pch")
end
filter { "gmake" }
buildoptions { "-Wno-reorder", "-Wno-deprecated" }
includedirs { gmakeIncludeDir }
filter { "action:vs*" }
files { "*.natvis"}
defines { "_HAS_EXCEPTIONS=0" }
--flags { "StaticRuntime" }
--linkoptions { "/ENTRY:mainCRTStartup" } -- TODO: Not working with DLL, should avoid that case somehow.
linkoptions {"/ignore:4221"} -- warns when .cpp are empty depending on the order of obj linking.
filter { "configurations:dev or release or prebuildRelease" }
optimize "Speed"
omitframepointer "On"
filter {"configurations:debug or dev or release"}
filter {'files:**.vert or **.frag or **.comp or **.geom'}
co_shadersFolder = "$(OutDir)/shaders/".._name
shaderOutPath = co_shadersFolder.."/%{file.name}.spv"
buildmessage 'Compiling %{file.relpath}'
buildcommands { '$(GLSLANG)/glslangValidator.exe -G -o "'..shaderOutPath ..'" %{file.relpath}' }
buildoutputs { shaderOutPath }
filter {}
--[[
if os.isfile("reflect.cpp") then
local projectBasePath = "../.."
local genAbsPath = "../../gen"
local command = co_prebuildPath .. ' "' .. path.getabsolute(co_projectDir, path.getabsolute(projectBasePath)) .. "/.." .. '" "' .. genAbsPath .. '" "' .. _name .. '" "'.. _name ..'/pch.h"'
command = command .. ' -I="$(UniversalCRT_IncludePath)"'
for _, d in pairs(co_srcDirs) do
command = command .. ' -I="'..d..'"'
end
prebuildcommands{command}
end
--]]
filter {}
end
function coSetShaderDefaults(_name)
-- Defaults
--language "C++" -- We don't have better here
---[[
--]]
end
function coSetProjectDependencies(_deps)
if not co_dependencies then
co_dependencies = {}
end
for _,v in pairs(_deps) do
table.insert(co_dependencies, v)
end
-- Add custom build commands on the .importShaders file to import shaders from other projects
filter {'files:**.importShaders'}
buildmessage 'Importing shaders...'
for _,v in pairs(_deps) do
local srcDir, foundDir = coFindDir(co_srcDirs, v)
if foundDir == nil then
error("Failed to find the project: "..v)
else
if os.isdir(foundDir.."/shaders") then
shadersDir = srcDir.."/../"..co_buildPath.."/bin/$(Configuration)/shaders/"..v
for _, f in pairs(os.matchfiles(foundDir.."/shaders/*")) do
name = path.getname(f)
local inputs = shadersDir.."/"..name..".spv"
buildinputs { inputs }
buildcommands { "{COPY} "..inputs.." $(OutDir)shaders/"..v }
buildoutputs { "$(OutDir)shaders/"..v.."/"..name..".spv" }
end
--postbuildcommands { "{COPY} "..shadersDir.."/* $(OutDir)shaders/"..v }
end
end
end
filter {}
links(_deps)
end
function coFindDir(_srcDirs, _dirName)
for _, d in pairs(_srcDirs) do
local foundDirs = os.matchdirs(d.."/".._dirName)
for _, e in pairs(foundDirs) do
return d, e
end
end
return nil
end
function coIncludeProject(_srcDirs, _projectName)
local srcDir, foundDir = coFindDir(_srcDirs, _projectName)
if foundDir == nil then
error("Failed to find the project: ".._projectName)
else
co_projectSrcDir = srcDir
co_projectDir = foundDir
include(foundDir)
end
end
function coGenerateProjectWorkspace(_params)
srcDirs = {path.getabsolute("src")}
co_workspaceDependencies = {}
for k, d in pairs(_params.dependencies) do
table.insert(srcDirs, path.getabsolute(d.."/src"))
co_workspaceDependencies[k] = path.getabsolute(d)
end
co_srcDirs = srcDirs
coSetWorkspaceDefaults(_params.name)
startproject(_params.projects[0])
for _, p in pairs(_params.projects) do
coIncludeProject(srcDirs, p)
end
if co_dependencies then
for _, d in pairs(co_dependencies) do
coIncludeProject(srcDirs, d)
end
end
end
|
function coInitParams(_params)
co_baseAbsPath = os.getcwd()
print("co_baseAbsPath: "..co_baseAbsPath)
co_externalAbsPath = co_baseAbsPath .. "/external"
co_buildPath = "build/" .. _ACTION
local coreRelativePath = "."
if _params.coreRelativePath then
coreRelativePath = _params.coreRelativePath
end
local coreAbsolutePath = path.getabsolute(coreRelativePath)
co_prebuildPath = coreAbsolutePath .. "/build/prebuild.exe"
co_versionMajor = 0
co_versionMinor = 0
co_versionBuild = 0
end
function coSetWorkspaceDefaults(_name)
print("Generating workspace ".._name.."... (in "..co_buildPath..")")
workspace(_name)
co_allConfigurations = {"debug", "dev", "release", "prebuildDebug", "prebuildRelease"}
configurations(co_allConfigurations)
location(co_buildPath)
end
function coSetPCH(_dir, _projectName, _fileName)
pchheader(_projectName .. "/".. _fileName .. '.h')
pchsource(_fileName .. '.cpp')
--[[
filter { "action:vs*" }
pchheader(_fileName .. '.h')
pchsource(_fileName .. '.cpp')
filter { "action:not vs*" }
pchheader(_dir .. '/' .. _fileName .. '.h')
filter {}
--]]
end
function coSetProjectDefaults(_name, _options)
local projectBasePath = "../.."
local buildAbsPath = projectBasePath .. "/" .. co_buildPath
local buildLocation = buildAbsPath.."/projects"
print("Generating project ".._name.."... (in "..buildLocation..")")
project(_name)
location(buildLocation)
architecture "x86_64"
warnings "Extra"
kind "StaticLib"
objdir(buildAbsPath .. "/obj")
targetdir(buildAbsPath .. "/bin/$(Configuration)")
libdirs { "$(OutDir)" }
defines { "coVERSION_MAJOR="..co_versionMajor, "coVERSION_MINOR="..co_versionMinor, "coVERSION_BUILD="..co_versionBuild }
includedirs { projectBasePath.."/build/gen", co_externalAbsPath }
includedirs(co_srcDirs)
debugdir "$(OutDir)"
defines { "coPROJECT_NAME=".._name }
if not (_options and _options.prebuildDependency) then
--removeconfigurations {"prebuild*"}
configurations { "debug", "dev", "release" }
end
filter{"configurations:debug or dev or prebuildDebug"}
defines {"coDEBUG", "coDEV"}
filter{"configurations:debug or dev or release"}
defines {"coREFLECT_ENABLED"}
filter { "configurations:dev or release or prebuildRelease" }
optimize "On"
filter {}
end
function coSetCppProjectDefaults(_name)
coSetProjectDefaults(_name)
rtti "Off"
language "C++"
exceptionhandling "Off"
vectorextensions "SSE2"
floatingpoint "Strict" -- Not slower than Fast, and helps for cross-platform/compiler determinism.
editandcontinue "Off"
symbols "On"
cppdialect "C++17"
runtime "Release" -- Even on debug builds, Unreal is setup this way anyway.
flags { "NoMinimalRebuild", "FatalWarnings", "MultiProcessorCompile" }
files { "**.cpp", "**.h", "**.inl", "**.frag", "**.vert", "**.comp", "**.tesc", "**.tese", "**.geom", "**.importShaders"}
if os.isfile("pch.h") then
coSetPCH(co_projectDir, _name, "pch")
end
filter { "gmake" }
buildoptions { "-Wno-reorder", "-Wno-deprecated" }
includedirs { gmakeIncludeDir }
filter { "action:vs*" }
files { "*.natvis"}
defines { "_HAS_EXCEPTIONS=0" }
--flags { "StaticRuntime" }
--linkoptions { "/ENTRY:mainCRTStartup" } -- TODO: Not working with DLL, should avoid that case somehow.
linkoptions {"/ignore:4221"} -- warns when .cpp are empty depending on the order of obj linking.
filter { "configurations:dev or release or prebuildRelease" }
optimize "Speed"
omitframepointer "On"
filter {"configurations:debug or dev or release"}
filter {'files:**.vert or **.frag or **.comp or **.geom'}
co_shadersFolder = "$(OutDir)/shaders/".._name
shaderOutPath = co_shadersFolder.."/%{file.name}.spv"
buildmessage 'Compiling %{file.relpath}'
buildcommands { '$(GLSLANG)/glslangValidator.exe -G -o "'..shaderOutPath ..'" %{file.relpath}' }
buildoutputs { shaderOutPath }
filter {}
--[[
if os.isfile("reflect.cpp") then
local projectBasePath = "../.."
local genAbsPath = "../../gen"
local command = co_prebuildPath .. ' "' .. path.getabsolute(co_projectDir, path.getabsolute(projectBasePath)) .. "/.." .. '" "' .. genAbsPath .. '" "' .. _name .. '" "'.. _name ..'/pch.h"'
command = command .. ' -I="$(UniversalCRT_IncludePath)"'
for _, d in pairs(co_srcDirs) do
command = command .. ' -I="'..d..'"'
end
prebuildcommands{command}
end
--]]
filter {}
end
function coSetShaderDefaults(_name)
-- Defaults
--language "C++" -- We don't have better here
---[[
--]]
end
function coSetProjectDependencies(_deps)
if not co_dependencies then
co_dependencies = {}
end
for _,v in pairs(_deps) do
table.insert(co_dependencies, v)
end
-- Add custom build commands on the .importShaders file to import shaders from other projects
filter {'files:**.importShaders'}
buildmessage 'Importing shaders...'
for _,v in pairs(_deps) do
local srcDir, foundDir = coFindDir(co_srcDirs, v)
if foundDir == nil then
error("Failed to find the project: "..v)
else
if path.normalize(path.join(srcDir, "..")) ~= path.normalize(co_baseAbsPath) then
if os.isdir(foundDir.."/shaders") then
print("Setting up shaders import from: "..foundDir.."/shaders")
shadersDir = srcDir.."/../"..co_buildPath.."/bin/$(Configuration)/shaders/"..v
for _, f in pairs(os.matchfiles(foundDir.."/shaders/*")) do
name = path.getname(f)
local inputs = shadersDir.."/"..name..".spv"
buildinputs { inputs }
buildcommands { "{COPY} "..inputs.." $(OutDir)shaders/"..v }
buildoutputs { "$(OutDir)shaders/"..v.."/"..name..".spv" }
end
--postbuildcommands { "{COPY} "..shadersDir.."/* $(OutDir)shaders/"..v }
end
end
end
end
filter {}
links(_deps)
end
function coFindDir(_srcDirs, _dirName)
for _, d in pairs(_srcDirs) do
local foundDirs = os.matchdirs(d.."/".._dirName)
for _, e in pairs(foundDirs) do
return d, e
end
end
return nil
end
function coIncludeProject(_srcDirs, _projectName)
local srcDir, foundDir = coFindDir(_srcDirs, _projectName)
if foundDir == nil then
error("Failed to find the project: ".._projectName)
else
co_projectSrcDir = srcDir
co_projectDir = foundDir
include(foundDir)
end
end
function coGenerateProjectWorkspace(_params)
srcDirs = {path.getabsolute("src")}
co_workspaceDependencies = {}
for k, d in pairs(_params.dependencies) do
table.insert(srcDirs, path.getabsolute(d.."/src"))
co_workspaceDependencies[k] = path.getabsolute(d)
end
co_srcDirs = srcDirs
coSetWorkspaceDefaults(_params.name)
startproject(_params.projects[0])
for _, p in pairs(_params.projects) do
coIncludeProject(srcDirs, p)
end
if co_dependencies then
for _, d in pairs(co_dependencies) do
coIncludeProject(srcDirs, d)
end
end
end
|
Fixed shaders import when importing from same workspace.
|
Fixed shaders import when importing from same workspace.
|
Lua
|
mit
|
smogpill/core,smogpill/core
|
999fbfe300c82a5865fee7cea98c4bfc068a4055
|
test/test_writeObject.lua
|
test/test_writeObject.lua
|
local myTester = torch.Tester()
local tests = {}
-- checks that an object can be written and unwritten
-- returns false if an error occurs
local function serializeAndDeserialize(obj)
local file = torch.MemoryFile()
file:binary()
local ok, msg = pcall (file.writeObject, file, obj)
myTester:assert(ok, 'error in writing an object' )
file:seek(1)
local ok, copy = pcall(file.readObject, file)
if not ok then print(copy) end
myTester:assert(ok, 'error in reading an object ')
return copy
end
function tests.test_can_write_a_nil_closure()
local a
local function closure()
if not a then return 1 end
return 0
end
local copyClosure = serializeAndDeserialize(closure)
myTester:assert(copyClosure() == closure(), 'the closures should give same output')
end
function tests.test_nil_upvalues_in_closure()
local a = 1
local b
local c = 2
local function closure()
if not b then return c end
return a
end
local copyClosure = serializeAndDeserialize(closure)
myTester:assert(copyClosure() == closure(), 'the closures should give same output')
end
function tests.test_global_function_in_closure()
local x = "5"
local function closure(str)
return tonumber(str .. x)
end
local copyClosure = serializeAndDeserialize(closure)
myTester:assert(copyClosure("3") == closure("3"), 'the closures should give same output')
end
function tests.test_a_recursive_closure()
local foo
foo = function (level)
if level == 1 then return 1 end
return 1+foo(level-1)
end
local copyFoo = serializeAndDeserialize(foo)
myTester:assert(copyFoo(42) == foo(42), 'the closures should give same output')
end
function tests.test_a_tensor()
local x = torch.rand(5, 10)
local xcopy = serializeAndDeserialize(x)
myTester:assert(x:norm() == xcopy:norm(), 'tensors should be the same')
end
myTester:add(tests)
myTester:run()
|
local myTester = torch.Tester()
local tests = {}
-- checks that an object can be written and unwritten
-- returns false if an error occurs
local function serializeAndDeserialize(obj)
local file = torch.MemoryFile()
file:binary()
local ok, msg = pcall (file.writeObject, file, obj)
myTester:assert(ok, 'error in writing an object' )
file:seek(1)
local ok, copy = pcall(file.readObject, file)
if not ok then print(copy) end
myTester:assert(ok, 'error in reading an object ')
return copy
end
function tests.test_can_write_a_nil_closure()
local a
local function closure()
if not a then return 1 end
return 0
end
local copyClosure = serializeAndDeserialize(closure)
myTester:assert(copyClosure() == closure(), 'the closures should give same output')
end
function tests.test_nil_upvalues_in_closure()
local a = 1
local b
local c = 2
local function closure()
if not b then return c end
return a
end
local copyClosure = serializeAndDeserialize(closure)
myTester:assert(copyClosure() == closure(), 'the closures should give same output')
end
function tests.test_global_function_in_closure()
local x = "5"
local function closure(str)
return tonumber(str .. x)
end
local copyClosure = serializeAndDeserialize(closure)
myTester:assert(copyClosure("3") == closure("3"), 'the closures should give same output')
end
function tests.test_a_recursive_closure()
local foo
foo = function (level)
if level == 1 then return 1 end
return 1+foo(level-1)
end
local copyFoo = serializeAndDeserialize(foo)
myTester:assert(copyFoo(42) == foo(42), 'the closures should give same output')
end
function tests.test_a_tensor()
local x = torch.rand(5, 10)
local xcopy = serializeAndDeserialize(x)
myTester:assert(x:norm() == xcopy:norm(), 'tensors should be the same')
end
-- Regression test for bug reported in issue 456.
function tests.test_empty_table()
local file = torch.MemoryFile()
file:writeObject({})
end
myTester:add(tests)
myTester:run()
|
Regression test for MemoryFile bug.
|
Regression test for MemoryFile bug.
|
Lua
|
bsd-3-clause
|
Moodstocks/torch7,wgapl/torch7,Moodstocks/torch7,Atcold/torch7,yozw/torch7,nicholas-leonard/torch7,adamlerer/torch7,wickedfoo/torch7,colesbury/torch7,szagoruyko/torch7,yozw/torch7,adamlerer/torch7,diz-vara/torch7,wgapl/torch7,nicholas-leonard/torch7,Atcold/torch7,colesbury/torch7,wickedfoo/torch7,diz-vara/torch7,szagoruyko/torch7
|
7b19c8c035681f990dec3bb57946360e0a47ae85
|
samples/gstvideo.lua
|
samples/gstvideo.lua
|
#! /usr/bin/env lua
--
-- Sample GStreamer application, port of public Vala GStreamer Video
-- Example (http://live.gnome.org/Vala/GStreamerSample)
--
require 'lgi'
local GLib = require 'lgi.GLib'
local Gtk = require 'lgi.Gtk'
local Gst = require 'lgi.Gst'
local GstInterfaces = require 'lgi.GstInterfaces'
Gtk.init()
Gst.init()
local pipeline = Gst.Pipeline.new('mypipeline')
local src = Gst.ElementFactory.make('videotestsrc', 'video')
local sink = Gst.ElementFactory.make('xvimagesink', 'sink')
pipeline:add(src)
pipeline:add(sink)
src:link(sink)
local function on_play()
end
local function on_stop()
pipeline.set_state(Gst.State.READY)
end
local vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0)
local drawing_area = Gtk.DrawingArea()
drawing_area:set_size_request(300, 150)
vbox:pack_start(drawing_area, true, true, 0)
local play_button = Gtk.Button.new_from_stock(Gtk.STOCK_MEDIA_PLAY)
play_button.on_clicked = function()
-- sink:set_window_handle(0)
pipeline:set_state(Gst.State.PLAYING)
end
local stop_button = Gtk.Button.new_from_stock(Gtk.STOCK_MEDIA_STOP)
stop_button.on_clicked = function()
pipeline:set_state(Gst.State.READY)
end
local quit_button = Gtk.Button.new_from_stock(Gtk.STOCK_QUIT)
quit_button.on_clicked = Gtk.main_quit
local button_box = Gtk.ButtonBox.new(Gtk.Orientation.HORIZONTAL)
button_box:add(play_button)
button_box:add(stop_button)
button_box:add(quit_button)
vbox:pack_start(button_box, false, true, 0)
local window = Gtk.Window {
title = 'Video Player',
child = vbox,
on_destroy = Gtk.main_quit
}
window:show_all()
Gtk.main()
|
#! /usr/bin/env lua
--
-- Sample GStreamer application, port of public Vala GStreamer Video
-- Example (http://live.gnome.org/Vala/GStreamerSample)
--
require 'lgi'
local GLib = require 'lgi.GLib'
local Gtk = require 'lgi.Gtk'
local Gst = require 'lgi.Gst'
local GstInterfaces = require 'lgi.GstInterfaces'
Gtk.init()
Gst.init()
local pipeline = Gst.Pipeline.new('mypipeline')
local src = Gst.ElementFactory.make('videotestsrc', 'video')
local sink = Gst.ElementFactory.make('xvimagesink', 'sink')
pipeline:add(src)
pipeline:add(sink)
src:link(sink)
local vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0)
local drawing_area = Gtk.DrawingArea()
drawing_area:set_size_request(300, 150)
vbox:pack_start(drawing_area, true, true, 0)
local play_button = Gtk.Button.new_from_stock(Gtk.STOCK_MEDIA_PLAY)
play_button.on_clicked = function()
sink:set_window_handle(0)
pipeline:set_state(Gst.State.PLAYING)
end
local stop_button = Gtk.Button.new_from_stock(Gtk.STOCK_MEDIA_STOP)
stop_button.on_clicked = function()
pipeline:set_state(Gst.State.READY)
end
local quit_button = Gtk.Button.new_from_stock(Gtk.STOCK_QUIT)
quit_button.on_clicked = Gtk.main_quit
local button_box = Gtk.ButtonBox.new(Gtk.Orientation.HORIZONTAL)
button_box:add(play_button)
button_box:add(stop_button)
button_box:add(quit_button)
vbox:pack_start(button_box, false, true, 0)
local window = Gtk.Window {
title = 'Video Player',
child = vbox,
on_destroy = Gtk.main_quit
}
window:show_all()
Gtk.main()
|
More fixes to video sample, still dysfunctional though.
|
More fixes to video sample, still dysfunctional though.
|
Lua
|
mit
|
pavouk/lgi,zevv/lgi,psychon/lgi
|
fa77dc94b184a75495329dc46044841968f3b804
|
script/c88754763.lua
|
script/c88754763.lua
|
--CX 熱血指導神アルティメットレーナー
function c88754763.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunction(c,9),4)
c:EnableReviveLimit()
--cannot be target
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(1)
c:RegisterEffect(e1)
--draw
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DRAW+CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCondition(c88754763.condition)
e1:SetCost(c88754763.cost)
e1:SetTarget(c88754763.target)
e1:SetOperation(c88754763.operation)
c:RegisterEffect(e1)
end
function c800000040.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetOverlayGroup():IsExists(Card.IsType,1,nil,TYPE_XYZ)
end
function c88754763.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c88754763.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c88754763.operation(e,tp,eg,ep,ev,re,r,rp,chk)
local ct=Duel.Draw(tp,1,REASON_EFFECT)
if ct==0 then return end
local dc=Duel.GetOperatedGroup():GetFirst()
Duel.ConfirmCards(1-tp,dc)
if dc:IsType(TYPE_MONSTER) then
Duel.Damage(1-tp,800,REASON_EFFECT)
end
Duel.ShuffleHand(tp)
end
|
--CX 熱血指導神アルティメットレーナー
function c88754763.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunction(c,9),4)
c:EnableReviveLimit()
--cannot be target
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(1)
c:RegisterEffect(e1)
--draw
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_DRAW+CATEGORY_DAMAGE)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetCondition(c88754763.condition)
e2:SetCost(c88754763.cost)
e2:SetTarget(c88754763.target)
e2:SetOperation(c88754763.operation)
c:RegisterEffect(e2)
end
function c88754763.condition(e)
return e:GetHandler():GetOverlayGroup():IsExists(Card.IsType,1,nil,TYPE_XYZ)
end
function c88754763.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c88754763.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c88754763.operation(e,tp,eg,ep,ev,re,r,rp,chk)
local ct=Duel.Draw(tp,1,REASON_EFFECT)
if ct==0 then return end
local dc=Duel.GetOperatedGroup():GetFirst()
Duel.ConfirmCards(1-tp,dc)
if dc:IsType(TYPE_MONSTER) then
Duel.Damage(1-tp,800,REASON_EFFECT)
end
Duel.ShuffleHand(tp)
end
|
Update c88754763.lua
|
Update c88754763.lua
fix
|
Lua
|
mit
|
sidschingis/DevProLauncher,SuperAndroid17/DevProLauncher,Tic-Tac-Toc/DevProLauncher
|
53a2c43bed17127c8e4641ec07c39136a1aa4c5d
|
vi_tags.lua
|
vi_tags.lua
|
local M = {}
local state = {
tags = nil, -- current set of tags
tagstack = {},-- current tag stack: list of { i=num, tags={tag list} }
tagidx = 0, -- index into tagstack of current level
lasttag = nil,-- last tag list
timestamp = nil, -- tags file modification time.
}
M.state = state
-- Load a tags file
local function load_tags()
vi_mode.err("Loading tags file...")
local tagf = io.open("tags") -- TODO: configurable tags file location
local results = {}
local pat = "^([^\t]*)\t([^\t]*)\t(.*)$"
if tagf then
state.timestamp = lfs.attributes("tags", "modification")
for line in tagf:lines() do
local tname, fname, excmd = line:match(pat)
local flags
if tname then
-- Initialise to an empty list if necessary
if not results[tname] then results[tname] = {} end
-- And append.
local l = results[tname] -- now guaranteed to be a table
do
-- Try to separate the ex command from extension fields
local e,f = excmd:match('^(.-);"\t(.*)$')
if e then
excmd = e
flags = f
end
end
l[#l+1] = { sym=tname, filename=fname, excmd=excmd, flags=flags }
end
end
tagf:close()
end
state.tags = results
end
-- Return or load the tags
local function get_tags()
-- TODO: check if tags file needs reloading
if state.tags == nil or lfs.attributes("tags", "modification") ~= state.timestamp then
load_tags()
end
return state.tags
end
function M.find_tag_exact(name)
local tags = get_tags()
local result = tags[name]
if result then
local newidx = state.tagidx + 1
-- Clear the stack above where we are.
while newidx <= #state.tagstack do
state.tagstack[#state.tagstack] = nil
end
state.tagstack[newidx] = {
i=1, -- which tag within this list
tags=result, -- this level's tags
fromname=buffer.filename, -- where we came from
frompos=buffer.current_pos,-- where we came from
}
state.lasttag = result
state.tagidx = newidx
return result[1]
else
return nil
end
end
-- Return a list of tags matching Lua pat
function M.match_tag(pat)
local tags = get_tags()
local result = {}
for name,_ in pairs(tags) do
if name:match(pat) then
result[#result+1] = name
end
end
if #result > 0 then return result end
-- return nil if nothing found
end
function M.pop_tag()
if state.tagidx >= 1 then
local tos = state.tagstack[state.tagidx]
io.open_file(tos.fromname)
buffer.goto_pos(tos.frompos)
state.tagidx = state.tagidx - 1
else
vi_mode.err("Top of stack")
end
end
-- Return all the tags in the current level
function M.get_all()
if state.tagidx > 0 then
return state.tagstack[state.tagidx].tags
end
end
-- Go to a particular tag
function M.goto_tag(tag)
io.open_file(tag.filename)
local excmd = tag.excmd
local _, pat = excmd:match("^([?/])(.*)%1$")
if pat then
-- TODO: properly handle regexes and line number tags.
-- For now, assume it's a fixed string possibly with ^ and $ around it.
pat = pat:match("^^?(.-)$?$")
buffer.current_pos = 0
buffer.search_anchor()
local pos = buffer:search_next(buffer.FIND_REGEXP, pat)
if pos >= 0 then
buffer.goto_pos(pos)
else
vi_mode.err("Not found: " .. pat)
end
return
end
-- Try a numeric line number
local pat = excmd:match("^(%d+)$")
if pat then
buffer.goto_line(tonumber(pat)-1)
return
end
-- unknown tag pattern
vi_mode.err('Tag pat: '..excmd)
end
-- Return the next tag at this level, or nil.
function M.tag_next()
local taglist = state.tagstack[state.tagidx]
if taglist.i < #taglist.tags then
taglist.i = taglist.i + 1
return taglist.tags[taglist.i]
end
end
-- Return the next tag at this level, or nil.
function M.tag_prev()
local taglist = state.tagstack[state.tagidx]
if taglist.i > 1 then
taglist.i = taglist.i - 1
return taglist.tags[taglist.i]
end
end
return M
|
local M = {}
local state = {
tags = nil, -- current set of tags
tagstack = {},-- current tag stack: list of { i=num, tags={tag list} }
tagidx = 0, -- index into tagstack of current level
lasttag = nil,-- last tag list
timestamp = nil, -- tags file modification time.
}
M.state = state
-- Load a tags file
local function load_tags()
vi_mode.err("Loading tags file...")
local tagf = io.open("tags") -- TODO: configurable tags file location
local results = {}
local pat = "^([^\t]*)\t([^\t]*)\t(.*)$"
if tagf then
state.timestamp = lfs.attributes("tags", "modification")
for line in tagf:lines() do
local tname, fname, excmd = line:match(pat)
local flags
if tname then
-- Initialise to an empty list if necessary
if not results[tname] then results[tname] = {} end
-- And append.
local l = results[tname] -- now guaranteed to be a table
do
-- Try to separate the ex command from extension fields
local e,f = excmd:match('^(.-);"\t(.*)$')
if e then
excmd = e
flags = f
end
end
l[#l+1] = { sym=tname, filename=fname, excmd=excmd, flags=flags }
end
end
tagf:close()
end
state.tags = results
end
-- Return or load the tags
local function get_tags()
-- TODO: check if tags file needs reloading
if state.tags == nil or lfs.attributes("tags", "modification") ~= state.timestamp then
load_tags()
end
return state.tags
end
function M.find_tag_exact(name)
local tags = get_tags()
local result = tags[name]
if result then
local newidx = state.tagidx + 1
-- Clear the stack above where we are.
while newidx <= #state.tagstack do
state.tagstack[#state.tagstack] = nil
end
state.tagstack[newidx] = {
i=1, -- which tag within this list
tags=result, -- this level's tags
fromname=buffer.filename, -- where we came from
frompos=buffer.current_pos,-- where we came from
}
state.lasttag = result
state.tagidx = newidx
return result[1]
else
return nil
end
end
-- Return a list of tags matching Lua pat
function M.match_tag(pat)
local tags = get_tags()
local result = {}
for name,_ in pairs(tags) do
if name:match(pat) then
result[#result+1] = name
end
end
if #result > 0 then return result end
-- return nil if nothing found
end
function M.pop_tag()
if state.tagidx >= 1 then
local tos = state.tagstack[state.tagidx]
io.open_file(tos.fromname)
buffer.goto_pos(tos.frompos)
state.tagidx = state.tagidx - 1
else
vi_mode.err("Top of stack")
end
end
-- Return all the tags in the current level
function M.get_all()
if state.tagidx > 0 then
return state.tagstack[state.tagidx].tags
end
end
-- Go to a particular tag
function M.goto_tag(tag)
io.open_file(tag.filename)
local excmd = tag.excmd
local _, pat = excmd:match("^([?/])(.*)%1$")
if pat then
-- TODO: properly handle regexes and line number tags.
-- For now, assume it's a fixed string possibly with ^ and $ around it.
pat = pat:match("^^?(.-)$?$")
-- Tag file regexes are treated as in vim's nomagic; ie most special
-- characters are only magic if backquoted (except .).
-- This is an approximation for now.
pat = pat:gsub("(%\\?)([%[%]*+])", function(pre, magic)
if pre ~= "" then
return pre .. magic
else
return "\\" .. magic
end
end)
buffer.current_pos = 0
buffer.search_anchor()
local pos = buffer:search_next(buffer.FIND_REGEXP, pat)
if pos >= 0 then
buffer.goto_pos(pos)
else
vi_mode.err("Not found: " .. pat)
end
return
end
-- Try a numeric line number
local pat = excmd:match("^(%d+)$")
if pat then
buffer.goto_line(tonumber(pat)-1)
return
end
-- unknown tag pattern
vi_mode.err('Tag pat: '..excmd)
end
-- Return the next tag at this level, or nil.
function M.tag_next()
local taglist = state.tagstack[state.tagidx]
if taglist.i < #taglist.tags then
taglist.i = taglist.i + 1
return taglist.tags[taglist.i]
end
end
-- Return the next tag at this level, or nil.
function M.tag_prev()
local taglist = state.tagstack[state.tagidx]
if taglist.i > 1 then
taglist.i = taglist.i - 1
return taglist.tags[taglist.i]
end
end
return M
|
Make an attempt to convert regular expressions in tag search patterns to the right format. This fixes jumping to tags for functions with pointer arguments.
|
Make an attempt to convert regular expressions in tag search patterns to the right
format. This fixes jumping to tags for functions with pointer arguments.
|
Lua
|
mit
|
jugglerchris/textadept-vi,erig0/textadept-vi,jugglerchris/textadept-vi
|
8072eac3ed1453803a64fa8d21100e67bc1315a4
|
share/lua/website/videobash.lua
|
share/lua/website/videobash.lua
|
-- libquvi-scripts
-- Copyright (C) 2011 Thomas Preud'homme <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident (self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "videobash%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/video_show/"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse (self)
self.host_id = "videobash"
local page = quvi.fetch(self.page_url)
local _,_,s = page:find("<title>(.-)%s+-")
self.title = s or error ("no match: media title")
local _,_,s = page:find("addFavorite%((%d+)")
self.id = s or error ("no match: media id")
local s = page:match('video_url="(.-);')
or error("no match: media url")
s = s:gsub("['%s+]",'')
self.url = {s}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2011 Thomas Preud'homme <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident (self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "videobash%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/video_show/"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse (self)
self.host_id = "videobash"
local page = quvi.fetch(self.page_url)
local _,_,s = page:find("<title>(.-)%s+-")
self.title = s or error ("no match: media title")
local _,_,s = page:find("addFavorite%((%d+)")
self.id = s or error ("no match: media id")
local s = page:match('video_url=(.-)&')
or error("no match: media url")
local U = require 'quvi/util'
self.url = {U.unescape(s)}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: videobash.lua: media URL pattern
|
FIX: videobash.lua: media URL pattern
* Fix "error: videobash.lua:54: no match: media url"
* Unescape media URL
|
Lua
|
agpl-3.0
|
legatvs/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts,DangerCove/libquvi-scripts,DangerCove/libquvi-scripts,hadess/libquvi-scripts-iplayer,legatvs/libquvi-scripts,hadess/libquvi-scripts-iplayer
|
63dc89a24c054aa7c53e37c0bf6340fd07a73539
|
Abillist.lua
|
Abillist.lua
|
--[[
This module prints the list of all Pokémon, alternative forms included, having
a given ability.
--]]
local k = {}
local mw = require('mw')
local abillib = require('Wikilib-abils')
local box = require('Box')
local css = require('Css')
local links = require('Links')
local list = require('Wikilib-lists')
--local mg = require('Wikilib-multigen')
local ms = require('MiniSprite')
local oop = require('Wikilib-oop')
local tab = require('Wikilib-tables') -- luacheck: no unused
local txt = require('Wikilib-strings') -- luacheck: no unused
local pokes = require('Poké-data')
--[[
Class representing a list entry. Fulfills requirements of makeList, sortNdex
and sortForms of Wikilib/lists
--]]
local Entry = oop.makeClass(list.PokeSortableEntry)
Entry.printTypeBox = function(type, typesCount)
return box.boxTipoLua(
string.fu(type),
'text-center roundy-5',
string.interp('padding: 0 0.5ex; margin-bottom: 0.2ex; height: ${width}%;',
{width = 100 / typesCount})
)
end
--[[
Printing ability is a complex job: event have to be handled, as well as
generation changes. The first argumetn is the ability to be printed, the second
one whether it should be marked or not, to be used for events.
--]]
Entry.printAbil = function(abil, marked)
if not abil then
return marked and '' or 'Nessuna'
end
-- Marked abilities are italic
local toHTML
if marked then
toHTML = function(ability)
return string.interp([=[<div>''${abil}''</div>]=],
{
abil = links.aColor(ability, '000'),
})
end
else
toHTML = links.aColor
end
if type(abil) == 'string' then
return toHTML(abil, '000')
end
-- Adding generations superscripts
return table.concat(table.map(abillib.abilspan(abil), function(v)
return string.interp(
'<div>${abil}<sup>${gen}</sup></div>',
{
abil = v.abil == 'Nessuna' and v.abil
or toHTML(v.abil, '000'),
gen = v.first == v.last and v.first
or table.concat{v.first, '-', v.last}
})
end))
end
--[[
Constructor: the first argument is an entry from Poké/data, the second one its
key and the third is the ability the Pokémon must have. As specified by
makeList in Wikilib/lists, returns nil whenever the Pokémon can not have the
ability.
--]]
Entry.new = function(pokeAbil, name, abil)
if not table.deepSearch(pokeAbil, abil) then
return nil
end
local this = Entry.super.new(name, pokes[name].ndex)
this = table.merge(this, pokeAbil)
return setmetatable(table.merge(this, pokes[name]), Entry)
end
-- Wikicode for a list entry: Pokémon mini sprite, name, types and abilities.
Entry.__tostring = function(this)
local typesCount = this.type1 == this.type2 and 1 or 2
return string.interp([=[| ${static}
| class="hidden-xs" | ${name}${form}
| class="hidden-xs" style="padding: 1ex 0.8ex; font-size: 90%;" | ${type1}${type2}
| ${abil1}${abilEv}
| ${abil2}
| ${abild}]=],
{
static = ms.staticLua(string.tf(this.ndex or 0) ..
(this.formAbbr == 'base' and '' or this.formAbbr or '')),
name = this.name,
form = this.formsData
and this.formsData.blacklinks[this.formAbbr]
or '',
type1 = Entry.printTypeBox(this.type1, typesCount),
type2 = typesCount == 1 and ''
or Entry.printTypeBox(this.type2, typesCount),
abil1 = Entry.printAbil(this.ability1),
abilEv = Entry.printAbil(this.abilitye, true),
abil2 = Entry.printAbil(this.ability2),
abild = Entry.printAbil(this.abilityd),
})
end
-- Wikicode for list header: it takes the type name, for colors
local makeHeader = function(type)
return string.interp([=[{| class="roundy text-center pull-center white-rows" style="border-spacing: 0; padding: 0.3ex; ${bg};"
|-
! style="padding-top: 0.5ex; padding-bottom: 0.5ex;" | [[Elenco Pokémon secondo il Pokédex Nazionale|<span style="color:#000;">#</span>]]
! class="hidden-xs" | Pokémon
! class="hidden-xs" | [[Tipo|<span style="color:#000;">Tipi</span>]]
! Prima abilità
! Seconda abilità
! Abilità nascosta]=],
{
bg = css.horizGradLua{type = type}
})
end
--[[
Funzione d'interfaccia: si passano il tipo per il colore
e il titolo della pagina, da cui si ricava quello
dell'abilità.
--]]
k.abillist = function(frame)
local type = string.trim(frame.args[1]) or 'pcwiki'
local abil = string.trim(mw.text.decode(frame.args[2]))
abil = abil:match('^(.+) %(abilità%)') or 'Cacofonia'
return list.makeList({
source = require('PokéAbil-data'),
iterator = list.pokeNames,
entryArgs = abil,
makeEntry = Entry.new,
header = makeHeader(type),
footer = [[| class="text-left font-small" colspan="6" style="background: transparent; padding: 0.3ex 0.3em;" |
* Le abilità in ''corsivo'' sono ottenibili solo in determinate circostanze.
|}]]
})
end
k.Abillist = k.abillist
return k
|
--[[
This module prints the list of all Pokémon, alternative forms included, having
a given ability.
--]]
local k = {}
local mw = require('mw')
local abillib = require('Wikilib-abils')
local box = require('Box')
local css = require('Css')
local links = require('Links')
local list = require('Wikilib-lists')
local ms = require('MiniSprite')
local oop = require('Wikilib-oop')
local tab = require('Wikilib-tables') -- luacheck: no unused
local txt = require('Wikilib-strings') -- luacheck: no unused
local pokes = require('Poké-data')
--[[
Class representing a list entry. Fulfills requirements of makeList, sortNdex
and sortForms of Wikilib/lists
--]]
local Entry = oop.makeClass(list.PokeSortableEntry)
Entry.printTypeBox = function(type, typesCount)
return box.boxTipoLua(
string.fu(type),
'text-center roundy-5',
string.interp('padding: 0 0.5ex; margin-bottom: 0.2ex; height: ${width}%;',
{width = 100 / typesCount})
)
end
--[[
Printing ability is a complex job: event have to be handled, as well as
generation changes. The first argumetn is the ability to be printed, the second
one whether it should be marked or not, to be used for events.
--]]
Entry.printAbil = function(abil, marked)
if not abil then
return marked and '' or 'Nessuna'
end
-- Marked abilities are italic
local toHTML
if marked then
toHTML = function(ability)
return string.interp([=[<div>''${abil}''</div>]=],
{
abil = links.aColor(ability, '000'),
})
end
else
toHTML = links.aColor
end
if type(abil) == 'string' then
return toHTML(abil, '000')
end
-- Adding generations superscripts
return table.concat(table.map(abillib.abilspan(abil), function(v)
return string.interp(
'<div>${abil}<sup>${gen}</sup></div>',
{
abil = v.abil == 'Nessuna' and v.abil
or toHTML(v.abil, '000'),
gen = v.first == v.last and v.first
or table.concat{v.first, '-', v.last}
})
end))
end
--[[
Constructor: the first argument is an entry from Poké/data, the second one its
key and the third is the ability the Pokémon must have. As specified by
makeList in Wikilib/lists, returns nil whenever the Pokémon can not have the
ability.
--]]
Entry.new = function(pokeAbil, name, abil)
if not table.deepSearch(pokeAbil, abil) then
return nil
end
local this = Entry.super.new(name, pokes[name].ndex)
this = table.merge(this, pokeAbil)
return setmetatable(table.merge(this, pokes[name]), Entry)
end
-- Wikicode for a list entry: Pokémon mini sprite, name, types and abilities.
Entry.__tostring = function(this)
local typesCount = this.type1 == this.type2 and 1 or 2
return string.interp([=[| ${static}
| class="hidden-xs" | ${name}${form}
| class="hidden-xs" style="padding: 1ex 0.8ex; font-size: 90%;" | ${type1}${type2}
| ${abil1}${abilEv}
| ${abil2}
| ${abild}]=],
{
static = ms.staticLua(string.tf(this.ndex or 0) ..
(this.formAbbr == 'base' and '' or this.formAbbr or '')),
name = this.name,
form = this.formsData
and this.formsData.blacklinks[this.formAbbr]
or '',
type1 = Entry.printTypeBox(this.type1, typesCount),
type2 = typesCount == 1 and ''
or Entry.printTypeBox(this.type2, typesCount),
abil1 = Entry.printAbil(this.ability1),
abilEv = Entry.printAbil(this.abilitye, true),
abil2 = Entry.printAbil(this.ability2),
abild = Entry.printAbil(this.abilityd),
})
end
-- Wikicode for list header: it takes the type name, for colors
local makeHeader = function(type)
return string.interp([=[{| class="roundy text-center pull-center white-rows" style="border-spacing: 0; padding: 0.3ex; ${bg};"
|-
! style="padding-top: 0.5ex; padding-bottom: 0.5ex;" | [[Elenco Pokémon secondo il Pokédex Nazionale|<span style="color:#000;">#</span>]]
! class="hidden-xs" | Pokémon
! class="hidden-xs" | [[Tipo|<span style="color:#000;">Tipi</span>]]
! Prima abilità
! Seconda abilità
! Abilità nascosta]=],
{
bg = css.horizGradLua{type = type}
})
end
--[[
Funzione d'interfaccia: si passano il tipo per il colore
e il titolo della pagina, da cui si ricava quello
dell'abilità.
--]]
k.abillist = function(frame)
local type = string.trim(frame.args[1]) or 'pcwiki'
local abil = string.trim(mw.text.decode(frame.args[2]))
abil = abil:match('^(.+) %(abilità%)') or 'Cacofonia'
return list.makeList({
source = require('PokéAbil-data'),
iterator = list.pokeNames,
entryArgs = abil,
makeEntry = Entry.new,
header = makeHeader(type),
footer = [[| class="text-left font-small" colspan="6" style="background: transparent; padding: 0.3ex 0.3em;" |
* Le abilità in ''corsivo'' sono ottenibili solo in determinate circostanze.
|}]]
})
end
k.Abillist = k.abillist
return k
|
Just removing an import, but the last burst of commit fixed pokemoncentral/wiki-project#15
|
Just removing an import, but the last burst of commit fixed pokemoncentral/wiki-project#15
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
6428e5664ef717099417c71f2f9e6c23719f875a
|
src/lua/Parallel.lua
|
src/lua/Parallel.lua
|
local zmq = require "lzmq"
local zloop = require "lzmq.loop"
local zthreads = require "lzmq.threads"
local mp = require "cmsgpack"
local zassert = zmq.assert
local ENDPOINT = "inproc://main"
local THREAD_STARTER = [[
local ENDPOINT = ]] .. ("%q"):format(ENDPOINT) .. [[
local zmq = require "lzmq"
local zthreads = require "lzmq.threads"
local mp = require "cmsgpack"
local zassert = zmq.assert
function FOR(do_work)
local ctx = zthreads.get_parent_ctx()
local s, err = ctx:socket{zmq.DEALER, connect = ENDPOINT}
if not s then return end
s:sendx(0, 'READY')
while not s:closed() do
local tid, cmd, args = s:recvx()
if not tid then
if cmd and (cmd:no() == zmq.errors.ETERM) then break end
zassert(nil, cmd)
end
assert(tid and cmd)
if cmd == 'END' then break end
assert(cmd == 'TASK', "invalid command " .. tostring(cmd))
assert(args, "invalid args in command")
local res, err = mp.pack( do_work(mp.unpack(args)) )
s:sendx(tid, 'RESP', res)
end
ctx:destroy()
end
]]
local function pcall_ret_pack(ok, ...)
if ok then return mp.pack(ok, ...) end
return nil, ...
end
local function pcall_ret(ok, ...)
if ok then return pcall_ret_pack(...) end
return nil, ...
end
local function ppcall(...)
return pcall_ret(pcall(...))
end
local function thread_alive(self)
local ok, err = self:join(0)
if ok then return false end
if err == 'timeout' then return true end
return nil, err
end
local function parallel_for_impl(code, src, snk, N, cache_size)
N = N or 4
zthreads.set_bootstrap_prelude(THREAD_STARTER)
local src_err, snk_err
local loop = zloop.new()
function loop:add_thread(code, ...)
return zthreads.run(self:context(), code, ... )
end
local cache = {} -- заранее рассчитанные данные для заданий
local threads = {} -- рабочие потоки
local MAX_CACHE = cache_size or N
local function call_src()
if src and not src_err then
local args, err = ppcall(src)
if args then return args end
if err then
src_err = err
return nil, err
end
src = nil
end
end
local function next_src()
local args = table.remove(cache, 1)
if args then return args end
return call_src()
end
local function cache_src()
if #cache >= MAX_CACHE then return end
for i = #cache, MAX_CACHE do
local args = call_src()
if args then cache[#cache + 1] = args else break end
end
end
local skt, err = loop:create_socket{zmq.ROUTER, bind = ENDPOINT}
zassert(skt, err)
loop:add_socket(skt, function(skt)
local identity, tid, cmd, args = skt:recvx()
zassert(tid, cmd)
if cmd ~= 'READY' then
assert(cmd == 'RESP')
if not snk_err then
if snk then
local ok, err = ppcall(snk, mp.unpack(args))
if not ok and err then snk_err = err end
end
else
skt:sendx(identity, tid, 'END')
return
end
end
if #cache == 0 then cache_src() end
local args, err = next_src()
if args ~= nil then
skt:sendx(identity, tid, 'TASK', args)
return
end
skt:sendx(identity, tid, 'END')
end)
-- watchdog
loop:add_interval(1000, function()
local alive = 0
for _, thread in ipairs(threads) do
if thread_alive(thread) then alive = alive + 1 end
end
if alive == 0 then loop:interrupt() end
end)
loop:add_interval(100, function(ev) cache_src() end)
for i = 1, N do
local thread = loop:add_thread(code, i)
thread:start(true, true)
threads[#threads + 1] = thread
end
loop:start()
loop:destroy()
for _, t in ipairs(threads) do t:join() end
if src_err or snk_err then
return nil, src_err or snk_err
end
return true
end
---
-- @tparam[number] be begin index
-- @tparam[number] en end index
-- @tparam[number?] step step
-- @tparam[string] code
-- @tparam[callable?] snk sink
-- @tparam[number?] N thread count
-- @tparam[number?] C cache size
local function For(be, en, step, code, snk, N, C)
if type(step) ~= 'number' then -- no step
step, code, snk, N, C = 1, step, code, snk, N
end
if type(snk) == 'number' then -- no sink
N, C = snk, N
end
assert(type(be) == "number")
assert(type(en) == "number")
assert(type(step) == "number")
assert(type(code) == "string")
local src = function()
if be > en then return end
local n = be
be = be + step
return n
end
return parallel_for_impl(code, src, snk, N, C)
end
---
-- @tparam[string] code
-- @tparam[callable?] snk sink
-- @tparam[number?] N thread count
-- @tparam[number?] C cache size
local function ForEach(it, code, snk, N, C)
local src = it
if type(it) == 'table' then
local k, v
src = function()
k, v = next(it, k)
return k, v
end
end
if type(snk) == 'number' then -- no sink
snk, N, C = nil, snk, N
end
assert(type(src) == "function")
assert(type(code) == "string")
return parallel_for_impl(code, src, snk, N, C)
end
local function Invoke(N, ...)
local code = string.dump(function() FOR(function(_,src)
if src:sub(1,1) == '@' then dofile(src:sub(2))
else assert((loadstring or load)(src))() end
end) end)
if type(N) == 'number' then
return ForEach({...}, code, N)
end
return ForEach({N, ...}, code)
end
local Parallel = {} do
Parallel.__index = Parallel
function Parallel:new(N)
local o = setmetatable({
thread_count = N or 4;
}, self)
o.cache_size = o.thread_count * 2
return o
end
function Parallel:For(be, en, step, code, snk)
return For(be, en, step, code, snk, self.thread_count, self.cache_size)
end
function Parallel:ForEach(src, code, snk)
return ForEach(src, code, snk, self.thread_count, self.cache_size)
end
function Parallel:Invoke(...)
return ForEach(self.thread_count, ...)
end
end
return {
For = For;
ForEach = ForEach;
Invoke = Invoke;
New = function(...) return Parallel:new(...) end
}
|
local zmq = require "lzmq"
local zloop = require "lzmq.loop"
local zthreads = require "lzmq.threads"
local mp = require "cmsgpack"
local zassert = zmq.assert
local ENDPOINT = "inproc://main"
local THREAD_STARTER = [[
local ENDPOINT = ]] .. ("%q"):format(ENDPOINT) .. [[
local zmq = require "lzmq"
local zthreads = require "lzmq.threads"
local mp = require "cmsgpack"
local zassert = zmq.assert
function FOR(do_work)
local ctx = zthreads.get_parent_ctx()
local s, err = ctx:socket{zmq.DEALER, connect = ENDPOINT}
if not s then return end
s:sendx(0, 'READY')
while not s:closed() do
local tid, cmd, args = s:recvx()
if not tid then
if cmd and (cmd:no() == zmq.errors.ETERM) then break end
zassert(nil, cmd)
end
assert(tid and cmd)
if cmd == 'END' then break end
assert(cmd == 'TASK', "invalid command " .. tostring(cmd))
assert(args, "invalid args in command")
local res, err = mp.pack( do_work(mp.unpack(args)) )
s:sendx(tid, 'RESP', res)
end
ctx:destroy()
end
]]
local function pcall_ret_pack(ok, ...)
if ok then return mp.pack(ok, ...) end
return nil, ...
end
local function pcall_ret(ok, ...)
if ok then return pcall_ret_pack(...) end
return nil, ...
end
local function ppcall(...)
return pcall_ret(pcall(...))
end
local function thread_alive(self)
local ok, err = self:join(0)
if ok then return false end
if err == 'timeout' then return true end
return nil, err
end
local function parallel_for_impl(code, src, snk, N, cache_size)
N = N or 4
-- @fixme do not change global state in zthreads library
zthreads.set_bootstrap_prelude(THREAD_STARTER)
local src_err, snk_err
local cache = {} -- заранее рассчитанные данные для заданий
local threads = {} -- рабочие потоки
local MAX_CACHE = cache_size or N
local function call_src()
if src and not src_err then
local args, err = ppcall(src)
if args then return args end
if err then
src_err = err
return nil, err
end
src = nil
end
end
local function next_src()
local args = table.remove(cache, 1)
if args then return args end
return call_src()
end
local function cache_src()
if #cache >= MAX_CACHE then return end
for i = #cache, MAX_CACHE do
local args = call_src()
if args then cache[#cache + 1] = args else break end
end
end
local loop = zloop.new()
local skt, err = loop:create_socket{zmq.ROUTER, bind = ENDPOINT}
zassert(skt, err)
loop:add_socket(skt, function(skt)
local identity, tid, cmd, args = skt:recvx()
zassert(tid, cmd)
if cmd ~= 'READY' then
assert(cmd == 'RESP')
if not snk_err then
if snk then
local ok, err = ppcall(snk, mp.unpack(args))
if not ok and err then snk_err = err end
end
else
skt:sendx(identity, tid, 'END')
return
end
end
if #cache == 0 then cache_src() end
local args, err = next_src()
if args ~= nil then
skt:sendx(identity, tid, 'TASK', args)
return
end
skt:sendx(identity, tid, 'END')
end)
-- watchdog
loop:add_interval(1000, function()
local alive = 0
for _, thread in ipairs(threads) do
if thread_alive(thread) then alive = alive + 1 end
end
if alive == 0 then loop:interrupt() end
end)
loop:add_interval(100, function(ev) cache_src() end)
local err
for i = 1, N do
local thread
thread, err = zthreads.run(loop:context(), code, i)
if thread and thread:start(true, true) then
threads[#threads + 1] = thread
end
end
if #threads == 0 then return nil, err end
loop:start()
loop:destroy()
for _, t in ipairs(threads) do t:join() end
if src_err or snk_err then
return nil, src_err or snk_err
end
return true
end
---
-- @tparam[number] be begin index
-- @tparam[number] en end index
-- @tparam[number?] step step
-- @tparam[string] code
-- @tparam[callable?] snk sink
-- @tparam[number?] N thread count
-- @tparam[number?] C cache size
local function For(be, en, step, code, snk, N, C)
if type(step) ~= 'number' then -- no step
step, code, snk, N, C = 1, step, code, snk, N
end
if type(snk) == 'number' then -- no sink
N, C = snk, N
end
assert(type(be) == "number")
assert(type(en) == "number")
assert(type(step) == "number")
assert(type(code) == "string")
local src = function()
if be > en then return end
local n = be
be = be + step
return n
end
return parallel_for_impl(code, src, snk, N, C)
end
---
-- @tparam[string] code
-- @tparam[callable?] snk sink
-- @tparam[number?] N thread count
-- @tparam[number?] C cache size
local function ForEach(it, code, snk, N, C)
local src = it
if type(it) == 'table' then
local k, v
src = function()
k, v = next(it, k)
return k, v
end
end
if type(snk) == 'number' then -- no sink
snk, N, C = nil, snk, N
end
assert(type(src) == "function")
assert(type(code) == "string")
return parallel_for_impl(code, src, snk, N, C)
end
local function Invoke(N, ...)
local code = string.dump(function() FOR(function(_,src)
if src:sub(1,1) == '@' then dofile(src:sub(2))
else assert((loadstring or load)(src))() end
end) end)
if type(N) == 'number' then
return ForEach({...}, code, N)
end
return ForEach({N, ...}, code)
end
local Parallel = {} do
Parallel.__index = Parallel
function Parallel:new(N)
local o = setmetatable({
thread_count = N or 4;
}, self)
o.cache_size = o.thread_count * 2
return o
end
function Parallel:For(be, en, step, code, snk)
return For(be, en, step, code, snk, self.thread_count, self.cache_size)
end
function Parallel:ForEach(src, code, snk)
return ForEach(src, code, snk, self.thread_count, self.cache_size)
end
function Parallel:Invoke(...)
return ForEach(self.thread_count, ...)
end
end
return {
For = For;
ForEach = ForEach;
Invoke = Invoke;
New = function(...) return Parallel:new(...) end
}
|
Fix. check creation work thread.
|
Fix. check creation work thread.
|
Lua
|
mit
|
moteus/lua-Parallel,kidaa/lua-Parallel
|
099e5bd55a17f67e0510784a726abce8ce5c5e33
|
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
|
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ipaddr, adv_interface, adv_subnet
local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network"))
adv_interface.widget = "checkbox"
adv_interface.exclude = arg[1]
adv_interface.default = "lan"
adv_interface.template = "cbi/network_netlist"
adv_interface.nocreate = true
adv_interface.nobridges = true
adv_interface.novirtual = true
function adv_interface.remove(self, section)
self:write(section, " ")
end
adv_subnet = section:taboption("general", Value, "adv_subnet",
translate("Advertised network ID"),
translate("Allowed range is 1 to 65535"))
adv_subnet.placeholder = "1"
adv_subnet.datatype = "range(1,65535)"
function adv_subnet.cfgvalue(self, section)
local v = Value.cfgvalue(self, section)
return v and tonumber(v, 16)
end
function adv_subnet .write(self, section, value)
value = tonumber(value) or 1
if value > 65535 then value = 65535
elseif value < 1 then value = 1 end
Value.write(self, section, "%X" % value)
end
adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime",
translate("Use valid lifetime"),
translate("Specifies the advertised valid prefix lifetime in seconds"))
adv_valid_lifetime.placeholder = "300"
adv_valid_lifetime.datatype = "uinteger"
adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime",
translate("Use preferred lifetime"),
translate("Specifies the advertised preferred prefix lifetime in seconds"))
adv_preferred_lifetime.placeholder = "120"
adv_preferred_lifetime.datatype = "uinteger"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(1500)"
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ipaddr, adv_interface, adv_subnet
local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network"))
adv_interface.widget = "checkbox"
adv_interface.exclude = arg[1]
adv_interface.default = "lan"
adv_interface.template = "cbi/network_netlist"
adv_interface.nocreate = true
adv_interface.nobridges = true
adv_interface.novirtual = true
function adv_interface.write(self, section, value)
if type(value) == "table" then
Value.write(self, section, table.concat(value, " "))
else
Value.write(self, section, value)
end
end
function adv_interface.remove(self, section)
self:write(section, " ")
end
adv_subnet = section:taboption("general", Value, "adv_subnet",
translate("Advertised network ID"),
translate("Allowed range is 1 to 65535"))
adv_subnet.placeholder = "1"
adv_subnet.datatype = "range(1,65535)"
function adv_subnet.cfgvalue(self, section)
local v = Value.cfgvalue(self, section)
return v and tonumber(v, 16)
end
function adv_subnet .write(self, section, value)
value = tonumber(value) or 1
if value > 65535 then value = 65535
elseif value < 1 then value = 1 end
Value.write(self, section, "%X" % value)
end
adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime",
translate("Use valid lifetime"),
translate("Specifies the advertised valid prefix lifetime in seconds"))
adv_valid_lifetime.placeholder = "300"
adv_valid_lifetime.datatype = "uinteger"
adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime",
translate("Use preferred lifetime"),
translate("Specifies the advertised preferred prefix lifetime in seconds"))
adv_preferred_lifetime.placeholder = "120"
adv_preferred_lifetime.datatype = "uinteger"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(1500)"
|
proto/6x4: cast 6to4 adv_interface to string when saving to uci, fixes 6in4.sh not picking up the adv interfaces
|
proto/6x4: cast 6to4 adv_interface to string when saving to uci, fixes 6in4.sh not picking up the adv interfaces
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@9009 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ch3n2k/luci,Canaan-Creative/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,8devices/carambola2-luci,eugenesan/openwrt-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,phi-psi/luci,vhpham80/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,gwlim/luci,phi-psi/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,vhpham80/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,phi-psi/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,ch3n2k/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,vhpham80/luci,gwlim/luci,Canaan-Creative/luci,gwlim/luci,phi-psi/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,8devices/carambola2-luci,8devices/carambola2-luci,phi-psi/luci,ch3n2k/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,phi-psi/luci,vhpham80/luci,gwlim/luci,8devices/carambola2-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,gwlim/luci,8devices/carambola2-luci,freifunk-gluon/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,Canaan-Creative/luci,gwlim/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci
|
89fe3e305129e537088fe9ec6e6970c85265d72e
|
spec/unit/defaults_spec.lua
|
spec/unit/defaults_spec.lua
|
describe("defaults module", function()
local Defaults, DataStorage
setup(function()
require("commonrequire")
Defaults = require("apps/filemanager/filemanagersetdefaults")
DataStorage = require("datastorage")
end)
it("should load all defaults from defaults.lua", function()
Defaults:init()
assert.is_same(#Defaults.defaults_name, 77)
assert.is_same(Defaults.defaults_name[28], 'DHINTCOUNT')
end)
it("should save changes to defaults.persistent.lua", function()
local persistent_filename = DataStorage:getDataDir() .. "/defaults.persistent.lua"
os.remove(persistent_filename)
-- not in persistent but checked in defaults
Defaults.changed[11] = true
Defaults.changed[19] = true
Defaults.changed[28] = true
Defaults.changed[63] = true
Defaults.changed[77] = true
Defaults:saveSettings()
assert.is_same(#Defaults.defaults_name, 77)
assert.is_same(Defaults.defaults_name[28], 'DHINTCOUNT')
assert.is_same(Defaults.defaults_name[77], 'SEARCH_TITLE')
assert.is_same(Defaults.defaults_name[63], 'DTAP_ZONE_MENU')
assert.is_same(Defaults.defaults_name[19], 'DCREREADER_VIEW_MODE')
assert.is_same(Defaults.defaults_name[11],
'DCREREADER_CONFIG_MARGIN_SIZES_LARGE')
local fd = io.open(persistent_filename, "r")
assert.Equals(
[[-- For configuration changes that persists between updates
SEARCH_TITLE = true
DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {
[1] = 20,
[2] = 20,
[3] = 20,
[4] = 20
}
DCREREADER_VIEW_MODE = "page"
DHINTCOUNT = 1
DTAP_ZONE_MENU = {
["y"] = 0,
["x"] = 0.125,
["h"] = 0.125,
["w"] = 0.75
}
]],
fd:read("*a"))
fd:close()
-- in persistent
Defaults:init()
Defaults.changed[28] = true
Defaults.defaults_value[28] = 2
Defaults.changed[63] = true
Defaults.defaults_value[63] = {
y = 10,
x = 10.125,
h = 20.25,
w = 20.75
}
Defaults:saveSettings()
fd = io.open(persistent_filename)
assert.Equals(
[[-- For configuration changes that persists between updates
SEARCH_TITLE = true
DHINTCOUNT = 2
DTAP_ZONE_MENU = {
["y"] = 10,
["x"] = 10.125,
["h"] = 20.25,
["w"] = 20.75
}
DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {
[1] = 20,
[2] = 20,
[3] = 20,
[4] = 20
}
DCREREADER_VIEW_MODE = "page"
]],
fd:read("*a"))
fd:close()
os.remove(persistent_filename)
end)
it("should delete entry from defaults.persistent.lua if value is reverted back to default", function()
local persistent_filename = DataStorage:getDataDir() .. "/defaults.persistent.lua"
local fd = io.open(persistent_filename, "w")
fd:write(
[[-- For configuration changes that persists between updates
SEARCH_TITLE = true
DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {
[1] = 20,
[2] = 20,
[3] = 20,
[4] = 20
}
DCREREADER_VIEW_MODE = "page"
DHINTCOUNT = 2
]])
fd:close()
-- in persistent
Defaults:init()
Defaults.changed[28] = true
Defaults.defaults_value[28] = 1
Defaults:saveSettings()
fd = io.open(persistent_filename)
assert.Equals(
[[-- For configuration changes that persists between updates
SEARCH_TITLE = true
DCREREADER_VIEW_MODE = "page"
DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {
[1] = 20,
[2] = 20,
[3] = 20,
[4] = 20
}
]],
fd:read("*a"))
fd:close()
os.remove(persistent_filename)
end)
end)
|
describe("defaults module", function()
local Defaults, DataStorage
setup(function()
require("commonrequire")
Defaults = require("apps/filemanager/filemanagersetdefaults")
DataStorage = require("datastorage")
end)
it("should load all defaults from defaults.lua", function()
Defaults:init()
assert.is_same(82, #Defaults.defaults_name)
assert.is_same("DFULL_SCREEN", Defaults.defaults_name[28])
end)
it("should save changes to defaults.persistent.lua", function()
local persistent_filename = DataStorage:getDataDir() .. "/defaults.persistent.lua"
os.remove(persistent_filename)
-- not in persistent but checked in defaults
Defaults.changed[11] = true
Defaults.changed[19] = true
Defaults.changed[28] = true
Defaults.changed[63] = true
Defaults.changed[77] = true
Defaults:saveSettings()
assert.is_same(82, #Defaults.defaults_name)
assert.is_same("DFULL_SCREEN", Defaults.defaults_name[28])
assert.is_same("SEARCH_LIBRARY_PATH", Defaults.defaults_name[77])
assert.is_same("DTAP_ZONE_BACKWARD", Defaults.defaults_name[63])
assert.is_same("DCREREADER_CONFIG_WORD_GAP_LARGE", Defaults.defaults_name[19])
assert.is_same("DCREREADER_CONFIG_MARGIN_SIZES_HUGE", Defaults.defaults_name[11])
local fd = io.open(persistent_filename, "r")
assert.Equals(
[[-- For configuration changes that persists between updates
SEARCH_LIBRARY_PATH = ""
DTAP_ZONE_BACKWARD = {
["y"] = 0,
["x"] = 0,
["h"] = 1,
["w"] = 0.25
}
DCREREADER_CONFIG_WORD_GAP_LARGE = 100
DFULL_SCREEN = 1
DCREREADER_CONFIG_MARGIN_SIZES_HUGE = {
[1] = 100,
[2] = 100,
[3] = 100,
[4] = 100
}
]],
fd:read("*a"))
fd:close()
-- in persistent
Defaults:init()
Defaults.changed[28] = true
Defaults.defaults_value[28] = 2
Defaults.changed[63] = true
Defaults.defaults_value[63] = {
y = 10,
x = 10.125,
h = 20.25,
w = 20.75
}
Defaults:saveSettings()
fd = io.open(persistent_filename)
assert.Equals(
[[-- For configuration changes that persists between updates
SEARCH_LIBRARY_PATH = ""
DTAP_ZONE_BACKWARD = {
["y"] = 10,
["x"] = 10.125,
["h"] = 20.25,
["w"] = 20.75
}
DCREREADER_CONFIG_WORD_GAP_LARGE = 100
DFULL_SCREEN = 2
DCREREADER_CONFIG_MARGIN_SIZES_HUGE = {
[1] = 100,
[2] = 100,
[3] = 100,
[4] = 100
}
]],
fd:read("*a"))
fd:close()
os.remove(persistent_filename)
end)
it("should delete entry from defaults.persistent.lua if value is reverted back to default", function()
local persistent_filename = DataStorage:getDataDir() .. "/defaults.persistent.lua"
local fd = io.open(persistent_filename, "w")
fd:write(
[[-- For configuration changes that persists between updates
SEARCH_TITLE = true
DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {
[1] = 20,
[2] = 20,
[3] = 20,
[4] = 20
}
DCREREADER_VIEW_MODE = "page"
DHINTCOUNT = 2
]])
fd:close()
-- in persistent
Defaults:init()
Defaults.changed[28] = true
Defaults.defaults_value[28] = 1
Defaults:saveSettings()
fd = io.open(persistent_filename)
assert.Equals(
[[-- For configuration changes that persists between updates
SEARCH_TITLE = true
DHINTCOUNT = 2
DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {
[1] = 20,
[2] = 20,
[3] = 20,
[4] = 20
}
DFULL_SCREEN = 1
DCREREADER_VIEW_MODE = "page"
]],
fd:read("*a"))
fd:close()
os.remove(persistent_filename)
end)
end)
|
[spec] Fix defaults_spec
|
[spec] Fix defaults_spec
Updated for https://github.com/koreader/koreader/pull/4691
Also the assert.is_same() argument order was wrong.
The first argument is expected, the second the real-life result.
Otherwise the error message in case of failure is misleading.
|
Lua
|
agpl-3.0
|
koreader/koreader,NiLuJe/koreader,NiLuJe/koreader,koreader/koreader,Frenzie/koreader,mihailim/koreader,Markismus/koreader,poire-z/koreader,poire-z/koreader,pazos/koreader,Hzj-jie/koreader,mwoz123/koreader,houqp/koreader,Frenzie/koreader
|
526140efdd531134e4c2010a4f2415e0e7d1924c
|
lualib/sys/socketdispatch.lua
|
lualib/sys/socketdispatch.lua
|
local socket = require "sys.socket"
local core = require "sys.core"
local pairs = pairs
local assert = assert
local tremove = table.remove
local CONNECTING = 1
local CONNECTED = 2
local CLOSE = 5
local FINAL = 6
local dispatch = {}
local mt = {
__index = dispatch,
__gc = function(tbl)
tbl:close()
end
}
--the function of process response insert into d.funcqueue
function dispatch:create(config)
local d = {
sock = false,
status = CLOSE,
responseco = false,
dispatchco = false,
connectqueue = {},
waitqueue = {},
funcqueue = {}, --process response, return
result_data = {},
--come from config
addr = config.addr,
auth = config.auth,
}
setmetatable(d, mt)
return d
end
local function wakeup_all(self, ret, err)
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
local result_data = self.result_data
local co = tremove(waitqueue, 1)
tremove(funcqueue, 1)
while co do
result_data[co] = err
core.wakeup(co, ret)
co = tremove(waitqueue, 1)
tremove(funcqueue, 1)
end
end
local function doclose(self)
if (self.status == CLOSE) then
return
end
assert(self.sock >= 0)
socket.close(self.sock)
self.sock = false
self.status = CLOSE;
local co = self.responseco
if co then
self.responseco = nil
core.wakeup(co)
end
end
--this function will be run the indepedent coroutine
local function dispatch_response(self)
return function ()
local pcall = core.pcall
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
local result_data = self.result_data
while self.sock do
local co = tremove(waitqueue, 1)
local func = tremove(funcqueue, 1)
if func and co then
local ok, status, data = pcall(func, self)
if ok then
result_data[co] = data
core.wakeup(co, status)
else
result_data[co] = status
core.wakeup(co, false)
doclose(self)
break
end
else
local co = core.running()
self.responseco = co
core.wait(co)
end
end
self.dispatchco = false
wakeup_all(self, false, "disconnected")
end
end
local function waitfor_response(self, response)
local co = core.running()
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
waitqueue[#waitqueue + 1] = co
funcqueue[#funcqueue + 1] = response
if self.responseco then --the first request
local co = self.responseco
self.responseco = nil
core.wakeup(co)
end
local status = core.wait(co)
local result_data = self.result_data
local data = result_data[co]
result_data[co] = nil
return status, data
end
local function waitfor_connect(self)
local co = core.running()
local connectqueue = self.connectqueue
connectqueue[#connectqueue + 1] = co
local status = core.wait(co)
local result_data = self.result_data
local data = result_data[co]
result_data[co] = nil
return status, data
end
local function wakeup_conn(self, success, err)
local result_data = self.result_data
local connectqueue = self.connectqueue
for k, v in pairs(connectqueue) do
result_data[v] = err
core.wakeup(v, success)
connectqueue[k] = nil
end
end
local function tryconnect(self)
local status = self.status
if status == CONNECTED then
return true;
end
if status == FINAL then
return false, "already closed"
end
local res
if status == CLOSE then
local err, sock
self.status = CONNECTING;
sock = socket.connect(self.addr)
if not sock then
res = false
self.status = CLOSE
err = "socketdispatch connect fail"
else
res = true
self.status = CONNECTED;
end
if res then
--wait for responseco exit
while self.dispatchco do
core.sleep(0)
end
self.sock = sock
local auth = self.auth
self.dispatchco = core.fork(dispatch_response(self))
if auth then
local ok, msg
ok, res, msg = core.pcall(auth, self)
if not ok then
res = false
err = res
doclose(self)
elseif not res then
err = msg
doclose(self)
end
end
assert(#self.funcqueue == 0)
assert(#self.waitqueue == 0)
end
wakeup_conn(self, res, err)
return res, err
elseif status == CONNECTING then
return waitfor_connect(self)
else
core.error("[socketdispatch] incorrect call at status:" .. self.status)
end
end
function dispatch:connect()
return tryconnect(self)
end
function dispatch:close()
if self.status == FINAL then
return
end
doclose(self)
self.status = FINAL
return
end
-- the respose function will be called in the socketfifo coroutine
function dispatch:request(cmd, response)
local ok, err = tryconnect(self)
if not ok then
return ok, err
end
local ok = socket.write(self.sock, cmd)
if not ok then
doclose(self)
return nil
end
if not response then
return
end
return waitfor_response(self, response)
end
local function read_write_wrapper(func)
return function (self, p)
return func(self.sock, p)
end
end
dispatch.read = read_write_wrapper(socket.read)
dispatch.write = read_write_wrapper(socket.write)
dispatch.readline = read_write_wrapper(socket.readline)
return dispatch
|
local socket = require "sys.socket"
local core = require "sys.core"
local pairs = pairs
local assert = assert
local tremove = table.remove
local CONNECTING = 1
local CONNECTED = 2
local CLOSE = 5
local FINAL = 6
local dispatch = {}
local mt = {
__index = dispatch,
__gc = function(tbl)
if tbl.sock then
socket.close(tbl.sock)
end
end
}
--the function of process response insert into d.funcqueue
function dispatch:create(config)
local d = {
sock = nil,
status = CLOSE,
authco = nil,
responseco = false,
dispatchco = false,
connectqueue = {},
waitqueue = {},
funcqueue = {}, --process response, return
result_data = {},
--come from config
addr = config.addr,
auth = config.auth,
}
setmetatable(d, mt)
return d
end
local function wakeup_all(self, ret, err)
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
local result_data = self.result_data
local co = tremove(waitqueue, 1)
tremove(funcqueue, 1)
while co do
result_data[co] = err
core.wakeup(co, ret)
co = tremove(waitqueue, 1)
tremove(funcqueue, 1)
end
end
local function doclose(self)
if self.status == CLOSE then
return
end
assert(self.sock)
socket.close(self.sock)
self.sock = nil
self.status = CLOSE;
local co = self.responseco
if co then
self.responseco = nil
core.wakeup(co)
end
end
--this function will be run the indepedent coroutine
local function dispatch_response(self)
return function ()
local pcall = core.pcall
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
local result_data = self.result_data
while self.sock do
local co = tremove(waitqueue, 1)
local func = tremove(funcqueue, 1)
if func and co then
local ok, status, data = pcall(func, self)
if ok then
result_data[co] = data
core.wakeup(co, status)
else
result_data[co] = status
core.wakeup(co, false)
doclose(self)
break
end
else
local co = core.running()
self.responseco = co
core.wait(co)
end
end
self.dispatchco = false
wakeup_all(self, false, "disconnected")
end
end
local function waitfor_response(self, response)
local co = core.running()
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
waitqueue[#waitqueue + 1] = co
funcqueue[#funcqueue + 1] = response
if self.responseco then --the first request
local co = self.responseco
self.responseco = nil
core.wakeup(co)
end
local status = core.wait(co)
local result_data = self.result_data
local data = result_data[co]
result_data[co] = nil
return status, data
end
local function waitfor_connect(self)
local co = core.running()
local connectqueue = self.connectqueue
connectqueue[#connectqueue + 1] = co
local status = core.wait(co)
local result_data = self.result_data
local data = result_data[co]
result_data[co] = nil
return status, data
end
local function wakeup_conn(self, success, err)
local result_data = self.result_data
local connectqueue = self.connectqueue
for k, v in pairs(connectqueue) do
result_data[v] = err
core.wakeup(v, success)
connectqueue[k] = nil
end
end
local function tryconnect(self)
local status = self.status
if status == CONNECTED then
return true
end
if status == FINAL then
return false, "already closed"
end
if status == CLOSE then
local err, sock, res
self.status = CONNECTING;
sock = socket.connect(self.addr)
if sock then
self.sock = sock
--wait for responseco exit
while self.dispatchco do
core.sleep(0)
end
local auth = self.auth
self.dispatchco = core.fork(dispatch_response(self))
if auth then
local ok, msg
self.authco = core.running()
ok, res, msg = core.pcall(auth, self)
self.authco = nil
if not ok then
res = false
err = res
doclose(self)
elseif not res then
res = false
err = msg
doclose(self)
end
else
res = true
end
if res then
self.status = CONNECTED;
assert(#self.funcqueue == 0)
assert(#self.waitqueue == 0)
end
else
res = false
self.status = CLOSE
err = "socketdispatch connect fail"
end
wakeup_conn(self, res, err)
return res, err
elseif status == CONNECTING then
if self.authco == core.running() then
return true
end
return waitfor_connect(self)
else
core.error("[socketdispatch] incorrect call at status:" .. self.status)
end
end
function dispatch:connect()
return tryconnect(self)
end
function dispatch:close()
if self.status == FINAL then
return
end
doclose(self)
self.status = FINAL
return
end
-- the respose function will be called in the `dispatchco` coroutine
function dispatch:request(cmd, response)
local ok, err = tryconnect(self)
if not ok then
return ok, err
end
local ok = socket.write(self.sock, cmd)
if not ok then
doclose(self)
return nil
end
if not response then
return
end
return waitfor_response(self, response)
end
local function read_write_wrapper(func)
return function (self, p)
return func(self.sock, p)
end
end
dispatch.read = read_write_wrapper(socket.read)
dispatch.write = read_write_wrapper(socket.write)
dispatch.readline = read_write_wrapper(socket.readline)
return dispatch
|
fix socketdispatch auth race
|
fix socketdispatch auth race
|
Lua
|
mit
|
findstr/silly
|
c182b94bcab360f2e10d06de30e36223188cfe8e
|
src_trunk/resources/vehicle-system/c_vehicle_rightclick.lua
|
src_trunk/resources/vehicle-system/c_vehicle_rightclick.lua
|
wRightClick = nil
bInventory = nil
bCloseMenu = nil
ax, ay = nil
localPlayer = getLocalPlayer()
vehicle = nil
function requestInventory(button)
if button=="left" and not getElementData(localPlayer, "exclusiveGUI") then
if isVehicleLocked(vehicle) and vehicle ~= getPedOccupiedVehicle(localPlayer) then
triggerServerEvent("onVehicleRemoteAlarm", vehicle)
outputChatBox("This vehicle is locked.", 255, 0, 0)
else
triggerServerEvent( "openFreakinInventory", localPlayer, vehicle, ax, ay )
end
hideVehicleMenu()
end
end
function clickVehicle(button, state, absX, absY, wx, wy, wz, element)
if (element) and (getElementType(element)=="vehicle") and (button=="right") and (state=="down") and not (wInventory) then
local x, y, z = getElementPosition(localPlayer)
if (getDistanceBetweenPoints3D(x, y, z, wx, wy, wz)<=3) then
if (wRightClick) then
hideVehicleMenu()
end
showCursor(true)
ax = absX
ay = absY
vehicle = element
showVehicleMenu()
end
end
end
addEventHandler("onClientClick", getRootElement(), clickVehicle, true)
function showVehicleMenu()
wRightClick = guiCreateWindow(ax, ay, 150, 200, getVehicleName(vehicle), false)
lPlate = guiCreateLabel(0.05, 0.13, 0.87, 0.1, "Plate: " .. getVehiclePlateText(vehicle), true, wRightClick)
guiSetFont(lPlate, "default-bold-small")
lPlate = guiCreateLabel(0.05, 0.23, 0.87, 0.1, "Impounded: " .. (getElementData(vehicle, "Impounded") > 0 and "Yes" or "No"), true, wRightClick)
guiSetFont(lPlate, "default-bold-small")
bInventory = guiCreateButton(0.05, 0.33, 0.87, 0.1, "Inventory", true, wRightClick)
addEventHandler("onClientGUIClick", bInventory, requestInventory, false)
local y = 0.47
if getPedOccupiedVehicle(localPlayer) == vehicle or exports.global:hasItem(localPlayer, 3, getElementData(vehicle, "dbid")) or (getElementData(localPlayer, "faction") > 0 and getElementData(localPlayer, "faction") == getElementData(vehicle, "faction")) then
bLockUnlock = guiCreateButton(0.05, y, 0.87, 0.1, "Lock/Unlock", true, wRightClick)
addEventHandler("onClientGUIClick", bLockUnlock, lockUnlock, false)
y = y + 0.14
end
local vx,vy,vz = getElementVelocity(vehicle)
if vx < 0.05 and vy < 0.05 and vz < 0.05 and not getPedOccupiedVehicle(localPlayer) and not isVehicleLocked(vehicle) then -- completely stopped
if exports.global:hasItem(localPlayer, 57) then -- FUEL CAN
bFill = guiCreateButton(0.05, y, 0.87, 0.1, "Fill tank", true, wRightClick)
addEventHandler("onClientGUIClick", bFill, fillFuelTank, false)
y = y + 0.14
end
if getElementData(localPlayer, "job") == 5 then -- Mechanic
bFix = guiCreateButton(0.05, y, 0.87, 0.1, "Fix/Upgrade", true, wRightClick)
addEventHandler("onClientGUIClick", bFix, openMechanicWindow, false)
y = y + 0.14
end
end
if (getElementModel(vehicle)==497) then -- HELICOPTER
local players = getElementData(vehicle, "players")
local found = false
if (players) then
for key, value in ipairs(players) do
if (value==localPlayer) then
found = true
end
end
end
if not (found) then
bSit = guiCreateButton(0.05, y, 0.87, 0.1, "Sit", true, wRightClick)
addEventHandler("onClientGUIClick", bSit, sitInHelicopter, false)
else
bSit = guiCreateButton(0.05, y, 0.87, 0.1, "Stand up", true, wRightClick)
addEventHandler("onClientGUIClick", bSit, unsitInHelicopter, false)
end
y = y + 0.14
end
bCloseMenu = guiCreateButton(0.05, y, 0.87, 0.1, "Close Menu", true, wRightClick)
addEventHandler("onClientGUIClick", bCloseMenu, hideVehicleMenu, false)
end
function lockUnlock(button, state)
if (button=="left") then
if getPedOccupiedVehicle(localPlayer) == vehicle then
triggerServerEvent("lockUnlockInsideVehicle", localPlayer, vehicle)
else
triggerServerEvent("lockUnlockOutsideVehicle", localPlayer, vehicle)
end
hideVehicleMenu()
end
end
function fillFuelTank(button, state)
if (button=="left") then
local _,_, value = exports.global:hasItem(localPlayer, 57)
triggerServerEvent("fillFuelTankVehicle", localPlayer, vehicle, value)
hideVehicleMenu()
end
end
function openMechanicWindow(button, state)
if (button=="left") then
triggerEvent("openMechanicFixWindow", localPlayer, vehicle)
hideVehicleMenu()
end
end
function sitInHelicopter(button, state)
if (button=="left") then
triggerServerEvent("sitInHelicopter", localPlayer, vehicle)
hideVehicleMenu()
end
end
function unsitInHelicopter(button, state)
if (button=="left") then
triggerServerEvent("unsitInHelicopter", localPlayer, vehicle)
hideVehicleMenu()
end
end
function hideVehicleMenu()
if (isElement(bCloseMenu)) then
destroyElement(bCloseMenu)
end
bCloseMenu = nil
if (isElement(wRightClick)) then
destroyElement(wRightClick)
end
wRightClick = nil
ax = nil
ay = nil
vehicle = nil
showCursor(false)
triggerEvent("cursorHide", getLocalPlayer())
end
|
wRightClick = nil
bInventory = nil
bCloseMenu = nil
ax, ay = nil
localPlayer = getLocalPlayer()
vehicle = nil
function requestInventory(button)
if button=="left" and not getElementData(localPlayer, "exclusiveGUI") then
if isVehicleLocked(vehicle) and vehicle ~= getPedOccupiedVehicle(localPlayer) then
triggerServerEvent("onVehicleRemoteAlarm", vehicle)
outputChatBox("This vehicle is locked.", 255, 0, 0)
else
triggerServerEvent( "openFreakinInventory", localPlayer, vehicle, ax, ay )
end
hideVehicleMenu()
end
end
function clickVehicle(button, state, absX, absY, wx, wy, wz, element)
if (element) and (getElementType(element)=="vehicle") and (button=="right") and (state=="down") and not (wInventory) then
local x, y, z = getElementPosition(localPlayer)
if (getDistanceBetweenPoints3D(x, y, z, wx, wy, wz)<=3) then
if (wRightClick) then
hideVehicleMenu()
end
showCursor(true)
ax = absX
ay = absY
vehicle = element
showVehicleMenu()
end
end
end
addEventHandler("onClientClick", getRootElement(), clickVehicle, true)
function showVehicleMenu()
wRightClick = guiCreateWindow(ax, ay, 150, 200, getVehicleName(vehicle), false)
lPlate = guiCreateLabel(0.05, 0.13, 0.87, 0.1, "Plate: " .. getVehiclePlateText(vehicle), true, wRightClick)
guiSetFont(lPlate, "default-bold-small")
lPlate = guiCreateLabel(0.05, 0.23, 0.87, 0.1, "Impounded: " .. (type(getElementData(vehicle, "Impounded")) == "number" and getElementData(vehicle, "Impounded") > 0 and "Yes" or "No"), true, wRightClick)
guiSetFont(lPlate, "default-bold-small")
bInventory = guiCreateButton(0.05, 0.33, 0.87, 0.1, "Inventory", true, wRightClick)
addEventHandler("onClientGUIClick", bInventory, requestInventory, false)
local y = 0.47
if getPedOccupiedVehicle(localPlayer) == vehicle or exports.global:hasItem(localPlayer, 3, getElementData(vehicle, "dbid")) or (getElementData(localPlayer, "faction") > 0 and getElementData(localPlayer, "faction") == getElementData(vehicle, "faction")) then
bLockUnlock = guiCreateButton(0.05, y, 0.87, 0.1, "Lock/Unlock", true, wRightClick)
addEventHandler("onClientGUIClick", bLockUnlock, lockUnlock, false)
y = y + 0.14
end
local vx,vy,vz = getElementVelocity(vehicle)
if vx < 0.05 and vy < 0.05 and vz < 0.05 and not getPedOccupiedVehicle(localPlayer) and not isVehicleLocked(vehicle) then -- completely stopped
if exports.global:hasItem(localPlayer, 57) then -- FUEL CAN
bFill = guiCreateButton(0.05, y, 0.87, 0.1, "Fill tank", true, wRightClick)
addEventHandler("onClientGUIClick", bFill, fillFuelTank, false)
y = y + 0.14
end
if getElementData(localPlayer, "job") == 5 then -- Mechanic
bFix = guiCreateButton(0.05, y, 0.87, 0.1, "Fix/Upgrade", true, wRightClick)
addEventHandler("onClientGUIClick", bFix, openMechanicWindow, false)
y = y + 0.14
end
end
if (getElementModel(vehicle)==497) then -- HELICOPTER
local players = getElementData(vehicle, "players")
local found = false
if (players) then
for key, value in ipairs(players) do
if (value==localPlayer) then
found = true
end
end
end
if not (found) then
bSit = guiCreateButton(0.05, y, 0.87, 0.1, "Sit", true, wRightClick)
addEventHandler("onClientGUIClick", bSit, sitInHelicopter, false)
else
bSit = guiCreateButton(0.05, y, 0.87, 0.1, "Stand up", true, wRightClick)
addEventHandler("onClientGUIClick", bSit, unsitInHelicopter, false)
end
y = y + 0.14
end
bCloseMenu = guiCreateButton(0.05, y, 0.87, 0.1, "Close Menu", true, wRightClick)
addEventHandler("onClientGUIClick", bCloseMenu, hideVehicleMenu, false)
end
function lockUnlock(button, state)
if (button=="left") then
if getPedOccupiedVehicle(localPlayer) == vehicle then
triggerServerEvent("lockUnlockInsideVehicle", localPlayer, vehicle)
else
triggerServerEvent("lockUnlockOutsideVehicle", localPlayer, vehicle)
end
hideVehicleMenu()
end
end
function fillFuelTank(button, state)
if (button=="left") then
local _,_, value = exports.global:hasItem(localPlayer, 57)
triggerServerEvent("fillFuelTankVehicle", localPlayer, vehicle, value)
hideVehicleMenu()
end
end
function openMechanicWindow(button, state)
if (button=="left") then
triggerEvent("openMechanicFixWindow", localPlayer, vehicle)
hideVehicleMenu()
end
end
function sitInHelicopter(button, state)
if (button=="left") then
triggerServerEvent("sitInHelicopter", localPlayer, vehicle)
hideVehicleMenu()
end
end
function unsitInHelicopter(button, state)
if (button=="left") then
triggerServerEvent("unsitInHelicopter", localPlayer, vehicle)
hideVehicleMenu()
end
end
function hideVehicleMenu()
if (isElement(bCloseMenu)) then
destroyElement(bCloseMenu)
end
bCloseMenu = nil
if (isElement(wRightClick)) then
destroyElement(wRightClick)
end
wRightClick = nil
ax = nil
ay = nil
vehicle = nil
showCursor(false)
triggerEvent("cursorHide", getLocalPlayer())
end
|
fix for vehicle rightclick breaking with Impound again
|
fix for vehicle rightclick breaking with Impound again
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1559 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
85cba95646165e201ecb15a698b2dc6a3a12760a
|
contrib/package/ffluci-splash/src/luci-splash.lua
|
contrib/package/ffluci-splash/src/luci-splash.lua
|
#!/usr/bin/lua
package.path = "/usr/lib/lua/?.lua;/usr/lib/lua/?/init.lua;" .. package.path
package.cpath = "/usr/lib/lua/?.so;" .. package.cpath
require("ffluci.http")
require("ffluci.sys")
require("ffluci.model.uci")
-- Init state session
uci = ffluci.model.uci.StateSession()
function main(argv)
local cmd = argv[1]
local arg = argv[2]
if not cmd then
print("Usage: " .. argv[0] .. " <status|add|remove|sync> [MAC]")
os.exit(1)
elseif cmd == "status" then
if not arg then
os.exit(1)
end
if iswhitelisted(arg) then
print("whitelisted")
os.exit(0)
end
if haslease(arg) then
print("lease")
os.exit(0)
end
print("unknown")
os.exit(0)
elseif cmd == "add" then
if not arg then
os.exit(1)
end
if not haslease(arg) then
add_lease(arg)
else
print("already leased!")
os.exit(2)
end
os.exit(0)
elseif cmd == "remove" then
if not cmd[2] then
os.exit(1)
end
remove_lease(arg)
os.exit(0)
elseif cmd == "sync" then
sync()
os.exit(0)
end
end
-- Add a lease to state and invoke add_rule
function add_lease(mac)
local key = uci:add("luci_splash", "lease")
uci:set("luci_splash", key, "mac", mac)
uci:set("luci_splash", key, "start", os.time())
add_rule(mac)
end
-- Remove a lease from state and invoke remove_rule
function remove_lease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v.mac:lower() == mac then
remove_rule(mac)
uci:del("luci_splash", k)
end
end
end
-- Add an iptables rule
function add_rule(mac)
return os.execute("iptables -t nat -I luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Remove an iptables rule
function remove_rule(mac)
return os.execute("iptables -t nat -D luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Check whether a MAC-Address is listed in the lease state list
function haslease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "lease" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Check whether a MAC-Address is whitelisted
function iswhitelisted(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "whitelist" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Returns a list of MAC-Addresses for which a rule is existing
function listrules()
local cmd = "iptables -t nat -L luci_splash_leases | grep RETURN |"
cmd = cmd .. "egrep -io [0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+"
return ffluci.util.split(ffluci.sys.exec(cmd))
end
-- Synchronise leases, remove abandoned rules
function sync()
local written = {}
local time = os.time()
-- Current leases in state files
local leases = uci:show("luci_splash").luci_splash
-- Convert leasetime to seconds
local leasetime = tonumber(uci:get("luci_splash", "general", "leasetime")) * 3600
-- Clean state file
uci:revert("luci_splash")
-- For all leases
for k, v in pairs(uci:show("luci_splash")) do
if v[".type"] == "lease" then
if os.difftime(time, tonumber(v.start)) > leasetime then
-- Remove expired
remove_rule(v.mac)
else
-- Rewrite state
local n = uci:add("luci_splash", "lease")
uci:set("luci_splash", n, "mac", v.mac)
uci:set("luci_splash", n, "start", v.start)
written[v.mac:lower()] = 1
end
end
end
-- Delete rules without state
for i, r in ipairs(listrules()) do
if #r > 0 and not written[r:lower()] then
remove_rule(r)
end
end
end
main(arg)
|
#!/usr/bin/lua
package.path = "/usr/lib/lua/?.lua;/usr/lib/lua/?/init.lua;" .. package.path
package.cpath = "/usr/lib/lua/?.so;" .. package.cpath
require("ffluci.http")
require("ffluci.sys")
require("ffluci.model.uci")
-- Init state session
uci = ffluci.model.uci.StateSession()
function main(argv)
local cmd = argv[1]
local arg = argv[2]
if cmd == "status" then
if not arg then
os.exit(1)
end
if iswhitelisted(arg) then
print("whitelisted")
os.exit(0)
end
if haslease(arg) then
print("lease")
os.exit(0)
end
print("unknown")
os.exit(0)
elseif cmd == "add" then
if not arg then
os.exit(1)
end
if not haslease(arg) then
add_lease(arg)
else
print("already leased!")
os.exit(2)
end
os.exit(0)
elseif cmd == "remove" then
if not arg then
os.exit(1)
end
remove_lease(arg)
os.exit(0)
elseif cmd == "sync" then
sync()
os.exit(0)
else
print("Usage: " .. argv[0] .. " <status|add|remove|sync> [MAC]")
os.exit(1)
end
end
-- Add a lease to state and invoke add_rule
function add_lease(mac)
local key = uci:add("luci_splash", "lease")
uci:set("luci_splash", key, "mac", mac)
uci:set("luci_splash", key, "start", os.time())
add_rule(mac)
end
-- Remove a lease from state and invoke remove_rule
function remove_lease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v.mac:lower() == mac then
remove_rule(mac)
uci:del("luci_splash", k)
end
end
end
-- Add an iptables rule
function add_rule(mac)
return os.execute("iptables -t nat -I luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Remove an iptables rule
function remove_rule(mac)
return os.execute("iptables -t nat -D luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Check whether a MAC-Address is listed in the lease state list
function haslease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "lease" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Check whether a MAC-Address is whitelisted
function iswhitelisted(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "whitelist" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Returns a list of MAC-Addresses for which a rule is existing
function listrules()
local cmd = "iptables -t nat -L luci_splash_leases | grep RETURN |"
cmd = cmd .. "egrep -io [0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+"
return ffluci.util.split(ffluci.sys.exec(cmd))
end
-- Synchronise leases, remove abandoned rules
function sync()
local written = {}
local time = os.time()
-- Current leases in state files
local leases = uci:show("luci_splash").luci_splash
-- Convert leasetime to seconds
local leasetime = tonumber(uci:get("luci_splash", "general", "leasetime")) * 3600
-- Clean state file
uci:revert("luci_splash")
-- For all leases
for k, v in pairs(uci:show("luci_splash")) do
if v[".type"] == "lease" then
if os.difftime(time, tonumber(v.start)) > leasetime then
-- Remove expired
remove_rule(v.mac)
else
-- Rewrite state
local n = uci:add("luci_splash", "lease")
uci:set("luci_splash", n, "mac", v.mac)
uci:set("luci_splash", n, "start", v.start)
written[v.mac:lower()] = 1
end
end
end
-- Delete rules without state
for i, r in ipairs(listrules()) do
if #r > 0 and not written[r:lower()] then
remove_rule(r)
end
end
end
main(arg)
|
ffluci-splash: Minor fixes
|
ffluci-splash: Minor fixes
|
Lua
|
apache-2.0
|
tobiaswaldvogel/luci,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,joaofvieira/luci,openwrt/luci,tcatm/luci,lcf258/openwrtcn,harveyhu2012/luci,jorgifumi/luci,bright-things/ionic-luci,kuoruan/luci,rogerpueyo/luci,male-puppies/luci,lcf258/openwrtcn,mumuqz/luci,palmettos/test,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,mumuqz/luci,artynet/luci,shangjiyu/luci-with-extra,zhaoxx063/luci,jlopenwrtluci/luci,jorgifumi/luci,opentechinstitute/luci,openwrt/luci,deepak78/new-luci,thesabbir/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,taiha/luci,hnyman/luci,shangjiyu/luci-with-extra,slayerrensky/luci,bright-things/ionic-luci,teslamint/luci,oyido/luci,jchuang1977/luci-1,taiha/luci,openwrt/luci,thesabbir/luci,jlopenwrtluci/luci,kuoruan/lede-luci,NeoRaider/luci,LuttyYang/luci,marcel-sch/luci,openwrt/luci,Kyklas/luci-proto-hso,cshore/luci,slayerrensky/luci,obsy/luci,nmav/luci,Wedmer/luci,obsy/luci,MinFu/luci,forward619/luci,mumuqz/luci,kuoruan/lede-luci,NeoRaider/luci,oyido/luci,MinFu/luci,RuiChen1113/luci,palmettos/cnLuCI,tcatm/luci,RuiChen1113/luci,palmettos/cnLuCI,RuiChen1113/luci,remakeelectric/luci,Wedmer/luci,nmav/luci,tcatm/luci,openwrt-es/openwrt-luci,deepak78/new-luci,dwmw2/luci,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,cappiewu/luci,MinFu/luci,NeoRaider/luci,nmav/luci,fkooman/luci,thesabbir/luci,jorgifumi/luci,openwrt/luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,mumuqz/luci,harveyhu2012/luci,NeoRaider/luci,RuiChen1113/luci,oyido/luci,schidler/ionic-luci,tcatm/luci,Sakura-Winkey/LuCI,jorgifumi/luci,keyidadi/luci,zhaoxx063/luci,tobiaswaldvogel/luci,jorgifumi/luci,ff94315/luci-1,urueedi/luci,zhaoxx063/luci,maxrio/luci981213,remakeelectric/luci,thesabbir/luci,slayerrensky/luci,palmettos/cnLuCI,Noltari/luci,florian-shellfire/luci,jlopenwrtluci/luci,daofeng2015/luci,jorgifumi/luci,NeoRaider/luci,dwmw2/luci,male-puppies/luci,wongsyrone/luci-1,bittorf/luci,hnyman/luci,forward619/luci,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,thess/OpenWrt-luci,deepak78/new-luci,ollie27/openwrt_luci,RedSnake64/openwrt-luci-packages,oyido/luci,ollie27/openwrt_luci,taiha/luci,RuiChen1113/luci,Kyklas/luci-proto-hso,rogerpueyo/luci,openwrt-es/openwrt-luci,opentechinstitute/luci,aa65535/luci,jchuang1977/luci-1,keyidadi/luci,sujeet14108/luci,RedSnake64/openwrt-luci-packages,cshore-firmware/openwrt-luci,remakeelectric/luci,taiha/luci,david-xiao/luci,fkooman/luci,LuttyYang/luci,artynet/luci,thesabbir/luci,sujeet14108/luci,hnyman/luci,thesabbir/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,lcf258/openwrtcn,maxrio/luci981213,palmettos/test,oneru/luci,bittorf/luci,dismantl/luci-0.12,dwmw2/luci,nwf/openwrt-luci,wongsyrone/luci-1,opentechinstitute/luci,fkooman/luci,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,teslamint/luci,ollie27/openwrt_luci,Sakura-Winkey/LuCI,deepak78/new-luci,chris5560/openwrt-luci,oyido/luci,sujeet14108/luci,shangjiyu/luci-with-extra,florian-shellfire/luci,teslamint/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,jlopenwrtluci/luci,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,keyidadi/luci,kuoruan/luci,palmettos/cnLuCI,fkooman/luci,ff94315/luci-1,thesabbir/luci,bright-things/ionic-luci,kuoruan/lede-luci,artynet/luci,ff94315/luci-1,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,ff94315/luci-1,Sakura-Winkey/LuCI,Noltari/luci,taiha/luci,dwmw2/luci,palmettos/cnLuCI,nmav/luci,ff94315/luci-1,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,RedSnake64/openwrt-luci-packages,Kyklas/luci-proto-hso,nwf/openwrt-luci,forward619/luci,joaofvieira/luci,bright-things/ionic-luci,db260179/openwrt-bpi-r1-luci,tobiaswaldvogel/luci,aircross/OpenWrt-Firefly-LuCI,rogerpueyo/luci,bittorf/luci,bittorf/luci,sujeet14108/luci,kuoruan/luci,artynet/luci,LuttyYang/luci,deepak78/new-luci,mumuqz/luci,david-xiao/luci,thess/OpenWrt-luci,fkooman/luci,cshore/luci,harveyhu2012/luci,hnyman/luci,daofeng2015/luci,daofeng2015/luci,cshore/luci,LuttyYang/luci,obsy/luci,chris5560/openwrt-luci,dismantl/luci-0.12,rogerpueyo/luci,urueedi/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,obsy/luci,florian-shellfire/luci,lbthomsen/openwrt-luci,opentechinstitute/luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,keyidadi/luci,schidler/ionic-luci,db260179/openwrt-bpi-r1-luci,teslamint/luci,slayerrensky/luci,schidler/ionic-luci,joaofvieira/luci,marcel-sch/luci,remakeelectric/luci,wongsyrone/luci-1,kuoruan/luci,Hostle/openwrt-luci-multi-user,kuoruan/lede-luci,LuttyYang/luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,lcf258/openwrtcn,fkooman/luci,tcatm/luci,jchuang1977/luci-1,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,fkooman/luci,aa65535/luci,slayerrensky/luci,maxrio/luci981213,teslamint/luci,joaofvieira/luci,oneru/luci,oneru/luci,openwrt-es/openwrt-luci,joaofvieira/luci,cshore/luci,hnyman/luci,LuttyYang/luci,nwf/openwrt-luci,schidler/ionic-luci,openwrt-es/openwrt-luci,Noltari/luci,Hostle/luci,aa65535/luci,male-puppies/luci,deepak78/new-luci,cshore/luci,urueedi/luci,RuiChen1113/luci,cshore/luci,lbthomsen/openwrt-luci,MinFu/luci,MinFu/luci,hnyman/luci,remakeelectric/luci,palmettos/cnLuCI,thess/OpenWrt-luci,oyido/luci,cappiewu/luci,david-xiao/luci,oneru/luci,Hostle/luci,lbthomsen/openwrt-luci,palmettos/cnLuCI,male-puppies/luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,marcel-sch/luci,joaofvieira/luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,chris5560/openwrt-luci,dwmw2/luci,harveyhu2012/luci,Noltari/luci,db260179/openwrt-bpi-r1-luci,cappiewu/luci,ReclaimYourPrivacy/cloak-luci,artynet/luci,Wedmer/luci,nmav/luci,taiha/luci,cappiewu/luci,daofeng2015/luci,Hostle/openwrt-luci-multi-user,dwmw2/luci,marcel-sch/luci,urueedi/luci,schidler/ionic-luci,bittorf/luci,rogerpueyo/luci,Noltari/luci,aa65535/luci,florian-shellfire/luci,nmav/luci,hnyman/luci,981213/luci-1,Hostle/luci,forward619/luci,forward619/luci,slayerrensky/luci,remakeelectric/luci,tobiaswaldvogel/luci,rogerpueyo/luci,kuoruan/lede-luci,ReclaimYourPrivacy/cloak-luci,forward619/luci,nwf/openwrt-luci,sujeet14108/luci,cappiewu/luci,aa65535/luci,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,Wedmer/luci,LazyZhu/openwrt-luci-trunk-mod,Hostle/luci,daofeng2015/luci,joaofvieira/luci,NeoRaider/luci,chris5560/openwrt-luci,bright-things/ionic-luci,tcatm/luci,Noltari/luci,ReclaimYourPrivacy/cloak-luci,zhaoxx063/luci,kuoruan/luci,cshore/luci,981213/luci-1,palmettos/test,openwrt-es/openwrt-luci,opentechinstitute/luci,schidler/ionic-luci,kuoruan/lede-luci,jchuang1977/luci-1,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,lbthomsen/openwrt-luci,zhaoxx063/luci,fkooman/luci,marcel-sch/luci,NeoRaider/luci,MinFu/luci,palmettos/test,mumuqz/luci,tobiaswaldvogel/luci,oneru/luci,Noltari/luci,dismantl/luci-0.12,palmettos/test,daofeng2015/luci,urueedi/luci,cshore-firmware/openwrt-luci,Hostle/luci,opentechinstitute/luci,deepak78/new-luci,dismantl/luci-0.12,Hostle/luci,aa65535/luci,dwmw2/luci,teslamint/luci,Noltari/luci,palmettos/test,cappiewu/luci,cshore/luci,ff94315/luci-1,oneru/luci,hnyman/luci,lcf258/openwrtcn,jorgifumi/luci,bittorf/luci,oyido/luci,lcf258/openwrtcn,jchuang1977/luci-1,male-puppies/luci,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,RuiChen1113/luci,cshore-firmware/openwrt-luci,Wedmer/luci,david-xiao/luci,Hostle/luci,chris5560/openwrt-luci,bright-things/ionic-luci,florian-shellfire/luci,sujeet14108/luci,david-xiao/luci,kuoruan/luci,thesabbir/luci,artynet/luci,thess/OpenWrt-luci,kuoruan/luci,maxrio/luci981213,opentechinstitute/luci,981213/luci-1,chris5560/openwrt-luci,florian-shellfire/luci,lcf258/openwrtcn,jchuang1977/luci-1,openwrt/luci,palmettos/test,taiha/luci,oneru/luci,MinFu/luci,artynet/luci,lbthomsen/openwrt-luci,mumuqz/luci,keyidadi/luci,deepak78/new-luci,teslamint/luci,mumuqz/luci,openwrt/luci,dismantl/luci-0.12,nwf/openwrt-luci,david-xiao/luci,tcatm/luci,obsy/luci,keyidadi/luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,aa65535/luci,thess/OpenWrt-luci,nwf/openwrt-luci,981213/luci-1,slayerrensky/luci,bright-things/ionic-luci,obsy/luci,cshore-firmware/openwrt-luci,cappiewu/luci,nwf/openwrt-luci,nmav/luci,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,kuoruan/lede-luci,schidler/ionic-luci,palmettos/test,shangjiyu/luci-with-extra,thess/OpenWrt-luci,male-puppies/luci,florian-shellfire/luci,jchuang1977/luci-1,zhaoxx063/luci,shangjiyu/luci-with-extra,david-xiao/luci,lcf258/openwrtcn,wongsyrone/luci-1,dismantl/luci-0.12,marcel-sch/luci,urueedi/luci,rogerpueyo/luci,oyido/luci,981213/luci-1,kuoruan/luci,nmav/luci,schidler/ionic-luci,tobiaswaldvogel/luci,lcf258/openwrtcn,Noltari/luci,zhaoxx063/luci,joaofvieira/luci,remakeelectric/luci,bittorf/luci,ReclaimYourPrivacy/cloak-luci,palmettos/cnLuCI,981213/luci-1,Wedmer/luci,bright-things/ionic-luci,slayerrensky/luci,Kyklas/luci-proto-hso,dwmw2/luci,remakeelectric/luci,Sakura-Winkey/LuCI,dismantl/luci-0.12,harveyhu2012/luci,LuttyYang/luci,artynet/luci,ollie27/openwrt_luci,artynet/luci,wongsyrone/luci-1,cshore-firmware/openwrt-luci,Kyklas/luci-proto-hso,cshore-firmware/openwrt-luci,Wedmer/luci,marcel-sch/luci,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,sujeet14108/luci,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,Kyklas/luci-proto-hso,Wedmer/luci,ff94315/luci-1,zhaoxx063/luci,oneru/luci,LuttyYang/luci,Hostle/openwrt-luci-multi-user,NeoRaider/luci,obsy/luci,Sakura-Winkey/LuCI,LazyZhu/openwrt-luci-trunk-mod,ollie27/openwrt_luci,MinFu/luci,tcatm/luci,thess/OpenWrt-luci,cappiewu/luci,Kyklas/luci-proto-hso,jlopenwrtluci/luci,wongsyrone/luci-1,marcel-sch/luci,aircross/OpenWrt-Firefly-LuCI,ollie27/openwrt_luci,jchuang1977/luci-1,male-puppies/luci,obsy/luci,nmav/luci,chris5560/openwrt-luci,kuoruan/lede-luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,Hostle/luci,urueedi/luci,nwf/openwrt-luci,keyidadi/luci,forward619/luci,openwrt-es/openwrt-luci,jlopenwrtluci/luci,ff94315/luci-1,harveyhu2012/luci,taiha/luci,forward619/luci,RedSnake64/openwrt-luci-packages,daofeng2015/luci,openwrt/luci,aa65535/luci,db260179/openwrt-bpi-r1-luci,RedSnake64/openwrt-luci-packages,981213/luci-1,keyidadi/luci,david-xiao/luci,lbthomsen/openwrt-luci,maxrio/luci981213,florian-shellfire/luci
|
ae5216e8b4527a1e3d4962fad7b933f420793666
|
lua/weapons/remotecontroller.lua
|
lua/weapons/remotecontroller.lua
|
AddCSLuaFile()
SWEP.Author = "Divran" -- Originally by ShaRose, rewritten by Divran at 2011-04-03
SWEP.Contact = ""
SWEP.Purpose = "Remote control for Pod Controllers in wire."
SWEP.Instructions = "Left Click on Pod Controller to link up, and use to start controlling."
SWEP.Category = "Wiremod"
SWEP.PrintName = "Remote Control"
SWEP.Slot = 0
SWEP.SlotPos = 4
SWEP.DrawAmmo = false
SWEP.Weight = 1
SWEP.Spawnable = true
SWEP.AdminOnly = false
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.viewModel = "models/weapons/v_pistol.mdl"
SWEP.worldModel = "models/weapons/w_pistol.mdl"
if CLIENT then return end
function SWEP:PrimaryAttack()
local trace = self:GetOwner():GetEyeTrace()
if IsValid(trace.Entity) and trace.Entity:GetClass() == "gmod_wire_pod" and gamemode.Call("PlayerUse", self:GetOwner(), trace.Entity) then
self.Linked = trace.Entity
self:GetOwner():ChatPrint("Remote Controller linked.")
end
end
function SWEP:Holster()
if (self.Linked) then
self:Off()
end
return true
end
function SWEP:OnDrop()
if (self.Linked) then
self:Off()
self.Linked = nil
end
end
function SWEP:On()
self.Active = true
self.OldMoveType = self:GetOwner():GetMoveType()
self:GetOwner():SetMoveType(MOVETYPE_NONE)
self:GetOwner():DrawViewModel(false)
if (self.Linked and self.Linked:IsValid()) then
self.Linked:PlayerEntered( self:GetOwner(), self )
end
end
function SWEP:Off()
if self.Active then
self:GetOwner():SetMoveType(self.OldMoveType or MOVETYPE_WALK)
end
self.Active = nil
self.OldMoveType = nil
self:GetOwner():DrawViewModel(true)
if (self.Linked and self.Linked:IsValid()) then
self.Linked:PlayerExited( self:GetOwner() )
end
end
function SWEP:Think()
if (!self.Linked) then return end
if (self:GetOwner():KeyPressed( IN_USE )) then
if (!self.Active) then
self:On()
else
self:Off()
end
end
end
function SWEP:Deploy()
return true
end
|
AddCSLuaFile()
SWEP.Author = "Divran" -- Originally by ShaRose, rewritten by Divran at 2011-04-03
SWEP.Contact = ""
SWEP.Purpose = "Remote control for Pod Controllers in wire."
SWEP.Instructions = "Left Click on Pod Controller to link up, and use to start controlling."
SWEP.Category = "Wiremod"
SWEP.PrintName = "Remote Control"
SWEP.Slot = 0
SWEP.SlotPos = 4
SWEP.DrawAmmo = false
SWEP.Weight = 1
SWEP.Spawnable = true
SWEP.AdminOnly = false
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.viewModel = "models/weapons/v_pistol.mdl"
SWEP.worldModel = "models/weapons/w_pistol.mdl"
if CLIENT then return end
function SWEP:PrimaryAttack()
local ply = self:GetOwner()
local trace = ply:GetEyeTrace()
if IsValid(trace.Entity) and trace.Entity:GetClass() == "gmod_wire_pod" and gamemode.Call("PlayerUse", ply, trace.Entity) then
self.Linked = trace.Entity
ply:ChatPrint("Remote Controller linked.")
end
end
function SWEP:Holster()
if self.Linked then
self:Off()
end
return true
end
function SWEP:Deploy()
return true
end
function SWEP:OnDrop()
if not self.Linked then return end
self:Off()
self.Linked = nil
end
function SWEP:On()
local ply = self:GetOwner()
self.Active = true
self.OldMoveType = not ply:InVehicle() and ply:GetMoveType() or MOVETYPE_WALK
ply:SetMoveType(MOVETYPE_NONE)
ply:DrawViewModel(false)
if IsValid(self.Linked) then
self.Linked:PlayerEntered(ply, self)
end
end
function SWEP:Off()
local ply = self:GetOwner()
if self.Active then
ply:SetMoveType(self.OldMoveType or MOVETYPE_WALK)
end
self.Active = nil
self.OldMoveType = nil
ply:DrawViewModel(true)
if IsValid(self.Linked) then
self.Linked:PlayerExited(ply)
end
end
function SWEP:Think()
if not self.Linked then return end
if self:GetOwner():KeyPressed(IN_USE) then
if not self.Active then
self:On()
else
self:Off()
end
end
end
|
Updated Remote Controller (#1172)
|
Updated Remote Controller (#1172)
Fixed exploit with remote controller which allowed you to get into noclip on servers which have noclip disabled
|
Lua
|
apache-2.0
|
NezzKryptic/Wire,garrysmodlua/wire,dvdvideo1234/wire,Grocel/wire,thegrb93/wire,wiremod/wire,sammyt291/wire,bigdogmat/wire
|
05e5ba4a27bb34e60334107364c403a68cf6fba0
|
mod_carbons/mod_carbons.lua
|
mod_carbons/mod_carbons.lua
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local host_sessions = hosts[module.host].sessions;
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable";
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = origin.username .. "@" .. origin.host;
local target_session = origin;
local top_priority = false;
local user_sessions = host_sessions[origin.username];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to]
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
return tag.attr.xmlns == xmlns_carbons
and tag.name == "private" and tag or nil;
end);
module:log("debug", "Message tagged private, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (not c2s or session.priority ~= top_priority) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local host_sessions = hosts[module.host].sessions;
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable";
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_from = stanza.attr.from;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = origin.type == "c2s" and origin.username .. "@" .. origin.host or jid_bare(orig_from);
local target_session = origin;
local top_priority = false;
local user_sessions = host_sessions[origin.username];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to]
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
return tag.attr.xmlns == xmlns_carbons
and tag.name == "private" and tag or nil;
end);
module:log("debug", "Message tagged private, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (not c2s or session.priority ~= top_priority) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
|
mod_carbons: Fix handling of messages from remote hosts
|
mod_carbons: Fix handling of messages from remote hosts
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
c971ec7dc7f5693e81535ec8f78b83ede6a33857
|
mods/screwdriver/init.lua
|
mods/screwdriver/init.lua
|
local mode_text = {
{"Change rotation, Don't change axisdir."},
{"Keep choosen face in front then rotate it."},
{"Change axis dir, Reset rotation."},
{"Bring top in front then rotate it."},
}
local opposite_faces = {
[0] = 5,
[1] = 2,
[2] = 1,
[3] = 4,
[4] = 3,
[5] = 0,
}
local function screwdriver_setmode(user,itemstack)
local player_name = user:get_player_name()
local item = itemstack:to_table()
local mode = tonumber(itemstack:get_metadata())
if not mode then
minetest.chat_send_player(player_name, "Hold shift and use to change screwdriwer modes.")
mode = 0
end
mode = mode + 1
if mode == 5 then
mode = 1
end
minetest.chat_send_player(player_name, "Screwdriver mode : "..mode.." - "..mode_text[mode][1] )
itemstack:set_name("screwdriver:screwdriver"..mode)
itemstack:set_metadata(mode)
return itemstack
end
local function get_node_face(pointed_thing)
local ax, ay, az = pointed_thing.above.x, pointed_thing.above.y, pointed_thing.above.z
local ux, uy, uz = pointed_thing.under.x, pointed_thing.under.y, pointed_thing.under.z
if ay > uy then return 0 -- Top
elseif az > uz then return 1 -- Z+ side
elseif az < uz then return 2 -- Z- side
elseif ax > ux then return 3 -- X+ side
elseif ax < ux then return 4 -- X- side
elseif ay < uy then return 5 -- Bottom
else
error("pointed_thing.above and under are the same!")
end
end
local function nextrange(x, max)
x = x + 1
if x > max then
x = 0
end
return x
end
local function screwdriver_handler(itemstack, user, pointed_thing)
if pointed_thing.type ~= "node" then
return
end
local pos = pointed_thing.under
local keys = user:get_player_control()
local player_name = user:get_player_name()
local mode = tonumber(itemstack:get_metadata())
if not mode or keys["sneak"] == true then
return screwdriver_setmode(user, itemstack)
end
if minetest.is_protected(pos, user:get_player_name()) then
minetest.record_protection_violation(pos, user:get_player_name())
return
end
local node = minetest.get_node(pos)
local node_name = node.name
local ndef = minetest.registered_nodes[node.name]
if ndef.paramtype2 == "facedir" then
if ndef.drawtype == "nodebox" and ndef.node_box.type ~= "fixed" then
return
end
if node.param2 == nil then
return
end
-- Get ready to set the param2
local n = node.param2
local axisdir = math.floor(n / 4)
local rotation = n - axisdir * 4
if mode == 1 then
n = axisdir * 4 + nextrange(rotation, 3)
elseif mode == 2 then
-- If you are pointing at the axisdir face or the
-- opposite one then you can just rotate the node.
-- Otherwise change the axisdir, avoiding the facing
-- and opposite axes.
local face = get_node_face(pointed_thing)
if axisdir == face or axisdir == opposite_faces[face] then
n = axisdir * 4 + nextrange(rotation, 3)
else
axisdir = nextrange(axisdir, 5)
-- This is repeated because switching from the face
-- can move to to the opposite and vice-versa
if axisdir == face or axisdir == opposite_faces[face] then
axisdir = nextrange(axisdir, 5)
end
if axisdir == face or axisdir == opposite_faces[face] then
axisdir = nextrange(axisdir, 5)
end
n = axisdir * 4
end
elseif mode == 3 then
n = nextrange(axisdir, 5) * 4
elseif mode == 4 then
local face = get_node_face(pointed_thing)
if axisdir == face then
n = axisdir * 4 + nextrange(rotation, 3)
else
n = face * 4
end
end
--print (dump(axisdir..", "..rotation))
node.param2 = n
minetest.swap_node(pos, node)
local item_wear = tonumber(itemstack:get_wear())
item_wear = item_wear + 327
if item_wear > 65535 then
itemstack:clear()
return itemstack
end
itemstack:set_wear(item_wear)
return itemstack
end
end
minetest.register_craft({
output = "screwdriver:screwdriver",
recipe = {
{"default:steel_ingot"},
{"group:stick"}
}
})
minetest.register_tool("screwdriver:screwdriver", {
description = "Screwdriver",
inventory_image = "screwdriver.png",
on_use = function(itemstack, user, pointed_thing)
screwdriver_handler(itemstack, user, pointed_thing)
return itemstack
end,
})
for i = 1, 4 do
minetest.register_tool("screwdriver:screwdriver"..i, {
description = "Screwdriver in Mode "..i,
inventory_image = "screwdriver.png^tool_mode"..i..".png",
wield_image = "screwdriver.png",
groups = {not_in_creative_inventory=1},
on_use = function(itemstack, user, pointed_thing)
screwdriver_handler(itemstack, user, pointed_thing)
return itemstack
end,
})
end
|
local mode_text = {
{"Change rotation, Don't change axisdir."},
{"Keep choosen face in front then rotate it."},
{"Change axis dir, Reset rotation."},
{"Bring top in front then rotate it."},
}
local opposite_faces = {
[0] = 5,
[1] = 2,
[2] = 1,
[3] = 4,
[4] = 3,
[5] = 0,
}
local function screwdriver_setmode(user,itemstack)
local player_name = user:get_player_name()
local item = itemstack:to_table()
local mode = tonumber(itemstack:get_metadata())
if not mode then
minetest.chat_send_player(player_name, "Hold shift and use to change screwdriwer modes.")
mode = 0
end
mode = mode + 1
if mode == 5 then
mode = 1
end
minetest.chat_send_player(player_name, "Screwdriver mode : "..mode.." - "..mode_text[mode][1] )
itemstack:set_name("screwdriver:screwdriver"..mode)
itemstack:set_metadata(mode)
return itemstack
end
local function get_node_face(pointed_thing)
local ax, ay, az = pointed_thing.above.x, pointed_thing.above.y, pointed_thing.above.z
local ux, uy, uz = pointed_thing.under.x, pointed_thing.under.y, pointed_thing.under.z
if ay > uy then return 0 -- Top
elseif az > uz then return 1 -- Z+ side
elseif az < uz then return 2 -- Z- side
elseif ax > ux then return 3 -- X+ side
elseif ax < ux then return 4 -- X- side
elseif ay < uy then return 5 -- Bottom
else
error("pointed_thing.above and under are the same!")
end
end
local function nextrange(x, max)
x = x + 1
if x > max then
x = 0
end
return x
end
local function screwdriver_handler(itemstack, user, pointed_thing)
if pointed_thing.type ~= "node" then
return
end
local pos = pointed_thing.under
local keys = user:get_player_control()
local player_name = user:get_player_name()
local mode = tonumber(itemstack:get_metadata())
if not mode or keys["sneak"] == true then
return screwdriver_setmode(user, itemstack)
end
if minetest.is_protected(pos, user:get_player_name()) then
minetest.record_protection_violation(pos, user:get_player_name())
return
end
local node = minetest.get_node(pos)
local ndef = minetest.registered_nodes[node.name]
if ndef and ndef.paramtype2 == "facedir" then
if ndef.drawtype == "nodebox" and ndef.node_box.type ~= "fixed" then
return
end
if node.param2 == nil then
return
end
-- Get ready to set the param2
local n = node.param2
local axisdir = math.floor(n / 4)
local rotation = n - axisdir * 4
if mode == 1 then
n = axisdir * 4 + nextrange(rotation, 3)
elseif mode == 2 then
-- If you are pointing at the axisdir face or the
-- opposite one then you can just rotate the node.
-- Otherwise change the axisdir, avoiding the facing
-- and opposite axes.
local face = get_node_face(pointed_thing)
if axisdir == face or axisdir == opposite_faces[face] then
n = axisdir * 4 + nextrange(rotation, 3)
else
axisdir = nextrange(axisdir, 5)
-- This is repeated because switching from the face
-- can move to to the opposite and vice-versa
if axisdir == face or axisdir == opposite_faces[face] then
axisdir = nextrange(axisdir, 5)
end
if axisdir == face or axisdir == opposite_faces[face] then
axisdir = nextrange(axisdir, 5)
end
n = axisdir * 4
end
elseif mode == 3 then
n = nextrange(axisdir, 5) * 4
elseif mode == 4 then
local face = get_node_face(pointed_thing)
if axisdir == face then
n = axisdir * 4 + nextrange(rotation, 3)
else
n = face * 4
end
end
--print (dump(axisdir..", "..rotation))
node.param2 = n
minetest.swap_node(pos, node)
local item_wear = tonumber(itemstack:get_wear())
item_wear = item_wear + 327
if item_wear > 65535 then
itemstack:clear()
return itemstack
end
itemstack:set_wear(item_wear)
return itemstack
end
end
minetest.register_craft({
output = "screwdriver:screwdriver",
recipe = {
{"default:steel_ingot"},
{"group:stick"}
}
})
minetest.register_tool("screwdriver:screwdriver", {
description = "Screwdriver",
inventory_image = "screwdriver.png",
on_use = function(itemstack, user, pointed_thing)
screwdriver_handler(itemstack, user, pointed_thing)
return itemstack
end,
})
for i = 1, 4 do
minetest.register_tool("screwdriver:screwdriver"..i, {
description = "Screwdriver in Mode "..i,
inventory_image = "screwdriver.png^tool_mode"..i..".png",
wield_image = "screwdriver.png",
groups = {not_in_creative_inventory=1},
on_use = function(itemstack, user, pointed_thing)
screwdriver_handler(itemstack, user, pointed_thing)
return itemstack
end,
})
end
|
Fix crash when using the screwdriver on an unknown node
|
Fix crash when using the screwdriver on an unknown node
|
Lua
|
lgpl-2.1
|
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
|
b53d4079797ca34869ed6970bf74243ec9450e9f
|
mods/mff/mff_pclasses/hunter.lua
|
mods/mff/mff_pclasses/hunter.lua
|
------------------
-- Hunter class --
------------------
--
-- See https://github.com/Ombridride/minetest-minetestforfun-server/issues/114
--
pclasses.api.register_class("hunter", {
on_assigned = function(pname, inform)
if inform then
minetest.chat_send_player(pname, "You are now a hunter")
minetest.sound_play("pclasses_full_hunter", {to_player=pname, gain=1})
end
local reinforced = pclasses.api.util.does_wear_full_armor(pname, "reinforcedleather", true)
if reinforced then
sprint.increase_maxstamina(pname, 20)
else
sprint.increase_maxstamina(pname, 10)
end
minetest.log("action", "[PClasses] Player " .. pname .. " become a hunter")
end,
on_unassigned = function(pname)
sprint.set_default_maxstamina(pname)
end,
switch_params = {
color = {r = 30, g = 170, b = 00},
tile = "default_wood.png",
holo_item = "throwing:bow_minotaur_horn_improved"
}
})
pclasses.api.reserve_item("hunter", "throwing:bow_minotaur_horn")
pclasses.api.reserve_item("hunter", "throwing:bow_minotaur_horn_improved")
pclasses.api.reserve_item("hunter", "throwing:arrow_mithril")
pclasses.api.reserve_item("hunter", "throwing:arbalest_auto")
pclasses.api.reserve_item("hunter", "spears:spear_stone")
pclasses.api.reserve_item("hunter", "spears:spear_steel")
pclasses.api.reserve_item("hunter", "spears:spear_obsidian")
pclasses.api.reserve_item("hunter", "spears:spear_diamond")
pclasses.api.reserve_item("hunter", "spears:spear_mithril")
for _, i in pairs({"helmet", "chestplate", "boots", "leggings"}) do
pclasses.api.reserve_item("hunter", "3d_armor:" .. i .. "_hardenedleather")
pclasses.api.reserve_item("hunter", "3d_armor:" .. i .. "_reinforcedleather")
end
|
------------------
-- Hunter class --
------------------
--
-- See https://github.com/Ombridride/minetest-minetestforfun-server/issues/114
--
pclasses.api.register_class("hunter", {
on_assigned = function(pname, inform)
if inform then
minetest.chat_send_player(pname, "You are now a hunter")
minetest.sound_play("pclasses_full_hunter", {to_player=pname, gain=1})
end
local reinforced = pclasses.api.util.does_wear_full_armor(pname, "reinforcedleather", true)
if reinforced then
sprint.increase_maxstamina(pname, 20)
else
sprint.increase_maxstamina(pname, 10)
end
minetest.log("action", "[PClasses] Player " .. pname .. " become a hunter")
end,
on_unassigned = function(pname)
sprint.set_default_maxstamina(pname)
end,
switch_params = {
color = {r = 30, g = 170, b = 00},
tile = "default_wood.png",
holo_item = "throwing:bow_minotaur_horn_improved"
}
})
pclasses.api.reserve_item("hunter", "throwing:bow_minotaur_horn")
pclasses.api.reserve_item("hunter", "throwing:bow_minotaur_horn_loaded")
pclasses.api.reserve_item("hunter", "throwing:bow_minotaur_horn_improved")
pclasses.api.reserve_item("hunter", "throwing:bow_minotaur_horn_improved_loaded")
pclasses.api.reserve_item("hunter", "throwing:arrow_mithril")
pclasses.api.reserve_item("hunter", "throwing:arbalest_auto")
pclasses.api.reserve_item("hunter", "throwing:arbalest_auto_loaded")
pclasses.api.reserve_item("hunter", "spears:spear_stone")
pclasses.api.reserve_item("hunter", "spears:spear_steel")
pclasses.api.reserve_item("hunter", "spears:spear_obsidian")
pclasses.api.reserve_item("hunter", "spears:spear_diamond")
pclasses.api.reserve_item("hunter", "spears:spear_mithril")
for _, i in pairs({"helmet", "chestplate", "boots", "leggings"}) do
pclasses.api.reserve_item("hunter", "3d_armor:" .. i .. "_hardenedleather")
pclasses.api.reserve_item("hunter", "3d_armor:" .. i .. "_reinforcedleather")
end
|
fix no drop hunter bow_minotaur_horn/arbalest_auto when loaded, issue https://github.com/MinetestForFun/server-minetestforfun/issues/420
|
fix no drop hunter bow_minotaur_horn/arbalest_auto when loaded, issue https://github.com/MinetestForFun/server-minetestforfun/issues/420
|
Lua
|
unlicense
|
Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server
|
3761aa95483ac060dc51973727b1f059698de016
|
mods/unified_inventory/group.lua
|
mods/unified_inventory/group.lua
|
function unified_inventory.canonical_item_spec_matcher(spec)
local specname = ItemStack(spec):get_name()
if specname:sub(1, 6) == "group:" then
local group_names = specname:sub(7):split(",")
return function (itemname)
local itemdef = minetest.registered_items[itemname]
for _, group_name in ipairs(group_names) do
if (itemdef.groups[group_name] or 0) == 0 then
return false
end
end
return true
end
else
return function (itemname) return itemname == specname end
end
end
function unified_inventory.item_matches_spec(item, spec)
local itemname = ItemStack(item):get_name()
return unified_inventory.canonical_item_spec_matcher(spec)(itemname)
end
unified_inventory.registered_group_items = {
mesecon_conductor_craftable = "mesecons:wire_00000000_off",
stone = "default:cobble",
wool = "wool:white",
}
function unified_inventory.register_group_item(groupname, itemname)
unified_inventory.registered_group_items[groupname] = itemname
end
-- This is used when displaying craft recipes, where an ingredient is
-- specified by group rather than as a specific item. A single-item group
-- is represented by that item, with the single-item status signalled
-- in the "sole" field. If the group contains no items at all, the item
-- field will be nil.
--
-- Within a multiple-item group, we prefer to use an item that has the
-- same specific name as the group, and if there are more than one of
-- those items we prefer the one registered for the group by a mod.
-- Among equally-preferred items, we just pick the one with the
-- lexicographically earliest name.
--
-- The parameter to this function isn't just a single group name.
-- It may be a comma-separated list of group names. This is really a
-- "group:..." ingredient specification, minus the "group:" prefix.
local function compute_group_item(group_name_list)
local group_names = group_name_list:split(",")
local candidate_items = {}
for itemname, itemdef in pairs(minetest.registered_items) do
if (itemdef.groups.not_in_creative_inventory or 0) == 0 then
local all = true
for _, group_name in ipairs(group_names) do
if (itemdef.groups[group_name] or 0) == 0 then
all = false
end
end
if all then table.insert(candidate_items, itemname) end
end
end
local num_candidates = #candidate_items
if num_candidates == 0 then
return {sole = true}
elseif num_candidates == 1 then
return {item = candidate_items[1], sole = true}
end
local is_group = {}
local registered_rep = {}
for _, group_name in ipairs(group_names) do
is_group[group_name] = true
local rep = unified_inventory.registered_group_items[group_name]
if rep then registered_rep[rep] = true end
end
local bestitem = ""
local bestpref = 0
for _, item in ipairs(candidate_items) do
local pref
if registered_rep[item] then
pref = 4
elseif string.sub(item, 1, 8) == "default:" and is_group[string.sub(item, 9)] then
pref = 3
elseif is_group[item:gsub("^[^:]*:", "")] then
pref = 2
else
pref = 1
end
if pref > bestpref or (pref == bestpref and item < bestitem) then
bestitem = item
bestpref = pref
end
end
return {item = bestitem, sole = false}
end
local group_item_cache = {}
function unified_inventory.get_group_item(group_name)
if not group_item_cache[group_name] then
group_item_cache[group_name] = compute_group_item(group_name)
end
return group_item_cache[group_name]
end
|
function unified_inventory.canonical_item_spec_matcher(spec)
local specname = ItemStack(spec):get_name()
if specname:sub(1, 6) == "group:" then
local group_names = specname:sub(7):split(",")
return function (itemname)
local itemdef = minetest.registered_items[itemname]
for _, group_name in ipairs(group_names) do
if (itemdef.groups[group_name] or 0) == 0 then
return false
end
end
return true
end
else
return function (itemname) return itemname == specname end
end
end
function unified_inventory.item_matches_spec(item, spec)
local itemname = ItemStack(item):get_name()
return unified_inventory.canonical_item_spec_matcher(spec)(itemname)
end
unified_inventory.registered_group_items = {
mesecon_conductor_craftable = "mesecons:wire_00000000_off",
stone = "default:cobble",
wool = "wool:white",
ingot = "default:steel_ingot",
}
function unified_inventory.register_group_item(groupname, itemname)
unified_inventory.registered_group_items[groupname] = itemname
end
-- This is used when displaying craft recipes, where an ingredient is
-- specified by group rather than as a specific item. A single-item group
-- is represented by that item, with the single-item status signalled
-- in the "sole" field. If the group contains no items at all, the item
-- field will be nil.
--
-- Within a multiple-item group, we prefer to use an item that has the
-- same specific name as the group, and if there are more than one of
-- those items we prefer the one registered for the group by a mod.
-- Among equally-preferred items, we just pick the one with the
-- lexicographically earliest name.
--
-- The parameter to this function isn't just a single group name.
-- It may be a comma-separated list of group names. This is really a
-- "group:..." ingredient specification, minus the "group:" prefix.
local function compute_group_item(group_name_list)
local group_names = group_name_list:split(",")
local candidate_items = {}
for itemname, itemdef in pairs(minetest.registered_items) do
if (itemdef.groups.not_in_creative_inventory or 0) == 0 then
local all = true
for _, group_name in ipairs(group_names) do
if (itemdef.groups[group_name] or 0) == 0 then
all = false
end
end
if all then table.insert(candidate_items, itemname) end
end
end
local num_candidates = #candidate_items
if num_candidates == 0 then
return {sole = true}
elseif num_candidates == 1 then
return {item = candidate_items[1], sole = true}
end
local is_group = {}
local registered_rep = {}
for _, group_name in ipairs(group_names) do
is_group[group_name] = true
local rep = unified_inventory.registered_group_items[group_name]
if rep then registered_rep[rep] = true end
end
local bestitem = ""
local bestpref = 0
for _, item in ipairs(candidate_items) do
local pref
if registered_rep[item] then
pref = 4
elseif string.sub(item, 1, 8) == "default:" and is_group[string.sub(item, 9)] then
pref = 3
elseif is_group[item:gsub("^[^:]*:", "")] then
pref = 2
else
pref = 1
end
if pref > bestpref or (pref == bestpref and item < bestitem) then
bestitem = item
bestpref = pref
end
end
return {item = bestitem, sole = false}
end
local group_item_cache = {}
function unified_inventory.get_group_item(group_name)
if not group_item_cache[group_name] then
group_item_cache[group_name] = compute_group_item(group_name)
end
return group_item_cache[group_name]
end
|
[u_inv] Use steel ingots as group item for ingots
|
[u_inv] Use steel ingots as group item for ingots
- Fix #480
|
Lua
|
unlicense
|
sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun
|
End of preview. Expand
in Data Studio
- Downloads last month
- 3