hexsha
stringlengths 40
40
| size
int64 5
129k
| content
stringlengths 5
129k
| avg_line_length
float64 4
98.3
| max_line_length
int64 5
660
| alphanum_fraction
float64 0.25
0.98
|
---|---|---|---|---|---|
99a3700fbaa2aa0350051c11ec5281a40727f8b4 | 236 | import AtlasData from require "LunoPunk.graphics.atlas.AtlasData"
-- TODO
class Atlas
new: =>
loadImageAsRegion: (source) ->
data = AtlasData.create source
data\createRegion Rectangle 0, 0, data\width!, data\height!
{ :Atlas }
| 19.666667 | 65 | 0.728814 |
f1c321f4b159faee523bd661b7a0c5c1df298bcc | 2,777 |
require('vimp')
assert = require("vimp.util.assert")
log = require("vimp.util.log")
helpers = require("vimp.testing.helpers")
TestKeys = '<f4>'
class Tester
test_nnoremap: =>
helpers.unlet('foo')
vimp.nnoremap TestKeys, [[:let g:foo = 5<cr>]]
assert.is_equal(vim.g.foo, nil)
helpers.rinput(TestKeys)
assert.is_equal(vim.g.foo, 5)
test_inoremap: =>
vimp.inoremap TestKeys, 'foo'
helpers.rinput("i#{TestKeys}")
assert.is_equal(helpers.get_line!, 'foo')
test_xnoremap: =>
vimp.xnoremap TestKeys, 'cfoo'
helpers.input("istart middle end<esc>")
assert.is_equal(helpers.get_line!, 'start middle end')
helpers.input("Fmviw")
helpers.rinput(TestKeys)
assert.is_equal(helpers.get_line!, 'start foo end')
test_snoremap: =>
vimp.snoremap TestKeys, 'foo'
helpers.input("istart mid end<esc>")
assert.is_equal(helpers.get_line!, 'start mid end')
helpers.input("Fmgh<right><right>")
helpers.rinput(TestKeys)
assert.is_equal(helpers.get_line!, 'start foo end')
test_cnoremap: =>
vimp.cnoremap TestKeys, 'foo'
helpers.unlet('foo')
helpers.rinput(":let g:foo='#{TestKeys}'<cr>")
assert.is_equal(vim.g.foo, 'foo')
test_onoremap: =>
vimp.onoremap TestKeys, 'aw'
helpers.input("istart mid end<esc>Fm")
helpers.rinput("d#{TestKeys}")
assert.is_equal(helpers.get_line!, 'start end')
-- Skip this one because it's tricky to test
-- Test it manually instead
-- test_tnoremap: =>
test_nmap: =>
helpers.unlet('foo')
vimp.nmap TestKeys, [[:let g:foo = 5<cr>]]
assert.is_equal(vim.g.foo, nil)
helpers.rinput(TestKeys)
assert.is_equal(vim.g.foo, 5)
test_imap: =>
vimp.imap TestKeys, 'foo'
helpers.rinput("i#{TestKeys}")
assert.is_equal(helpers.get_line!, 'foo')
test_xmap: =>
vimp.xmap TestKeys, 'cfoo'
helpers.input("istart middle end<esc>")
assert.is_equal(helpers.get_line!, 'start middle end')
helpers.input("Fmviw")
helpers.rinput(TestKeys)
assert.is_equal(helpers.get_line!, 'start foo end')
test_smap: =>
vimp.smap TestKeys, 'foo'
helpers.input("istart mid end<esc>")
assert.is_equal(helpers.get_line!, 'start mid end')
helpers.input("Fmgh<right><right>")
helpers.rinput(TestKeys)
assert.is_equal(helpers.get_line!, 'start foo end')
test_cmap: =>
vimp.cmap TestKeys, 'foo'
helpers.unlet('foo')
helpers.rinput(":let g:foo='#{TestKeys}'<cr>")
assert.is_equal(vim.g.foo, 'foo')
test_omap: =>
vimp.omap TestKeys, 'iw'
helpers.input("istart mid end<esc>Fm")
helpers.rinput("d#{TestKeys}")
assert.is_equal(helpers.get_line!, 'start end')
-- Skip this one because it's tricky to test
-- Test it manually instead
-- test_tmap: =>
| 28.336735 | 58 | 0.661145 |
5c7fd682867380391a9b378499fecf58e4fce42e | 1,704 | import loadfile from require 'moonscript.base'
Context = require 'moonbuild.context'
DepGraph = require 'moonbuild.core.DAG'
Executor = require 'moonbuild.core.executor'
_ = require 'moonbuild._'
import insert from table
moonbuild = (...) ->
-- build argument table
opts = {}
for i=1, select '#', ...
arg = select i, ...
if (type arg) == 'string'
insert opts, arg
elseif (type arg) == 'table'
for k, v in pairs arg
opts[k] = v if (type k) != 'number'
for i, v in ipairs arg
insert opts, v
else
error "Invalid argument type #{type arg} for moonbuild"
-- resolve arguments
buildfile = opts.buildfile or opts.b or 'Build.moon'
opts.buildfile = buildfile
parallel = opts.parallel or opts.j or 1
parallel = true if parallel == 'y'
opts.parallel = parallel
quiet = opts.quiet or opts.q or false
opts.quiet = quiet
force = opts.force or opts.f or false
opts.force = force
verbose = opts.verbose or opts.v or false
opts.verbose = verbose
-- create context and DAG
ctx = Context!
ctx\load (loadfile buildfile), opts
print "Loaded buildfile" if verbose
ctx\init!
print "Initialized buildfile" if verbose
targets = #opts==0 and ctx.defaulttargets or opts
dag = DepGraph ctx, targets
print "Created dependancy graph" if verbose
-- and build
nparallel = parallel == true and Executor\getmaxparallel! or parallel
print "Building with #{nparallel} max parallel process#{nparallel>1 and "es" or ""}" if verbose
executor = Executor dag, nparallel
executor\execute opts
print "Finished" if verbose
table = {
:moonbuild, :_
:Context, :DepGraph, :Executor
}
setmetatable table,
__call: (...) => moonbuild ...
__index: (name) => require "moonbuild.#{name}"
| 27.934426 | 96 | 0.699531 |
d2b86a2f553fa3a1ad319ed91c35a028991e3803 | 19,311 |
-- Copyright (C) 2018-2020 DBotThePony
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
import DPP2 from _G
import Menus from DPP2
Menus._Icons = {
Add: 'icon16/pencil_add.png'
Wrench: 'icon16/wrench.png'
Wrench2: 'icon16/wrench_orange.png'
AddPlain: 'icon16/add.png'
Edit: 'icon16/pencil.png'
Copy: ['icon16/tag_' .. tag .. '.png' for tag in *{'blue', 'green', 'orange', 'pink', 'purple', 'red', 'yellow'}]
CleanupMenu: 'icon16/package_delete.png'
Restrict: 'icon16/cross.png'
Confirm: 'icon16/accept.png'
Angle: {'icon16/arrow_rotate_anticlockwise.png', 'icon16/arrow_rotate_clockwise.png'}
Vector: 'icon16/arrow_in.png'
Share: 'icon16/key_add.png'
ShareAll: 'icon16/key_go.png'
UnShare: 'icon16/key_delete.png'
ShareContraption: 'icon16/lock_add.png'
ShareAllContraption: 'icon16/lock_go.png'
UnShareContraption: 'icon16/lock_delete.png'
LockTool: 'icon16/lock.png'
UnLockTool: 'icon16/lock_open.png'
LockToolAll: 'icon16/lock_go.png'
UnLockToolAll: 'icon16/lock_delete.png'
}
Menus.Icons = setmetatable({}, {
__index: (key) => istable(Menus._Icons[key]) and table.Random(Menus._Icons[key]) or Menus._Icons[key]
})
Menus.ModelBlacklistMenu = =>
return if not IsValid(@)
DPP2.ModelBlacklist\BuildCPanel(@)
button = @Button('gui.dpp2.model_blacklist.window_title')
button.DoClick = -> Menus.OpenModelBlacklistFrame(
DPP2.ModelBlacklist,
'gui.dpp2.model_blacklist.window_title'
)
Menus.QCheckBox(@, 'model_blacklist_props')
Menus.ModelExclusionMenu = =>
return if not IsValid(@)
DPP2.ModelExclusions\BuildCPanel(@)
button = @Button('gui.dpp2.model_exclusions.window_title')
button.DoClick = -> Menus.OpenModelBlacklistFrame(
DPP2.ModelExclusions,
'gui.dpp2.model_exclusions.window_title'
)
Menus.QCheckBox(@, 'model_exclusion_props')
Menus.ModelRestrictionMenu = =>
return if not IsValid(@)
DPP2.ModelRestrictions\BuildCPanel(@)
button = @Button('gui.dpp2.model_exclusions.window_title')
button.DoClick = -> Menus.OpenModelRestricitonFrame(
DPP2.ModelRestrictions,
'gui.dpp2.model_restrictions.window_title'
)
Menus.QCheckBox(@, 'model_restrict_props')
Menus.ModelLimitMenu = =>
return if not IsValid(@)
DPP2.PerModelLimits\BuildCPanel(@)
button = @Button('gui.dpp2.model_limits.window_title')
button.DoClick = -> Menus.OpenModelRestricitonFrame(
DPP2.PerModelLimits,
'gui.dpp2.model_restrictions.window_title',
false
)
Menus.OpenModelBlacklistFrame = (target, name) ->
self = vgui.Create('DLib_Window')
@SetSize(ScrW() - 100, ScrH() - 100)
@SetTitle(name)
@Center()
@MakePopup()
scroll = vgui.Create('DScrollPanel', @)
scroll\DockMargin(5, 5, 5, 5)
scroll\Dock(FILL)
canvas = scroll\GetCanvas()
grid = vgui.Create('DTileLayout', canvas)
grid\Dock(FILL)
grid\SetSelectionCanvas(true)
grid\SetDnD(false)
buttons = {}
openMultipleMenu = (selected = grid\GetSelectedChildren()) ->
return if #selected == 0
with menu = DermaMenu()
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. target.remove_command_identifier)
remove = ->
for button in *selected
RunConsoleCommand('dpp2_' .. target.remove_command_identifier, button._model)
submenu, button = \AddSubMenu('gui.dpp2.menu.remove_from_' .. target.identifier .. '_' .. target.__class.REGULAR_NAME)
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', remove)\SetIcon(Menus.Icons.Remove)
\Open()
grid.DoRightClick = openMultipleMenu
openButtonMenu = =>
selected = grid\GetSelectedChildren()
if #selected == 0
with menu = DermaMenu()
\AddOption('gui.dpp2.property.copyclassname', (-> SetClipboardText(@_model)))\SetIcon(Menus.Icons.Copy)
\AddSpacer()
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. target.remove_command_identifier)
remove = -> RunConsoleCommand('dpp2_' .. target.remove_command_identifier, @_model)
submenu, button = \AddSubMenu('gui.dpp2.menu.remove_from_' .. target.identifier .. '_' .. target.__class.REGULAR_NAME)
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', remove)\SetIcon(Menus.Icons.Remove)
\Open()
else
openMultipleMenu(selected)
rebuildList = ->
button._mark = true for _, button in pairs(buttons)
for _, model in SortedPairs(target.listing.values)
if not buttons[model]
button = vgui.Create('SpawnIcon', grid)
button\SetSize(64, 64)
button\SetModel(model)
button\SetTooltip(model)
button._model = model
button.DoClick = openButtonMenu
button.DoRightClick = button.DoClick
button.OpenMenu = button.DoClick
buttons[model] = button
else
buttons[model]._mark = false
button\Remove() for _, button in pairs(buttons) when button._mark
buttons = {_, button for _, button in pairs(buttons) when not button._mark}
grid\Layout()
rebuildList()
hook.Add 'DPP2_' .. target.__class.__name .. '_' .. target.identifier .. '_EntryAdded', @, -> timer.Create 'DPP2_RebuildModelVisualMenu' .. target.identifier, 0.1, 1, rebuildList
hook.Add 'DPP2_' .. target.__class.__name .. '_' .. target.identifier .. '_EntryRemoved', @, -> timer.Create 'DPP2_RebuildModelVisualMenu' .. target.identifier, 0.1, 1, rebuildList
Menus.OpenModelRestricitonFrame = (target, name, mode = true) ->
self = vgui.Create('DLib_Window')
@SetSize(ScrW() - 100, ScrH() - 100)
@SetTitle(name)
@Center()
@MakePopup()
scroll = vgui.Create('DScrollPanel', @)
scroll\DockMargin(5, 5, 5, 5)
scroll\Dock(FILL)
canvas = scroll\GetCanvas()
grid = vgui.Create('DTileLayout', canvas)
grid\Dock(FILL)
grid\SetSelectionCanvas(true)
grid\SetDnD(false)
buttons = {}
openMultipleMenu = (selected = grid\GetSelectedChildren()) ->
return if #selected == 0
with menu = DermaMenu()
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. target.remove_command_identifier)
remove = ->
for button in *selected
if mode
RunConsoleCommand('dpp2_' .. target.remove_command_identifier, button._model)
else
RunConsoleCommand('dpp2_' .. target.remove_command_identifier, button._model, entry.group) for entry in *target\GetByClass(button._model)
submenu, button = \AddSubMenu('gui.dpp2.menus.remove')
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', remove)\SetIcon(Menus.Icons.Remove)
\Open()
grid.DoRightClick = openMultipleMenu
openButtonMenu = =>
selected = grid\GetSelectedChildren()
if #selected == 0
with menu = DermaMenu()
\AddOption('gui.dpp2.property.copyclassname', (-> SetClipboardText(@_model)))\SetIcon(Menus.Icons.Copy)
\AddSpacer()
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. target.add_command_identifier)
edit = -> target\OpenMenu(@_model)
\AddOption('gui.dpp2.menus.edit', edit)\SetIcon(Menus.Icons.Edit)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. target.remove_command_identifier)
remove = ->
if mode
RunConsoleCommand('dpp2_' .. target.remove_command_identifier, @_model)
else
RunConsoleCommand('dpp2_' .. target.remove_command_identifier, @_model, entry.group) for entry in *target\GetByClass(@_model)
submenu, button = \AddSubMenu('gui.dpp2.menus.remove')
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', remove)\SetIcon(Menus.Icons.Remove)
\Open()
else
openMultipleMenu(selected)
rebuildList = ->
button._mark = true for _, button in pairs(buttons)
listModels = {}
table.insert(listModels, object.class) for object in *target.listing when not table.qhasValue(listModels, object.class)
table.sort(listModels)
for model in *listModels
if not buttons[model]
button = vgui.Create('SpawnIcon', grid)
button\SetSize(64, 64)
button\SetModel(model)
button\SetTooltip(model)
button._model = model
button.DoClick = openButtonMenu
button.DoRightClick = button.DoClick
button.OpenMenu = button.DoClick
buttons[model] = button
else
buttons[model]._mark = false
button\Remove() for _, button in pairs(buttons) when button._mark
buttons = {_, button for _, button in pairs(buttons) when not button._mark}
grid\Layout()
rebuildList()
if mode
hook.Add 'DPP2_' .. target.identifier .. '_EntryAdded', @, -> timer.Create 'DPP2_RebuildModelRVisualMenu' .. target.identifier, 0.1, 1, rebuildList
hook.Add 'DPP2_' .. target.identifier .. '_EntryRemoved', @, -> timer.Create 'DPP2_RebuildModelRVisualMenu' .. target.identifier, 0.1, 1, rebuildList
else
hook.Add 'DPP2_Limits_' .. target.identifier .. '_EntryAdded', @, -> timer.Create 'DPP2_RebuildModelRVisualMenu' .. target.identifier, 0.1, 1, rebuildList
hook.Add 'DPP2_Limits_' .. target.identifier .. '_EntryRemoved', @, -> timer.Create 'DPP2_RebuildModelRVisualMenu' .. target.identifier, 0.1, 1, rebuildList
Menus.ClientCommands = =>
return if not IsValid(@)
@Button('message.dpp2.import.button_dpp_friends', 'dpp2_import_dpp_friends')
@Button('message.dpp2.import.button_fpp_friends', 'dpp2_import_fpp_friends')
hook.Add 'PopulateToolMenu', 'DPP2.Menus', ->
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.client', 'gui.dpp2.toolmenu.client_protection', 'gui.dpp2.toolmenu.client_protection', '', '', Menus.ClientProtectionModulesMenu
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.client', 'gui.dpp2.toolmenu.client_settings', 'gui.dpp2.toolmenu.client_settings', '', '', Menus.ClientMenu
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.client', 'gui.dpp2.toolmenu.client_commands', 'gui.dpp2.toolmenu.client_commands', '', '', Menus.ClientCommands
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.client', 'gui.dpp2.toolmenu.transfer_fallback', 'gui.dpp2.toolmenu.transfer_fallback', '', '', Menus.BuildTransferFallbackPanel
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.client', 'gui.dpp2.toolmenu.transfer', 'gui.dpp2.toolmenu.transfer', '', '', Menus.BuildTransferPanel
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.main', 'gui.dpp2.toolmenu.primary', 'gui.dpp2.toolmenu.primary', '', '', Menus.PrimaryMenu
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.main', 'gui.dpp2.toolmenu.secondary', 'gui.dpp2.toolmenu.secondary', '', '', Menus.SecondaryMenu
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.main', 'gui.dpp2.toolmenu.logging', 'gui.dpp2.toolmenu.logging', '', '', Menus.LoggingMenu
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.main', 'gui.dpp2.toolmenu.antispam', 'gui.dpp2.toolmenu.antispam', '', '', Menus.AntispamMenu
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.main', 'gui.dpp2.toolmenu.antipropkill', 'gui.dpp2.toolmenu.antipropkill', '', '', Menus.AntipropkillMenu
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.player', 'gui.dpp2.toolmenu.playermode', 'gui.dpp2.toolmenu.playermode', '', '', Menus.BuildPlayerModePanel
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.player', 'gui.dpp2.toolmenu.cleanup', 'gui.dpp2.toolmenu.cleanup', '', '', Menus.BuildCleanupPanel
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.player', 'gui.dpp2.toolmenu.utils', 'gui.dpp2.toolmenu.utils', '', '', Menus.BuildUtilsPanel
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.limits', 'gui.dpp2.toolmenu.limits.sbox', 'gui.dpp2.toolmenu.limits.sbox', '', '', => DPP2.SBoxLimits\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.limits', 'gui.dpp2.toolmenu.limits.entity', 'gui.dpp2.toolmenu.limits.entity', '', '', => DPP2.PerEntityLimits\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.limits', 'gui.dpp2.toolmenu.limits.model', 'gui.dpp2.toolmenu.limits.model', '', '', Menus.ModelLimitMenu
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.restriction', 'gui.dpp2.toolmenu.restrictions.physgun', 'gui.dpp2.toolmenu.restrictions.physgun', '', '', => DPP2.PhysgunProtection.RestrictionList\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.restriction', 'gui.dpp2.toolmenu.restrictions.drive', 'gui.dpp2.toolmenu.restrictions.drive', '', '', => DPP2.DriveProtection.RestrictionList\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.restriction', 'gui.dpp2.toolmenu.restrictions.pickup', 'gui.dpp2.toolmenu.restrictions.pickup', '', '', => DPP2.PickupProtection.RestrictionList\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.restriction', 'gui.dpp2.toolmenu.restrictions.use', 'gui.dpp2.toolmenu.restrictions.use', '', '', => DPP2.UseProtection.RestrictionList\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.restriction', 'gui.dpp2.toolmenu.restrictions.vehicle', 'gui.dpp2.toolmenu.restrictions.vehicle', '', '', => DPP2.VehicleProtection.RestrictionList\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.restriction', 'gui.dpp2.toolmenu.restrictions.gravgun', 'gui.dpp2.toolmenu.restrictions.gravgun', '', '', => DPP2.GravgunProtection.RestrictionList\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.restriction', 'gui.dpp2.toolmenu.restrictions.toolgun', 'gui.dpp2.toolmenu.restrictions.toolgun', '', '', => DPP2.ToolgunProtection.RestrictionList\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.restriction', 'gui.dpp2.toolmenu.restrictions.toolgun_mode', 'gui.dpp2.toolmenu.restrictions.toolgun_mode', '', '', => DPP2.ToolgunModeRestrictions\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.restriction', 'gui.dpp2.toolmenu.restrictions.damage', 'gui.dpp2.toolmenu.restrictions.damage', '', '', => DPP2.DamageProtection.RestrictionList\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.restriction', 'gui.dpp2.toolmenu.restrictions.class_spawn', 'gui.dpp2.toolmenu.restrictions.class_spawn', '', '', => DPP2.SpawnRestrictions\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.restriction', 'gui.dpp2.toolmenu.restrictions.model', 'gui.dpp2.toolmenu.restrictions.model', '', '', Menus.ModelRestrictionMenu
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.restriction', 'gui.dpp2.toolmenu.restrictions.e2fn', 'gui.dpp2.toolmenu.restrictions.e2fn', '', '', => DPP2.E2FunctionRestrictions\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.blacklist', 'gui.dpp2.toolmenu.blacklist.model', 'gui.dpp2.toolmenu.blacklist.model', '', '', Menus.ModelBlacklistMenu
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.blacklist', 'gui.dpp2.toolmenu.blacklist.physgun', 'gui.dpp2.toolmenu.blacklist.physgun', '', '', => DPP2.PhysgunProtection.Blacklist\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.blacklist', 'gui.dpp2.toolmenu.blacklist.drive', 'gui.dpp2.toolmenu.blacklist.drive', '', '', => DPP2.DriveProtection.Blacklist\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.blacklist', 'gui.dpp2.toolmenu.blacklist.pickup', 'gui.dpp2.toolmenu.blacklist.pickup', '', '', => DPP2.PickupProtection.Blacklist\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.blacklist', 'gui.dpp2.toolmenu.blacklist.use', 'gui.dpp2.toolmenu.blacklist.use', '', '', => DPP2.UseProtection.Blacklist\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.blacklist', 'gui.dpp2.toolmenu.blacklist.vehicle', 'gui.dpp2.toolmenu.blacklist.vehicle', '', '', => DPP2.VehicleProtection.Blacklist\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.blacklist', 'gui.dpp2.toolmenu.blacklist.gravgun', 'gui.dpp2.toolmenu.blacklist.gravgun', '', '', => DPP2.GravgunProtection.Blacklist\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.blacklist', 'gui.dpp2.toolmenu.blacklist.toolgun', 'gui.dpp2.toolmenu.blacklist.toolgun', '', '', => DPP2.ToolgunProtection.Blacklist\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.blacklist', 'gui.dpp2.toolmenu.blacklist.damage', 'gui.dpp2.toolmenu.blacklist.damage', '', '', => DPP2.DamageProtection.Blacklist\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.exclusions', 'gui.dpp2.toolmenu.exclusions.model', 'gui.dpp2.toolmenu.exclusions.model', '', '', Menus.ModelExclusionMenu
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.exclusions', 'gui.dpp2.toolmenu.exclusions.physgun', 'gui.dpp2.toolmenu.exclusions.physgun', '', '', => DPP2.PhysgunProtection.Exclusions\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.exclusions', 'gui.dpp2.toolmenu.exclusions.drive', 'gui.dpp2.toolmenu.exclusions.drive', '', '', => DPP2.DriveProtection.Exclusions\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.exclusions', 'gui.dpp2.toolmenu.exclusions.pickup', 'gui.dpp2.toolmenu.exclusions.pickup', '', '', => DPP2.PickupProtection.Exclusions\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.exclusions', 'gui.dpp2.toolmenu.exclusions.use', 'gui.dpp2.toolmenu.exclusions.use', '', '', => DPP2.UseProtection.Exclusions\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.exclusions', 'gui.dpp2.toolmenu.exclusions.vehicle', 'gui.dpp2.toolmenu.exclusions.vehicle', '', '', => DPP2.VehicleProtection.Exclusions\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.exclusions', 'gui.dpp2.toolmenu.exclusions.gravgun', 'gui.dpp2.toolmenu.exclusions.gravgun', '', '', => DPP2.GravgunProtection.Exclusions\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.exclusions', 'gui.dpp2.toolmenu.exclusions.toolgun', 'gui.dpp2.toolmenu.exclusions.toolgun', '', '', => DPP2.ToolgunProtection.Exclusions\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.exclusions', 'gui.dpp2.toolmenu.exclusions.toolgun_mode', 'gui.dpp2.toolmenu.exclusions.toolgun_mode', '', '', => DPP2.ToolgunModeExclusions\BuildCPanel(@)
spawnmenu.AddToolMenuOption 'DPP/2', 'gui.dpp2.toolcategory.exclusions', 'gui.dpp2.toolmenu.exclusions.damage', 'gui.dpp2.toolmenu.exclusions.damage', '', '', => DPP2.DamageProtection.Exclusions\BuildCPanel(@)
| 55.651297 | 223 | 0.747139 |
49c97a745c88e607b9b48a9149d8fe8a9cd250ff | 1,219 | describe "run.vimscript", ->
setup ->
parse = require('lush.parser')
ast = parse -> {
A { gui: "italic", blend: 40 }
}
package.loaded["theme"] = ast
_G.vim = {
inspect: ->
"inspect mock"
list_slice: (list, s, e) ->
[item for item in *list[s,e]]
}
teardown ->
package.loaded["theme"] = nil
it "returns vimscript", ->
vimscript = require("shipwright.transform.lush.to_vimscript")
value = vimscript(require("theme"))
assert.is.table(value)
assert.matches("highlight A guifg=NONE guibg=NONE guisp=NONE gui=italic blend=40", value[1])
it "orders the vimscript", ->
vimscript = require("shipwright.transform.lush.to_vimscript")
parse = require('lush.parser')
ast = parse -> {
Apple { gui: "italic", blend: 40 }, -- first
Bananna { gui: "italic", blend: 40 }, -- after apple and links
Cat { Apple } -- link, so after apple, after bandana
Bandana { Apple } -- link, so after apple
}
value = vimscript(ast)
assert.match("highlight Apple", value[1])
assert.match("link Bandana Apple", value[2])
assert.match("link Cat Apple", value[3])
assert.match("highlight Bananna", value[4])
| 32.078947 | 96 | 0.607055 |
8e847de921a056e0738c3a6879be702421a77b2c | 1,795 | ----------------------------------------------------------------
-- A structure for storing a simple key-value table but it also
-- keeps track of how many pairs are in the table.
--
-- @classmod HashMap
-- @author Richard Voelker
-- @license MIT
----------------------------------------------------------------
-- {{ TBSHTEMPLATE:BEGIN }}
class HashMap
----------------------------------------------------------------
-- Create the HashMap. Values are stored and retrieved as if
-- this were a normal table.
--
-- @tparam HashMap self
-- @tparam table t The starting values for the HashMap.
----------------------------------------------------------------
new: (t) =>
rawset @, "_t", {}
rawset @, "_length", 0
for key, value in pairs t
@[key] = value
mt = getmetatable @
old_index = mt.__index
mt.__index = (key) =>
if value = rawget rawget(@, "_t"), key
return value
else
if type(old_index) == "function"
return old_index @, key
else
return old_index[key]
----------------------------------------------------------------
-- @treturn iterator The pairs iterator over the table.
----------------------------------------------------------------
pairs: => pairs @_t
----------------------------------------------------------------
-- Alias for the __len metamethod. Since the __len metamethod is
-- not supported in Lua 5.1 (the current version on ROBLOX),
-- this can be used instead.
--
-- @treturn integer The number of key-value pairs in the table.
----------------------------------------------------------------
Length: => @\__len!
__newindex: (key, value) =>
if @_t[key] == nil
@_length += 1
elseif value == nil
@_length -= 1
@_t[key] = value
__len: => @_length
-- {{ TBSHTEMPLATE:END }}
return HashMap
| 28.046875 | 65 | 0.457939 |
6b37a6c935112a3600d86a45db25d8f78cb9372d | 2,846 | import Widget from require "lapis.html"
import ResourceScreenshots from require "models"
date = require "date"
db = require "lapis.db"
i18n = require "i18n"
class MTAResourceManageScreenies extends Widget
@include "widgets.utils"
name: "Screenshots"
content: =>
p -> button type: "button", class: "btn btn-primary", ["data-toggle"]: "collapse", ["data-target"]: "#upload", ["aria-expanded"]: "false", ["aria-controls"]: "upload", ->
i class: "fa fa-chevron-circle-down"
raw " "
text i18n "resources.manage.screenshots.upload"
div class: "collapse", id: "upload", ->
div class: "card card-block", ->
form method: "POST", enctype: "multipart/form-data", ->
@write_csrf_input!
fieldset class: "form-group", ->
label for: "screenieTitle", ->
text "#{i18n 'resources.manage.screenshots.title'} "
small class: "text-muted", i18n "resources.manage.screenshots.title_info"
input type: "text", class: "form-control", id: "screenieTitle", name: "screenieTitle", required: true
fieldset class: "form-group", ->
label for: "screenieDescription", ->
text "#{i18n 'resources.manage.screenshots.description'} "
small class: "text-muted", i18n "resources.manage.screenshots.optional"
textarea class: "form-control", id: "screenieDescription", name: "screenieDescription", rows: 3
input type: "file", name: "screenieFile", required: true
button type: "submit", class: "btn btn-secondary btn-sm", ->
i class: "fa fa-upload"
text " #{i18n 'resources.manage.packages.upload'}"
div class: "card", ->
div class: "card-header", ->
text i18n "resources.manage.tab_screenshots"
div class: "card-block", ->
screenshots = ResourceScreenshots\select "where resource = ? order by created_at desc", @resource.id, fields: "id, title, created_at"
if #screenshots == 0
return p i18n "resources.manage.screenshots.none_uploaded"
element "table", class: "table table-hover table-bordered table-href mta-card-table", ->
thead ->
th i18n "resources.table.title"
th i18n "resources.table.publish_date"
tbody ->
for screenshot in *screenshots
manage_url = @url_for("resources.manage.view_screenshot", resource_slug: @resource, screenie_id: screenshot.id)
view_url = @url_for("resources.view_screenshot", resource_slug: @resource, screenie_id: screenshot.id)
tr ["data-href"]: manage_url, ->
td screenshot.title
td ->
text date(screenshot.created_at)\fmt "${http}"
div class: "pull-xs-right", ->
a href: view_url , class: "btn btn-sm btn-secondary", -> i class: "fa fa-globe"
raw " "
a href: manage_url, class: "btn btn-sm btn-secondary", -> i class: "fa fa-cogs" | 46.655738 | 173 | 0.64617 |
052ffbe5de13428810526e72be519f720d4987c9 | 1,464 | local Client
export ^
local *
unit = assert require "luaunit"
Client = assert require "lrpc.client"
Server = assert require "lrpc.server"
--------------------------------------------------------------------------------
reduce = (op, acc, n, ...) ->
return acc if n == nil
reduce op, (op acc, n), ...
client = Client "localhost"
--------------------------------------------------------------------------------
TestRPC =
testSum: =>
expected = reduce ((a, b) -> a + b), 1, 2, 3, 4
resp, count = client.remote.sum 1, 2, 3, 4
unit.assertEquals resp, expected
unit.assertEquals count, 4
testFact: =>
expected = 120
resp = client.remote.fact 5
unit.assertEquals resp, expected
testUnregistered: =>
expected = ": unknown command unknown"
unit.assertErrorMsgContains expected, client.remote.unknown, "data"
testNotReset: =>
expected = ": cannot set remote attributes"
unit.assertErrorMsgContains expected, -> client.remote.other = true
testExpectFunction: =>
server = Server "localhost", 54001
expected = ": expected function, got string"
unit.assertErrorMsgContains expected, -> server.callbacks.some = "some"
server.callbacks.a = -> nil
server.callbacks.b = setmetatable {}, __call: () => nil
--------------------------------------------------------------------------------
os.exit unit.LuaUnit.run!
| 28.705882 | 80 | 0.519126 |
377264a83ce41e2c586bdf4b168f50fff3a36f03 | 1,247 | require "busted"
require "tests.mock_love"
import EventListener from require "LunoPunk.utils.EventListener"
describe "EventListener", ->
e = EventListener
after_each -> e\remove "test"
it "add/remove", ->
-- Add a couple
el1 = -> assert false, "EventListener1"
e\add "test", el1
el2 = -> assert false, "EventListener2"
e\add "test", el2
assert.are.equal 2, e.__listeners["test"]\len!
-- Remove each
e\remove "test", el1
assert.are.equal 1, e.__listeners["test"]\len!
-- Check a non-existant callback
assert.is.Nil e\remove "test", 'fu'
e\remove "test", el2
assert.are.equal 0, e.__listeners["test"]\len!
assert.has_no.errors -> e\dispatch "test"
-- Remove all with remove "", nil
e\add "test", el1
e\add "test", el2
assert.are.equal 2, e.__listeners["test"]\len!
e\remove "test"
assert.is.Nil e.__listeners["test"]
-- Test when the no events are added
assert.is.Nil e\remove "test", 'nil'
it "single dispatch", (done) ->
s = spy.new ->
e\add "test", s
e\dispatch "test"
assert.spy(s).was.called!
it "multi dispatch", (done) ->
s1 = spy.new ->
e\add "test", s1
s2 = spy.new ->
e\add "test", s2
e\dispatch "test"
assert.spy(s1).was.called!
assert.spy(s2).was.called!
| 23.092593 | 64 | 0.648757 |
f7da52b68ff531329f29e1d2f05e0743f9858fbc | 1,131 | do = zb2rhkLJtRQwHz9e5GjiQkBtjL2SzZZByogr1uNZFyzJGA9dX
hexToDec = zb2rhYSZqJ3v79y8EtvjYBrxMneDd1bF4t7a6BkP4HQVXDkRn
moonImage = zb2rhbEccKnwdnXWDLyMhMi2UrGdFpXtpLX9Trdx1fKzf8rbF
{
name: "moon-home"
title: {
text:"Hello, Moon"
background:"rgb(0,0,0)"
}
state: {
blockNumber: "0"
}
onFetch: |
blockNumber = <(do "eth" ["blockNumber" ["latest"]])
(do "set" {blockNumber: (hexToDec blockNumber)})>
(do "stop")
child: my =>
size = (my "size")
width = (get size "0")
height = (get size "1")
[
{
pos: [0 (sub height 150)]
size: [width 150]
background: moonImage
child: ""
}
{
pos: [20 20]
size: [90 40]
font: {color:"rgb(250,250,250)" weight:"300"}
child: "Hello,"
}
{
pos: [110 20]
size: [(sub width 130) 40]
font: {color:"rgb(250,250,250)" weight:"500"}
child: "Moon"
}
{
pos: [20 60]
size: [(sub width 40) 25]
font: {color:"rgb(80,80,80)" weight:"300"}
child: (con "Block: " (my "blockNumber"))
}
]
}
| 23.5625 | 61 | 0.531388 |
6fcdbc6ff3ad4a0bf8d3cce47862ea7318280905 | 238 | export modinfo = {
type: "command"
desc: "Remove Hats"
alias: {"nohats", "rhats", "removehats"}
func: getDoPlayersFunction (v) ->
for i,j in pairs(v.Character\GetChildren())
if j\IsA"Hat" or j\IsA"Accessory"
j.Parent = nil
} | 26.444444 | 46 | 0.655462 |
c08993d9d1b856e986706fcdda2bd5bd5fa98e95 | 17,911 |
--
-- Copyright (C) 2017-2020 DBotThePony
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
-- 0 LrigPelvis
-- 1 LrigSpine1
-- 2 LrigSpine2
-- 3 LrigRibcage
-- 4 LrigNeck1
-- 5 LrigNeck2
-- 6 LrigNeck3
-- 7 LrigScull
-- 8 Lrig_LEG_BL_Femur
-- 9 Lrig_LEG_BL_Tibia
-- 10 Lrig_LEG_BL_LargeCannon
-- 11 Lrig_LEG_BL_PhalanxPrima
-- 12 Lrig_LEG_BL_RearHoof
-- 13 Lrig_LEG_BR_Femur
-- 14 Lrig_LEG_BR_Tibia
-- 15 Lrig_LEG_BR_LargeCannon
-- 16 Lrig_LEG_BR_PhalanxPrima
-- 17 Lrig_LEG_BR_RearHoof
-- 18 Lrig_LEG_FL_Scapula
-- 19 Lrig_LEG_FL_Humerus
-- 20 Lrig_LEG_FL_Radius
-- 21 Lrig_LEG_FL_Metacarpus
-- 22 Lrig_LEG_FL_PhalangesManus
-- 23 Lrig_LEG_FL_FrontHoof
-- 24 Lrig_LEG_FR_Scapula
-- 25 Lrig_LEG_FR_Humerus
-- 26 Lrig_LEG_FR_Radius
-- 27 Lrig_LEG_FR_Metacarpus
-- 28 Lrig_LEG_FR_PhalangesManus
-- 29 Lrig_LEG_FR_FrontHoof
-- 30 Mane01
-- 31 Mane02
-- 32 Mane03
-- 33 Mane04
-- 34 Mane05
-- 35 Mane06
-- 36 Mane07
-- 37 Mane03_tip
-- 38 Tail01
-- 39 Tail02
-- 40 Tail03
USE_NEW_HULL = CreateConVar('ppm2_sv_newhull', '1', {FCVAR_NOTIFY, FCVAR_REPLICATED}, 'Use proper collision box for ponies. Slightly affects jump mechanics. When disabled, unexpected behaviour could happen.')
ALLOW_TO_MODIFY_SCALE = PPM2.ALLOW_TO_MODIFY_SCALE
class PonySizeController extends PPM2.ControllerChildren
@AVALIABLE_CONTROLLERS = {}
@MODELS = {'models/ppm/player_default_base.mdl', 'models/ppm/player_default_base_nj.mdl', 'models/cppm/player_default_base.mdl', 'models/cppm/player_default_base_nj.mdl'}
@NECK_BONE_1 = 'LrigNeck1'
@NECK_BONE_2 = 'LrigNeck2'
@NECK_BONE_3 = 'LrigNeck3'
@NECK_BONE_4 = 'LrigScull'
@LEGS_BONE_ROOT = 'LrigPelvis'
@LEGS_FRONT_1 = 'Lrig_LEG_FL_FrontHoof'
@LEGS_FRONT_2 = 'Lrig_LEG_FR_FrontHoof'
@LEGS_FRONT_3 = 'Lrig_LEG_FL_Metacarpus'
@LEGS_FRONT_4 = 'Lrig_LEG_FR_Metacarpus'
@LEGS_FRONT_5 = 'Lrig_LEG_FL_Radius'
@LEGS_FRONT_6 = 'Lrig_LEG_FR_Radius'
@LEGS_BEHIND_1_1 = 'Lrig_LEG_BR_Tibia'
@LEGS_BEHIND_2_1 = 'Lrig_LEG_BR_PhalanxPrima'
@LEGS_BEHIND_3_1 = 'Lrig_LEG_BR_LargeCannon'
@LEGS_BEHIND_1_2 = 'Lrig_LEG_BL_Tibia'
@LEGS_BEHIND_2_2 = 'Lrig_LEG_BL_PhalanxPrima'
@LEGS_BEHIND_3_2 = 'Lrig_LEG_BL_LargeCannon'
@NEXT_OBJ_ID = 0
@@skelton_mapping = {
'NECK_BONE_1'
'NECK_BONE_2'
'NECK_BONE_3'
'NECK_BONE_4'
'LEGS_BONE_ROOT'
'LEGS_FRONT_1'
'LEGS_FRONT_2'
'LEGS_FRONT_3'
'LEGS_FRONT_4'
'LEGS_FRONT_5'
'LEGS_FRONT_6'
'LEGS_BEHIND_1_1'
'LEGS_BEHIND_2_1'
'LEGS_BEHIND_3_1'
'LEGS_BEHIND_1_2'
'LEGS_BEHIND_2_2'
'LEGS_BEHIND_3_2'
}
new: (controller) =>
super(controller)
@isValid = true
@objID = @@NEXT_OBJ_ID
@@NEXT_OBJ_ID += 1
@lastPAC3BoneReset = 0
@Remap()
@GetEntity()\SetModelScale(1) if not @GetEntity()\IsPlayer() and @GetEntity()\GetModelScale() ~= 1
Remap: =>
@validSkeleton = true
ent = @GetEntity()
for name in *@@skelton_mapping
@[name] = ent\LookupBone(@@[name])
if not @[name]
@validSkeleton = false
break
IsValid: => @controller\IsValid()
GetEntity: => @controller\GetEntity()
IsNetworked: => @controller\IsNetworked()
AllowResize: => not @controller\IsNetworked() or ALLOW_TO_MODIFY_SCALE\GetBool()
@STEP_SIZE = 20
@PONY_HULL = 17
@HULL_MINS = Vector(-@PONY_HULL, -@PONY_HULL, 0)
@HULL_MAXS = Vector(@PONY_HULL, @PONY_HULL, 72 * PPM2.PONY_HEIGHT_MODIFIER)
@HULL_MAXS_DUCK = Vector(@PONY_HULL, @PONY_HULL, 36 * PPM2.PONY_HEIGHT_MODIFIER_DUCK_HULL)
@DEFAULT_HULL_MINS = Vector(-16, -16, 0)
@DEFAULT_HULL_MAXS = Vector(16, 16, 72)
@DEFAULT_HULL_MAXS_DUCK = Vector(16, 16, 36)
@DEF_SCALE = Vector(1, 1, 1)
DataChanges: (state) =>
return if not IsValid(@GetEntity())
return if not @GetEntity()\IsPony()
@Remap()
@GetEntity()\SetModelScale(1) if not @GetEntity()\IsPlayer() and @GetEntity()\GetModelScale() ~= 1
if state\GetKey() == 'PonySize'
@ModifyScale()
if state\GetKey() == 'NeckSize'
@ModifyNeck()
@ModifyViewOffset()
if state\GetKey() == 'LegsSize'
@ModifyLegs()
@ModifyHull()
@ModifyViewOffset()
ResetViewOffset: (ent = @GetEntity()) =>
ent\SetViewOffset(PPM2.PLAYER_VIEW_OFFSET_ORIGINAL) if ent.SetViewOffset
ent\SetViewOffsetDucked(PPM2.PLAYER_VIEW_OFFSET_DUCK_ORIGINAL) if ent.SetViewOffsetDucked
ResetHulls: (ent = @GetEntity()) =>
ent\ResetHull() if ent.ResetHull
ent\SetStepSize(@@STEP_SIZE) if ent.SetStepSize
ent.__ppm2_modified_hull = false
ResetJumpHeight: (ent = @GetEntity()) =>
return if CLIENT
return if not ent.SetJumpPower
return if not ent.__ppm2_modified_jump
ent\SetJumpPower(ent\GetJumpPower() / PPM2.PONY_JUMP_MODIFIER)
ent.__ppm2_modified_jump = false
ResetModelScale: (ent = @GetEntity()) =>
if SERVER
--ent\SetModelScale(1)
return
mat = Matrix()
mat\Scale(@@DEF_SCALE)
ent\EnableMatrix('RenderMultiply', mat)
ResetScale: (ent = @GetEntity()) =>
return if not IsValid(ent)
if USE_NEW_HULL\GetBool() or ent.__ppm2_modified_hull
@ResetHulls(ent)
@ResetJumpHeight(ent)
@ResetViewOffset(ent)
@ResetModelScale(ent)
if @validSkeleton
@ResetNeck(ent)
@ResetLegs(ent)
ResetNeck: (ent = @GetEntity()) =>
return if not CLIENT
return if not IsValid(@GetEntity())
return if not @validSkeleton
with ent
\ManipulateBoneScale(@NECK_BONE_1, Vector(1, 1, 1))
\ManipulateBoneScale(@NECK_BONE_2, Vector(1, 1, 1))
\ManipulateBoneScale(@NECK_BONE_3, Vector(1, 1, 1))
\ManipulateBoneScale(@NECK_BONE_4, Vector(1, 1, 1))
\ManipulateBoneAngles(@NECK_BONE_1, Angle(0, 0, 0))
\ManipulateBoneAngles(@NECK_BONE_2, Angle(0, 0, 0))
\ManipulateBoneAngles(@NECK_BONE_3, Angle(0, 0, 0))
\ManipulateBoneAngles(@NECK_BONE_4, Angle(0, 0, 0))
\ManipulateBonePosition(@NECK_BONE_1, Vector(0, 0, 0))
\ManipulateBonePosition(@NECK_BONE_2, Vector(0, 0, 0))
\ManipulateBonePosition(@NECK_BONE_3, Vector(0, 0, 0))
\ManipulateBonePosition(@NECK_BONE_4, Vector(0, 0, 0))
ResetLegs: (ent = @GetEntity()) =>
return if not CLIENT
return if not IsValid(ent)
return if not @validSkeleton
vec1 = Vector(1, 1, 1)
vec2 = Vector(0, 0, 0)
ang = Angle(0, 0, 0)
with ent
\ManipulateBoneScale(@LEGS_BONE_ROOT, vec1)
\ManipulateBoneScale(@LEGS_FRONT_1, vec1)
\ManipulateBoneScale(@LEGS_FRONT_2, vec1)
\ManipulateBoneScale(@LEGS_BEHIND_1_1, vec1)
\ManipulateBoneScale(@LEGS_BEHIND_2_1, vec1)
\ManipulateBoneScale(@LEGS_BEHIND_3_1, vec1)
\ManipulateBoneScale(@LEGS_BEHIND_1_2, vec1)
\ManipulateBoneScale(@LEGS_BEHIND_2_2, vec1)
\ManipulateBoneScale(@LEGS_BEHIND_3_2, vec1)
\ManipulateBoneAngles(@LEGS_BONE_ROOT, ang)
\ManipulateBoneAngles(@LEGS_FRONT_1, ang)
\ManipulateBoneAngles(@LEGS_FRONT_2, ang)
\ManipulateBoneAngles(@LEGS_BEHIND_1_1, ang)
\ManipulateBoneAngles(@LEGS_BEHIND_2_1, ang)
\ManipulateBoneAngles(@LEGS_BEHIND_3_1, ang)
\ManipulateBoneAngles(@LEGS_BEHIND_1_2, ang)
\ManipulateBoneAngles(@LEGS_BEHIND_2_2, ang)
\ManipulateBoneAngles(@LEGS_BEHIND_3_2, ang)
\ManipulateBonePosition(@LEGS_BONE_ROOT, vec2)
\ManipulateBonePosition(@LEGS_FRONT_1, vec2)
\ManipulateBonePosition(@LEGS_FRONT_2, vec2)
\ManipulateBonePosition(@LEGS_BEHIND_1_1, vec2)
\ManipulateBonePosition(@LEGS_BEHIND_2_1, vec2)
\ManipulateBonePosition(@LEGS_BEHIND_3_1, vec2)
\ManipulateBonePosition(@LEGS_BEHIND_1_2, vec2)
\ManipulateBonePosition(@LEGS_BEHIND_2_2, vec2)
\ManipulateBonePosition(@LEGS_BEHIND_3_2, vec2)
Remove: => @ResetScale()
Reset: =>
@ResetScale()
@ResetNeck()
@ResetLegs()
@ModifyScale()
GetLegsSize: => @GrabData('LegsSize')
GetLegsScale: => @GrabData('LegsSize')
GetNeckSize: => @GrabData('NeckSize')
GetNeckScale: => @GrabData('NeckSize')
GetPonySize: => @GrabData('PonySize')
GetPonyScale: => @GrabData('PonySize')
PlayerDeath: =>
@ResetScale()
@ResetNeck()
@ResetLegs()
@Remap()
PlayerRespawn: =>
@Remap()
@ResetScale()
@ModifyScale()
SlowUpdate: =>
@Remap()
@ModifyScale()
CalculatePonyHeight: => (@@HULL_MAXS.z - @@HULL_MINS.z) * @GetLegsModifier() * @GetPonySize()
CalculatePonyHeightFull: => (@@HULL_MAXS.z - @@HULL_MINS.z) * @GetLegsModifier() * @GetPonySize() * @GetNeckModifier() * 1.17
CalculatePonyWidth: => (@@HULL_MAXS.x - @@HULL_MINS.x) * @GetLegsModifier() * @GetPonySize()
ModifyHull: (ent = @GetEntity()) =>
ent.__ppm2_modified_hull = true
size = @GetPonySize()
legssize = @GetLegsModifier()
HULL_MINS = Vector(@@HULL_MINS)
HULL_MAXS = Vector(@@HULL_MAXS)
HULL_MAXS_DUCK = Vector(@@HULL_MAXS_DUCK)
if @AllowResize()
HULL_MINS *= size
HULL_MAXS *= size
HULL_MAXS_DUCK *= size
HULL_MINS.z *= legssize
HULL_MAXS.z *= legssize
HULL_MAXS_DUCK.z *= legssize
with ent
if .SetHull
cmins, cmaxs = \GetHull()
\SetHull(HULL_MINS, HULL_MAXS) if cmins ~= HULL_MINS or cmaxs ~= HULL_MAXS
if .SetHullDuck
cmins, cmaxs = \GetHullDuck()
\SetHullDuck(HULL_MINS, HULL_MAXS_DUCK) if cmins ~= HULL_MINS or cmaxs ~= HULL_MAXS_DUCK
if .SetStepSize
newsize = @@STEP_SIZE * size * @GetLegsModifier(1.2)
\SetStepSize(newsize) if \GetStepSize() ~= newsize
ModifyJumpHeight: (ent = @GetEntity()) =>
return if CLIENT
return if not @GetEntity().SetJumpPower
return if ent.__ppm2_modified_jump
ent\SetJumpPower(ent\GetJumpPower() * PPM2.PONY_JUMP_MODIFIER)
ent.__ppm2_modified_jump = true
GetLegsModifier: (mult = 0.4) =>
if @AllowResize()
1 + (@GetLegsSize() - 1) * mult
else
1
GetNeckModifier: (mult = 0.6) =>
if @AllowResize()
1 + (@GetNeckSize() - 1) * mult
else
1
ModifyViewOffset: (ent = @GetEntity()) =>
size = @GetPonySize()
necksize = 1 + (@GetNeckSize() - 1) * .3
legssize = @GetLegsModifier()
PLAYER_VIEW_OFFSET = Vector(PPM2.PLAYER_VIEW_OFFSET)
PLAYER_VIEW_OFFSET_DUCK = Vector(PPM2.PLAYER_VIEW_OFFSET_DUCK)
if @AllowResize()
PLAYER_VIEW_OFFSET *= size * necksize
PLAYER_VIEW_OFFSET_DUCK *= size * necksize
PLAYER_VIEW_OFFSET.z *= legssize
PLAYER_VIEW_OFFSET_DUCK.z *= legssize
ent\SetViewOffset(PLAYER_VIEW_OFFSET) if ent.SetViewOffset
ent\SetViewOffsetDucked(PLAYER_VIEW_OFFSET_DUCK) if ent.SetViewOffsetDucked
ModifyModelScale: (ent = @GetEntity()) =>
return if not @AllowResize()
-- https://github.com/Facepunch/garrysmod-issues/issues/2193
if SERVER
if not ent\IsPlayer()
newscale = (@GetPonySize() * 100)\floor() / 100
currscale = (ent\GetModelScale() * 100)\floor() / 100
if currscale ~= newscale
if type(ent) == 'NPC' or type(NPC) == 'NextBot'
ent\SetPreventTransmit(ply, true) for _, ply in ipairs player.GetAll()
ent\SetModelScale(newscale)
ent\SetPreventTransmit(ply, false) for _, ply in ipairs player.GetAll()
else
ent\SetModelScale(newscale)
return
--return if not ent\IsClientsideEntity()
return if ent.RenderOverride -- PAC3 and other stuff that can change this value
mat = Matrix()
mat\Scale(@@DEF_SCALE * @GetPonySize())
ent\EnableMatrix('RenderMultiply', mat)
ModifyScale: (ent = @GetEntity()) =>
return if not IsValid(ent)
return if not ent\IsPony()
return if ent.Alive and not ent\Alive()
if USE_NEW_HULL\GetBool()
@ModifyHull(ent)
@ModifyJumpHeight(ent)
@ModifyViewOffset(ent)
@ModifyModelScale(ent)
if CLIENT and @lastPAC3BoneReset < RealTimeL()
@ModifyNeck(ent)
@ModifyLegs(ent)
ModifyNeck: (ent = @GetEntity()) =>
return if not IsValid(ent)
return if not @AllowResize()
return if not @validSkeleton
size = (@GetNeckSize() - 1) * 3
return if size\abs() * 4 <= 0.05
vec = Vector(size, -size, 0)
boneAnimTable = ent.pac_boneanim and ent.pac_boneanim.positions or {}
emptyVector = Vector(0, 0, 0)
with ent
\ManipulateBonePosition(@NECK_BONE_1, vec + (boneAnimTable[@NECK_BONE_1] or emptyVector))
\ManipulateBonePosition(@NECK_BONE_2, vec + (boneAnimTable[@NECK_BONE_2] or emptyVector))
\ManipulateBonePosition(@NECK_BONE_3, vec + (boneAnimTable[@NECK_BONE_3] or emptyVector))
\ManipulateBonePosition(@NECK_BONE_4, vec + (boneAnimTable[@NECK_BONE_4] or emptyVector))
@LEGS_PONY_HEIGHT_MODIF = 3.8
@LEGS_BACK_MODIF = 2.5
@LEGS_BACK_MODIF2 = 0.5
@LEGS_BACK_MODIF_ = 1
@LEGS_BACK_MODIF_2 = 0.7
ModifyLegs: (ent = @GetEntity()) =>
return if not IsValid(ent)
return if not @AllowResize()
return if not @validSkeleton
realSizeModify = @GetLegsSize() - 1
return if realSizeModify\abs() * 4 <= 0.05
size = realSizeModify * 3
boneAnimTable = ent.pac_boneanim and ent.pac_boneanim.positions or {}
emptyVector = Vector(0, 0, 0)
with ent
\ManipulateBonePosition(@LEGS_BONE_ROOT, Vector(0, 0, size * @@LEGS_PONY_HEIGHT_MODIF) + \GetManipulateBonePosition(@LEGS_BONE_ROOT))
\ManipulateBonePosition(@LEGS_FRONT_1, Vector(size * 1.5, 0, 0) + (boneAnimTable[@LEGS_FRONT_1] or emptyVector))
\ManipulateBonePosition(@LEGS_FRONT_2, Vector(size * 1.5, 0, 0) + (boneAnimTable[@LEGS_FRONT_2] or emptyVector))
\ManipulateBonePosition(@LEGS_FRONT_3, Vector(size, 0, 0) + (boneAnimTable[@LEGS_FRONT_3] or emptyVector))
\ManipulateBonePosition(@LEGS_FRONT_4, Vector(size, 0, 0) + (boneAnimTable[@LEGS_FRONT_4] or emptyVector))
\ManipulateBonePosition(@LEGS_FRONT_5, Vector(size, size, 0) + (boneAnimTable[@LEGS_FRONT_5] or emptyVector))
\ManipulateBonePosition(@LEGS_FRONT_6, Vector(size, size, 0) + (boneAnimTable[@LEGS_FRONT_6] or emptyVector))
\ManipulateBonePosition(@LEGS_BEHIND_1_1, Vector(size * @@LEGS_BACK_MODIF_, -size * @@LEGS_BACK_MODIF_2, 0) + (boneAnimTable[@LEGS_BEHIND_1_1] or emptyVector))
\ManipulateBonePosition(@LEGS_BEHIND_1_2, Vector(size * @@LEGS_BACK_MODIF_, -size * @@LEGS_BACK_MODIF_2, 0) + (boneAnimTable[@LEGS_BEHIND_1_2] or emptyVector))
\ManipulateBonePosition(@LEGS_BEHIND_2_1, Vector(size * @@LEGS_BACK_MODIF, 0, 0) + (boneAnimTable[@LEGS_BEHIND_2_1] or emptyVector))
\ManipulateBonePosition(@LEGS_BEHIND_2_2, Vector(size * @@LEGS_BACK_MODIF, 0, 0) + (boneAnimTable[@LEGS_BEHIND_2_2] or emptyVector))
\ManipulateBonePosition(@LEGS_BEHIND_3_1, Vector(size * @@LEGS_BACK_MODIF2, 0, 0) + (boneAnimTable[@LEGS_BEHIND_3_1] or emptyVector))
\ManipulateBonePosition(@LEGS_BEHIND_3_2, Vector(size * @@LEGS_BACK_MODIF2, 0, 0) + (boneAnimTable[@LEGS_BEHIND_3_2] or emptyVector))
-- 0 LrigPelvis
-- 1 Lrig_LEG_BL_Femur
-- 2 Lrig_LEG_BL_Tibia
-- 3 Lrig_LEG_BL_LargeCannon
-- 4 Lrig_LEG_BL_PhalanxPrima
-- 5 Lrig_LEG_BL_RearHoof
-- 6 Lrig_LEG_BR_Femur
-- 7 Lrig_LEG_BR_Tibia
-- 8 Lrig_LEG_BR_LargeCannon
-- 9 Lrig_LEG_BR_PhalanxPrima
-- 10 Lrig_LEG_BR_RearHoof
-- 11 LrigSpine1
-- 12 LrigSpine2
-- 13 LrigRibcage
-- 14 Lrig_LEG_FL_Scapula
-- 15 Lrig_LEG_FL_Humerus
-- 16 Lrig_LEG_FL_Radius
-- 17 Lrig_LEG_FL_Metacarpus
-- 18 Lrig_LEG_FL_PhalangesManus
-- 19 Lrig_LEG_FL_FrontHoof
-- 20 Lrig_LEG_FR_Scapula
-- 21 Lrig_LEG_FR_Humerus
-- 22 Lrig_LEG_FR_Radius
-- 23 Lrig_LEG_FR_Metacarpus
-- 24 Lrig_LEG_FR_PhalangesManus
-- 25 Lrig_LEG_FR_FrontHoof
-- 26 LrigNeck1
-- 27 LrigNeck2
-- 28 LrigNeck3
-- 29 LrigScull
-- 30 Jaw
-- 31 Ear_L
-- 32 Ear_R
-- 33 Mane02
-- 34 Mane03
-- 35 Mane03_tip
-- 36 Mane04
-- 37 Mane05
-- 38 Mane06
-- 39 Mane07
-- 40 Mane01
-- 41 Lrigweaponbone
-- 42 right_hand
-- 43 wing_l
-- 44 wing_r
-- 45 Tail01
-- 46 Tail02
-- 47 Tail03
-- 48 wing_l_bat
-- 49 wing_r_bat
-- 50 wing_open_l
-- 51 wing_open_r
PPM2.PonySizeController = PonySizeController
class NewPonySizeContoller extends PonySizeController
@MODELS = {'models/ppm/player_default_base_new.mdl', 'models/ppm/player_default_base_new_nj.mdl'}
@NECK_BONE_1 = 'LrigNeck1'
@NECK_BONE_2 = 'LrigNeck2'
@NECK_BONE_3 = 'LrigNeck3'
@NECK_BONE_4 = 'LrigScull'
@LEGS_FRONT_1 = 'Lrig_LEG_FL_FrontHoof'
@LEGS_FRONT_2 = 'Lrig_LEG_FR_FrontHoof'
@LEGS_FRONT_3 = 'Lrig_LEG_FL_Metacarpus'
@LEGS_FRONT_4 = 'Lrig_LEG_FR_Metacarpus'
@LEGS_FRONT_5 = 'Lrig_LEG_FL_Radius'
@LEGS_FRONT_6 = 'Lrig_LEG_FR_Radius'
@LEGS_BEHIND_1_1 = 'Lrig_LEG_BL_Tibia'
@LEGS_BEHIND_1_2 = 'Lrig_LEG_BR_Tibia'
@LEGS_BEHIND_2_1 = 'Lrig_LEG_BL_PhalanxPrima'
@LEGS_BEHIND_2_2 = 'Lrig_LEG_BR_PhalanxPrima'
@LEGS_BEHIND_3_1 = 'Lrig_LEG_BL_LargeCannon'
@LEGS_BEHIND_3_2 = 'Lrig_LEG_BR_LargeCannon'
new: (...) =>
super(...)
PPM2.NewPonySizeContoller = NewPonySizeContoller
hook.Add 'PPM2.SetupBones', 'PPM2.Size', (ent, data) ->
if sizes = data\GetSizeController()
sizes.ent = ent
sizes\ModifyNeck()
sizes\ModifyLegs()
sizes.lastPAC3BoneReset = RealTimeL() + 1
ppm2_sv_allow_resize = ->
for _, ply in ipairs player.GetAll()
if data = ply\GetPonyData()
if scale = data\GetSizeController()
scale\Reset()
cvars.AddChangeCallback 'ppm2_sv_allow_resize', ppm2_sv_allow_resize, 'PPM2.Scale'
PPM2.GetSizeController = (model = 'models/ppm/player_default_base.mdl') -> PonySizeController.AVALIABLE_CONTROLLERS[model\lower()] or PonySizeController
| 31.926916 | 208 | 0.725978 |
f2401f976a4d547ee9871216b29dc35228fc1bfb | 7,072 |
util = require "lapis.util"
json = require "cjson"
tests = {
{
-> util.parse_query_string "field1=value1&field2=value2&field3=value3"
{
{"field1", "value1"}
{"field2", "value2"}
{"field3", "value3"}
field1: "value1"
field2: "value2"
field3: "value3"
}
}
{
-> util.parse_query_string "blahblah"
{
{ "blahblah"}
blahblah: true
}
}
{
-> util.parse_query_string "hello=wo%22rld&thing"
{
{ "hello", 'wo"rld' }
{ "thing" }
hello: 'wo"rld'
thing: true
}
}
{
-> util.parse_query_string "hello=&thing=123&world="
{
{"hello", ""}
{"thing", "123"}
{"world", ""}
hello: ""
thing: "123"
world: ""
}
}
{
-> util.underscore "ManifestRocks"
"manifest_rocks"
}
{
-> util.underscore "ABTestPlatform"
"abtest_platform"
}
{
-> util.underscore "HELLO_WORLD"
"" -- TODO: fix
}
{
-> util.underscore "whats_up"
"whats__up" -- TODO: fix
}
{
-> util.camelize "hello"
"Hello"
}
{
-> util.camelize "world_wide_i_web"
"WorldWideIWeb"
}
{
-> util.camelize util.underscore "ManifestRocks"
"ManifestRocks"
}
{
->
util.encode_query_string {
{"dad", "day"}
"hello[hole]": "wor=ld"
}
"dad=day&hello%5bhole%5d=wor%3dld"
}
{ -- stripping invalid types
->
json.decode util.to_json {
color: "blue"
data: {
height: 10
fn: =>
}
}
{
color: "blue", data: { height: 10}
}
}
{
->
util.build_url {
path: "/test"
scheme: "http"
host: "localhost.com"
port: "8080"
fragment: "cool_thing"
query: "dad=days"
}
"http://localhost.com:8080/test?dad=days#cool_thing"
}
{
-> util.time_ago os.time! - 34234349
{
{"years", 1}
{"days", 31}
{"hours", 5}
{"minutes", 32}
{"seconds", 29}
years: 1
days: 31
hours: 5
minutes: 32
seconds: 29
}
}
{
-> util.time_ago os.time! + 34234349
{
{"years", 1}
{"days", 31}
{"hours", 5}
{"minutes", 32}
{"seconds", 29}
years: 1
days: 31
hours: 5
minutes: 32
seconds: 29
}
}
{
-> util.time_ago_in_words os.time! - 34234349
"1 year ago"
}
{
-> util.time_ago_in_words os.time! - 34234349, 2
"1 year, 31 days ago"
}
{
-> util.time_ago_in_words os.time! - 34234349, 10
"1 year, 31 days, 5 hours, 32 minutes, 29 seconds ago"
}
{
-> util.time_ago_in_words os.time!
"0 seconds ago"
}
{
-> util.parse_cookie_string "__utma=54729783.634507326.1355638425.1366820216.1367111186.43; __utmc=54729783; __utmz=54729783.1364225235.36.12.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/Q95kO2iEje; __utma=163024063.1111023767.1355638932.1367297108.1367341173.42; __utmb=163024063.1.10.1367341173; __utmc=163024063; __utmz=163024063.1366693549.37.11.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/UYMGwvGJNo"
{
__utma: '163024063.1111023767.1355638932.1367297108.1367341173.42'
__utmz: '163024063.1366693549.37.11.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/UYMGwvGJNo'
__utmb: '163024063.1.10.1367341173'
__utmc: '163024063'
}
}
{
-> util.slugify "What is going on right now?"
"what-is-going-on-right-now"
}
{
-> util.slugify "whhaa $%#$ hooo"
"whhaa-hooo"
}
{
-> util.slugify "what-about-now"
"what-about-now"
}
{
-> util.slugify "hello - me"
"hello-me"
}
{
-> util.slugify "cow _ dogs"
"cow-dogs"
}
{
-> util.uniquify { "hello", "hello", "world", "another", "world" }
{ "hello", "world", "another" }
}
{
-> util.trim "what the heck"
"what the heck"
}
{
-> util.trim "
blah blah "
"blah blah"
}
{
-> util.trim_filter {
" ", " thing ",
yes: " "
okay: " no "
}
{ -- TODO: fix indexing?
nil, "thing", okay: "no"
}
}
{
-> util.trim_filter {
hello: " hi"
world: " hi"
yeah: " "
}, {"hello", "yeah"}, 0
{ hello: "hi", yeah: 0 }
}
{
->
util.key_filter {
hello: "world"
foo: "bar"
}, "hello", "yeah"
{ hello: "world" }
}
{
-> "^%()[12332]+$"\match(util.escape_pattern "^%()[12332]+$") and true
true
}
{
-> util.title_case "hello"
"Hello"
}
{
-> util.title_case "hello world"
"Hello World"
}
{
-> util.title_case "hello-world"
"Hello-world"
}
{
-> util.title_case "What my 200 Dollar thing You love to eat"
"What My 200 Dollar Thing You Love To Eat"
}
}
describe "lapis.util", ->
for group in *tests
it "should match", ->
input = group[1]!
if #group > 2
assert.one_of input, { unpack group, 2 }
else
assert.same input, group[2]
it "should autoload", ->
package.loaded["things.hello_world"] = "yeah"
package.loaded["things.cool_thing"] = "cool"
mod = util.autoload "things"
assert.equal "yeah", mod.HelloWorld
assert.equal "cool", mod.cool_thing
assert.equal nil, mod.not_here
assert.equal nil, mod.not_here
assert.equal "cool", mod.cool_thing
it "should autoload with starting table", ->
package.loaded["things.hello_world"] = "yeah"
package.loaded["things.cool_thing"] = "cool"
mod = util.autoload "things", { dad: "world" }
assert.equal "yeah", mod.HelloWorld
assert.equal "cool", mod.cool_thing
assert.equal "world", mod.dad
it "should autoload with multiple prefixes", ->
package.loaded["things.hello_world"] = "yeah"
package.loaded["things.cool_thing"] = "cool"
package.loaded["wings.cool_thing"] = "very cool"
package.loaded["wings.hats"] = "off to you"
mod = util.autoload "wings", "things"
assert.equal "off to you", mod.hats
assert.equal "very cool", mod.CoolThing
assert.equal "yeah", mod.hello_world
assert.equal "yeah", mod.HelloWorld
describe "lapis.util.mixin", ->
it "should mixin mixins", ->
import insert from table
log = {}
class Mixin
new: =>
insert log, "initializing Mixin"
@thing = { "hello" }
pop: =>
add_one: (num) =>
insert log, "Before add_one (Mixin), #{num}"
class Mixin2
new: =>
insert log, "initializing Mixin2"
add_one: (num) =>
insert log, "Before add_one (Mixin2), #{num}"
class One
util.mixin Mixin
util.mixin Mixin2
add_one: (num) =>
num + 1
new: =>
insert log, "initializing One"
o = One!
assert.equal 13, o\add_one(12)
assert.same {
"initializing One"
"initializing Mixin"
"initializing Mixin2"
"Before add_one (Mixin2), 12"
"Before add_one (Mixin), 12"
}, log
| 18.659631 | 430 | 0.541997 |
dd05edde27ecbcb5406921601634b69f7d635be8 | 1,096 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
Gtk = require 'ljglibs.gtk'
Pango = require 'ljglibs.pango'
class IndicatorBar
new: (cls) =>
error('Missing argument #1 (id)', 2) if not cls
@box = Gtk.Box {
height_request: 20
spacing: 10
}
@indics = {}
add: (position, id, widget) =>
pack = nil
switch position
when 'left'
pack = @box\pack_start
when 'right'
pack = @box\pack_end
else error 'Illegal indicator position "' .. position .. '"', 2
indicator = self._create_indicator id, widget
@indics[id] = indicator
pack indicator, false, false, 0
indicator
remove: (id) =>
indicator = @indics[id]
indicator\destroy! if indicator
to_gobject: => @box
_create_indicator: (id, widget) ->
widget or= Gtk.Label single_line_mode: true, ellipsize: Pango.ELLIPSIZE_MIDDLE
with widget.style_context
\add_class 'indic_default'
\add_class 'indic_' .. id
widget\show!
widget
return IndicatorBar
| 23.826087 | 82 | 0.643248 |
15e0f91cb5a9a48d61f24445007247a9205d2a17 | 710 | import print from _G
import APPLICATION_CORE_VERSION from "novacbn/gmodproj/lib/constants"
-- ::TEXT_COMMAND_VERSION -> string
-- Represents the current version of the application
-- export
export TEXT_COMMAND_VERSION = "#{APPLICATION_CORE_VERSION[1]}.#{APPLICATION_CORE_VERSION[2]}.#{APPLICATION_CORE_VERSION[3]} Pre-alpha"
-- ::formatDescription(table flags) -> string
-- Formats the help description of the command
-- export
export formatDescription = (flags) ->
return "version\t\t\t\t\tDisplays the version text of application"
-- ::executeCommand(table flags) -> void
-- Prints the version of the application to console
-- export
export executeCommand = (flags) ->
print(TEXT_COMMAND_VERSION) | 35.5 | 134 | 0.766197 |
04a5065b842d0dd2b995de0350e30e2fd259df16 | 1,514 | Dorothy!
SelectionItemView = require "View.Control.Basic.SelectionItem"
-- [params]
-- x, y, width, height, text
Class SelectionItemView,
__init:(args)=>
@_checked = false
@_text = @label.text
@label.texture.antiAlias = false
@slot "Tapped",-> @checked = not @checked
makeChecked:=>
@_checked = true
@border.visible = false
@opacity = 1
with @borderBold
.visible = true
.opacity = 1
.scaleX = 1
.scaleY = 1
checked:property => @_checked,
(value)=>
return if value == @_checked
@_checked = not @_checked
@border.visible = not value
if value then
@opacity = 1
with @borderBold
.visible = true
.opacity = 1
.scaleX = 0.8
.scaleY = 0.8
\perform @scale
else
@opacity = 0.6
@borderBold\runAction @fade
text:property => @_text,
(value)=>
@_text = value
@label.text = value
@label.texture.antiAlias = false
glow:=>
@cascadeOpacity = false
{:width,:height} = @
tile = with CCDrawNode()
.position = oVec2 width/2,height/2
.zOrder = -1
.opacity = 0
\drawPolygon {
oVec2 -width/2,height/2
oVec2 width/2,height/2
oVec2 width/2,-height/2
oVec2 -width/2,-height/2
},ccColor4(0x8800ffff),0.5,ccColor4(0xffffffff)
\runAction CCSequence {
CCRepeat (CCSequence {
oOpacity 0.1,1
oOpacity 0.1,0
}),2
CCCall ->
.parent\removeChild tile
@cascadeOpacity = true
}
@addChild tile
| 21.942029 | 63 | 0.593791 |
5a2957dfcef217c909a225a606f4d4583da2cb27 | 2,492 | import insert, remove, sort from table
import tointeger from math
import map, filter from require'opeth.common.utils'
local get_block
validly_insert = (t, v) ->
unless v.start and v.end
error "lack of block elements v.start: #{v.start}, v.end: #{v.end}"
if v.start > v.end
error "invalid block"
unless #(filter (=> @start == v.start and @.end == v.end), t) > 0
insert t, v
map tointeger, {v.start, v.end}
sort t, (a, b) -> a.end < b.start
-- shrink `blk` from `delimp` to `blk.end`,
-- and return new block `blk.start` to `delimp - 1`
split_block = (blk, delimp) ->
with newblk = {start: blk.start, end: delimp - 1, succ: {blk}, pred: blk.pred}
blk.start = delimp
blk.pred = {newblk}
mkcfg = (instruction) ->
blocks = {}
for ins_idx = 1, #instruction
singleblock = {start: ins_idx, end: ins_idx, succ: {}, pred: {}}
{RA, RB, RC, :op} = instruction[ins_idx]
singleblock.succ_pos = switch op
when JMP, FORPREP then {ins_idx + RB + 1}
when LOADBOOL then {ins_idx + 2} if RC == 1
when TESTSET, TEST, LT, LE, EQ then {ins_idx + 1, ins_idx + 2}
when FORLOOP, TFORLOOP then {ins_idx + 1, ins_idx + RB + 1}
when RETURN, TAILCALL then {}
validly_insert blocks, singleblock
blk_idx = 1
while blocks[blk_idx]
blk = blocks[blk_idx]
if blk.succ_pos
while #blk.succ_pos > 0
succ_pos = remove blk.succ_pos, 1
if blk_ = get_block instruction, succ_pos, blocks
if blk_.start < succ_pos
newblk = split_block blk_, succ_pos
validly_insert blocks, newblk
validly_insert blk_.pred, blk
validly_insert blk.succ, blk_
else
validly_insert blk_.pred, blk
validly_insert blk.succ, blk_
else
if #blk.succ_pos > 0
insert blk.succ_pos, succ_pos
else
error "cannot resolve succ_pos #{succ_pos} / ##{#instruction}"
blk.succ_pos = nil
elseif #blk.succ == 0
nextblock = blocks[blk_idx + 1]
if #nextblock.pred > 0
validly_insert nextblock.pred, blk
validly_insert blk.succ, nextblock
else
{:start, :pred} = blk
remove blocks, blk_idx
(for psucci = 1, #p.succ
if p.succ[psucci].start == start
remove p.succ, psucci
validly_insert p.succ, nextblock
break
) for p in *pred
nextblock.start = start
nextblock.pred = pred
continue
blk_idx += 1
blocks
get_block = (instruction, nth, blocks = mkcfg instruction) ->
return b for b in *blocks when ((b.start <= nth) and (b.end >= nth))
:get_block, :mkcfg
| 25.690722 | 79 | 0.648475 |
fcf251c9ea316e304b375cb56a6901b06df7e445 | 5,615 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import interact from howl
import Window from howl.ui
describe 'interact', ->
run_in_coroutine = (f) ->
wrapped = coroutine.wrap -> f!
return wrapped!
before_each ->
if howl.app.window
howl.app.window.command_line\abort_all!
howl.app.window = Window!
after_each ->
howl.app.window.command_line\abort_all!
howl.app.window = nil
describe '.register(spec)', ->
it 'raises an error if any of the mandatory fields are missing', ->
assert.raises 'name', -> interact.register description: 'foo', factory: -> true
assert.raises 'description', -> interact.register name: 'foo', factory: -> true
assert.raises 'factory', -> interact.register name: 'foo', description: 'foo'
it 'accepts one of "factory" or "handler"', ->
assert.raises 'factory', -> interact.register
name: 'foo'
description: 'foo'
factory: -> true
handler: -> true
it '.unregister(name) removes the specified input', ->
interact.register name: 'foo', description: 'foo', factory: -> true
interact.unregister 'foo'
assert.is_nil interact.foo
context 'calling an interaction .<name>(...)', ->
before_each ->
interact.register
name: 'interaction_call'
description: 'calls passed in function'
handler: (f) -> f!
interaction_instance =
run: (@finish, f) => f(finish)
interact.register
name: 'interaction_with_factory',
description: 'calls passed in function f(finish)'
factory: -> moon.copy interaction_instance
after_each ->
interact.unregister 'interaction_call'
interact.unregister 'interaction_with_factory'
context 'for a spec with .handler', ->
local i1_spec
before_each ->
i1_spec =
name: 'interaction1'
description: 'interaction with handler'
handler: spy.new -> return 'r1', 'r2'
interact.register i1_spec
after_each ->
interact.unregister i1_spec.name
it 'calls the interaction handler(...), returns result', ->
multi_value = table.pack interact.interaction1 'arg1', 'arg2'
assert.spy(i1_spec.handler).was_called_with 'arg1', 'arg2'
assert.is_same {'r1', 'r2', n:2}, multi_value
context 'for a spec with .factory', ->
local i2_spec, i2_interactor
before_each ->
i2_interactor =
run: spy.new (@finish, ...) => return
i2_spec =
name: 'interaction2'
description: 'interaction with factory'
factory: -> i2_interactor
interact.register i2_spec
after_each ->
interact.unregister i2_spec.name
it '.<name>(...) invokes the interaction method run(finish, ...)', ->
run_in_coroutine -> table.pack interact.interaction2 'arg1', 'arg2'
assert.spy(i2_interactor.run).was_called 1
it '.<name>(...) returns results passed via finish(...)', ->
multi_value = nil
run_in_coroutine -> multi_value = table.pack interact.interaction2!
i2_interactor.finish 'r1', 'r2'
assert.is_same {'r1', 'r2', n:2}, multi_value
context 'nested transactions', ->
it 'raises an error when attempting to finishing not active interaction', ->
local captured_finish
capture_finish = (finish) -> captured_finish = finish
run_in_coroutine -> interact.interaction_with_factory capture_finish
finish1 = captured_finish
finish1!
assert.has_error finish1, 'Cannot finish - no running activities'
it 'allows cancelling outer interactions, when nested interactions present', ->
local captured_finish
capture_finish = (finish) -> captured_finish = finish
run_in_coroutine -> interact.interaction_with_factory capture_finish
run_in_coroutine -> interact.interaction_with_factory capture_finish
finish2 = captured_finish
assert.has_no_error finish2
describe 'sequence()', ->
it 'runs specified functions in serial, returns table containing all results', ->
calls = {}
local result
run_in_coroutine ->
result = interact.sequence {'first', 'second', 'third'},
first: ->
table.insert calls, 'first'
'first-result'
second: ->
table.insert calls, 'second'
'second-result'
third: ->
table.insert calls, 'third'
'third-result'
assert.same {'first', 'second', 'third'}, calls
assert.same 'first-result', result.first
assert.same 'second-result', result.second
assert.same 'third-result', result.third
it 'a function returning nil cancels the entire interaction', ->
calls = {}
local result
run_in_coroutine ->
result = interact.sequence {'first', 'second', 'third'},
first: ->
table.insert calls, 'first'
'first-result'
second: ->
table.insert calls, 'second'
nil
third: ->
table.insert calls, 'third'
'third-result'
assert.same {'first', 'second'}, calls
assert.same nil, result
it 'calls `finish`, if present, on the final result and returns that', ->
local result
run_in_coroutine ->
result = interact.sequence {'first'},
first: -> 'first-result'
finish: (r) -> 'finish ' .. r.first
assert.same 'finish first-result', result
| 34.237805 | 85 | 0.620837 |
30ffdb3f7eba6ee968dec35b6dab37da637fc032 | 326 | M = {}
-- execute the function with the same name as the inclosing module
M.self = (target_module) ->
for name, test in pairs(target_module)
print string.format "ERROR HINT: %s() doesn't exist", name if test[name]== nil
result = test[name]()
return false if result == false
return true
return M | 36.222222 | 86 | 0.653374 |
75ed1ddb65144ddac9a8942d5680744ad0449091 | 20,586 | socket = require "pgmoon.socket"
import insert from table
import rshift, lshift, band, bxor from require "pgmoon.bit"
unpack = table.unpack or unpack
-- Protocol documentation:
-- https://www.postgresql.org/docs/current/protocol-message-formats.html
VERSION = "1.13.0"
_len = (thing, t=type(thing)) ->
switch t
when "string"
#thing
when "table"
l = 0
for inner in *thing
inner_t = type inner
if inner_t == "string"
l += #inner
else
l += _len inner, inner_t
l
else
error "don't know how to calculate length of #{t}"
_debug_msg = (str) ->
require("moon").dump [p for p in str\gmatch "[^%z]+"]
flipped = (t) ->
keys = [k for k in pairs t]
for key in *keys
t[t[key]] = key
t
MSG_TYPE = flipped {
status: "S"
auth: "R"
backend_key: "K"
ready_for_query: "Z"
query: "Q"
notice: "N"
notification: "A"
password: "p"
row_description: "T"
data_row: "D"
command_complete: "C"
error: "E"
}
ERROR_TYPES = flipped {
severity: "S"
code: "C"
message: "M"
position: "P"
detail: "D"
schema: "s"
table: "t"
constraint: "n"
}
PG_TYPES = {
[16]: "boolean"
[17]: "bytea"
[20]: "number" -- int8
[21]: "number" -- int2
[23]: "number" -- int4
[700]: "number" -- float4
[701]: "number" -- float8
[1700]: "number" -- numeric
[114]: "json" -- json
[3802]: "json" -- jsonb
-- arrays
[1000]: "array_boolean" -- bool array
[1005]: "array_number" -- int2 array
[1007]: "array_number" -- int4 array
[1016]: "array_number" -- int8 array
[1021]: "array_number" -- float4 array
[1022]: "array_number" -- float8 array
[1231]: "array_number" -- numeric array
[1009]: "array_string" -- text array
[1015]: "array_string" -- varchar array
[1002]: "array_string" -- char array
[1014]: "array_string" -- bpchar array
[2951]: "array_string" -- uuid array
[199]: "array_json" -- json array
[3807]: "array_json" -- jsonb array
}
NULL = "\0"
tobool = (str) ->
str == "t"
class Postgres
convert_null: false
NULL: {"NULL"}
:PG_TYPES
default_config: {
application_name: "pgmoon"
user: "postgres"
host: "127.0.0.1"
port: "5432"
ssl: false
}
-- custom types supplementing PG_TYPES
type_deserializers: {
json: (val, name) =>
import decode_json from require "pgmoon.json"
decode_json val
bytea: (val, name) =>
@decode_bytea val
array_boolean: (val, name) =>
import decode_array from require "pgmoon.arrays"
decode_array val, tobool
array_number: (val, name) =>
import decode_array from require "pgmoon.arrays"
decode_array val, tonumber
array_string: (val, name) =>
import decode_array from require "pgmoon.arrays"
decode_array val
array_json: (val, name) =>
import decode_array from require "pgmoon.arrays"
import decode_json from require "pgmoon.json"
decode_array val, decode_json
hstore: (val, name) =>
import decode_hstore from require "pgmoon.hstore"
decode_hstore val
}
set_type_oid: (oid, name) =>
unless rawget(@, "PG_TYPES")
@PG_TYPES = {k,v for k,v in pairs @PG_TYPES}
@PG_TYPES[assert tonumber oid] = name
setup_hstore: =>
res = unpack @query "SELECT oid FROM pg_type WHERE typname = 'hstore'"
assert res, "hstore oid not found"
@set_type_oid tonumber(res.oid), "hstore"
-- config={}
-- host: server hostname
-- port: server port
-- user: the username to authenticate with
-- password: the username to authenticate with
-- database: database to connect to
-- application_name: name assigned to connection to server
-- socket_type: type of socket to use (nginx, luasocket, cqueues)
-- ssl: enable ssl connections
-- ssl_verify: verify the certificate
-- cqueues_openssl_context: manually created openssl.ssl.context for cqueues sockets
-- luasec_opts: manually created options for LuaSocket ssl connections
new: (@config={}) =>
assert not getmetatable(@config),
"options argument must not have a metatable to allow default configuration to be inherited"
setmetatable @config, __index: @default_config
@sock, @sock_type = socket.new @config.socket_type
connect: =>
unless @sock
@sock = socket.new @sock_type
connect_opts = switch @sock_type
when "nginx"
{
pool: @config.pool_name or "#{@config.host}:#{@config.port}:#{@config.database}:#{@config.user}"
pool_size: @config.pool_size
backlog: @config.backlog
}
ok, err = @sock\connect @config.host, @config.port, connect_opts
return nil, err unless ok
if @sock\getreusedtimes! == 0
if @config.ssl
success, err = @send_ssl_message!
return nil, err unless success
success, err = @send_startup_message!
return nil, err unless success
success, err = @auth!
return nil, err unless success
success, err = @wait_until_ready!
return nil, err unless success
true
settimeout: (...) =>
@sock\settimeout ...
disconnect: =>
sock = @sock
@sock = nil
sock\close!
keepalive: (...) =>
sock = @sock
@sock = nil
sock\setkeepalive ...
-- see: http://25thandclement.com/~william/projects/luaossl.pdf
create_cqueues_openssl_context: =>
return unless @config.ssl_verify != nil or @config.cert or @config.key or @config.ssl_version
ssl_context = require("openssl.ssl.context")
out = ssl_context.new @config.ssl_version
if @config.ssl_verify == true
out\setVerify ssl_context.VERIFY_PEER
if @config.ssl_verify == false
out\setVerify ssl_context.VERIFY_NONE
if @config.cert
out\setCertificate @config.cert
if @config.key
out\setPrivateKey @config.key
out
create_luasec_opts: =>
{
key: @config.key
certificate: @config.cert
cafile: @config.cafile
protocol: @config.ssl_version
verify: @config.ssl_verify and "peer" or "none"
}
auth: =>
t, msg = @receive_message!
return nil, msg unless t
unless MSG_TYPE.auth == t
@disconnect!
if MSG_TYPE.error == t
return nil, @parse_error msg
error "unexpected message during auth: #{t}"
auth_type = @decode_int msg, 4
switch auth_type
when 0 -- trust
true
when 3 -- cleartext password
@cleartext_auth msg
when 5 -- md5 password
@md5_auth msg
when 10 -- AuthenticationSASL
@scram_sha_256_auth msg
else
error "don't know how to auth: #{auth_type}"
cleartext_auth: (msg) =>
assert @config.password, "missing password, required for connect"
@send_message MSG_TYPE.password, {
@config.password
NULL
}
@check_auth!
-- https://www.postgresql.org/docs/current/sasl-authentication.html#SASL-SCRAM-SHA-256
scram_sha_256_auth: (msg) =>
assert @config.password, "missing password, required for connect"
openssl_rand = require "openssl.rand"
-- '18' is the number set by postgres on the server side
rand_bytes = assert openssl_rand.bytes 18
import encode_base64 from require "pgmoon.util"
c_nonce = encode_base64 rand_bytes
nonce = "r=" .. c_nonce
saslname = ""
username = "n=" .. saslname
client_first_message_bare = username .. "," .. nonce
plus = false
bare = false
if msg\match "SCRAM%-SHA%-256%-PLUS"
plus = true
elseif msg\match "SCRAM%-SHA%-256"
bare = true
else
error "unsupported SCRAM mechanism name: " .. tostring(msg)
local gs2_cbind_flag
local gs2_header
local cbind_input
local mechanism_name
if bare
gs2_cbind_flag = "n"
gs2_header = gs2_cbind_flag .. ",,"
cbind_input = gs2_header
mechanism_name = "SCRAM-SHA-256" .. NULL
elseif plus
cb_name = "tls-server-end-point"
gs2_cbind_flag = "p=" .. cb_name
gs2_header = gs2_cbind_flag .. ",,"
mechanism_name = "SCRAM-SHA-256-PLUS" .. NULL
cbind_data = do
if @sock_type == "cqueues"
openssl_x509 = @sock\getpeercertificate!
openssl_x509\digest "sha256", "s"
else
pem, signature = if @sock_type == "nginx"
ssl = require("resty.openssl.ssl").from_socket(@sock)
server_cert = ssl\get_peer_certificate()
server_cert\to_PEM!, server_cert\get_signature_name!
else
server_cert = @sock\getpeercertificate()
server_cert\pem!, server_cert\getsignaturename!
signature = signature\lower!
-- upgrade the signature if necessary
if signature\match("^md5") or signature\match("^sha1")
signature = "sha256"
openssl_x509 = require("openssl.x509").new(pem, "PEM")
assert openssl_x509\digest(signature, "s")
cbind_input = gs2_header .. cbind_data
client_first_message = gs2_header .. client_first_message_bare
@send_message MSG_TYPE.password, {
mechanism_name
@encode_int #client_first_message
client_first_message
}
t, msg = @receive_message()
unless t
return nil, msg
server_first_message = msg\sub 5
int32 = @decode_int msg, 4
if int32 == nil or int32 != 11
return nil, "server_first_message error: " .. msg
channel_binding = "c=" .. encode_base64 cbind_input
nonce = server_first_message\match "([^,]+)"
unless nonce
return nil, "malformed server message (nonce)"
client_final_message_without_proof = channel_binding .. "," .. nonce
xor = (a, b) ->
result = for i=1,#a
x = a\byte i
y = b\byte i
unless x and y
return nil
string.char bxor x, y
table.concat result
salt = server_first_message\match ",s=([^,]+)"
unless salt
return nil, "malformed server message (salt)"
i = server_first_message\match ",i=(.+)"
unless i
return nil, "malformed server message (iteraton count)"
if tonumber(i) < 4096
return nil, "the iteration-count sent by the server is less than 4096"
import kdf_derive_sha256, hmac_sha256, digest_sha256 from require "pgmoon.crypto"
salted_password, err = kdf_derive_sha256 @config.password, salt, tonumber i
unless salted_password
return nil, err
client_key, err = hmac_sha256 salted_password, "Client Key"
unless client_key
return nil, err
stored_key, err = digest_sha256 client_key
unless stored_key
return nil, err
auth_message = "#{client_first_message_bare },#{server_first_message },#{client_final_message_without_proof}"
client_signature, err = hmac_sha256 stored_key, auth_message
unless client_signature
return nil, err
proof = xor client_key, client_signature
unless proof
return nil, "failed to generate the client proof"
client_final_message = "#{client_final_message_without_proof },p=#{encode_base64 proof}"
@send_message MSG_TYPE.password, {
client_final_message
}
t, msg = @receive_message()
unless t
return nil, msg
server_key, err = hmac_sha256 salted_password, "Server Key"
unless server_key
return nil, err
server_signature, err = hmac_sha256 server_key, auth_message
unless server_signature
return nil, err
server_signature = encode_base64 server_signature
sent_server_signature = msg\match "v=([^,]+)"
if server_signature != sent_server_signature then
return nil, "authentication exchange unsuccessful"
@check_auth!
md5_auth: (msg) =>
import md5 from require "pgmoon.crypto"
salt = msg\sub 5, 8
assert @config.password, "missing password, required for connect"
@send_message MSG_TYPE.password, {
"md5"
md5 md5(@config.password .. @config.user) .. salt
NULL
}
@check_auth!
check_auth: =>
t, msg = @receive_message!
return nil, msg unless t
switch t
when MSG_TYPE.error
nil, @parse_error msg
when MSG_TYPE.auth
true
else
error "unknown response from auth"
query: (q) =>
if q\find NULL
return nil, "invalid null byte in query"
@post q
local row_desc, data_rows, command_complete, err_msg
local result, notifications
num_queries = 0
while true
t, msg = @receive_message!
return nil, msg unless t
switch t
when MSG_TYPE.data_row
data_rows or= {}
insert data_rows, msg
when MSG_TYPE.row_description
row_desc = msg
when MSG_TYPE.error
err_msg = msg
when MSG_TYPE.command_complete
command_complete = msg
next_result = @format_query_result row_desc, data_rows, command_complete
num_queries += 1
if num_queries == 1
result = next_result
elseif num_queries == 2
result = { result, next_result }
else
insert result, next_result
row_desc, data_rows, command_complete = nil
when MSG_TYPE.ready_for_query
break
when MSG_TYPE.notification
notifications = {} unless notifications
insert notifications, @parse_notification(msg)
-- when MSG_TYPE.notice
-- TODO: do something with notices
if err_msg
return nil, @parse_error(err_msg), result, num_queries, notifications
result, num_queries, notifications
post: (q) =>
@send_message MSG_TYPE.query, {q, NULL}
wait_for_notification: =>
while true
t, msg = @receive_message!
return nil, msg unless t
switch t
when MSG_TYPE.notification
return @parse_notification(msg)
format_query_result: (row_desc, data_rows, command_complete) =>
local command, affected_rows
if command_complete
command = command_complete\match "^%w+"
affected_rows = tonumber command_complete\match "(%d+)%z$"
if row_desc
return {} unless data_rows
fields = @parse_row_desc row_desc
num_rows = #data_rows
for i=1,num_rows
data_rows[i] = @parse_data_row data_rows[i], fields
if affected_rows and command != "SELECT"
data_rows.affected_rows = affected_rows
return data_rows
if affected_rows
{ :affected_rows }
else
true
parse_error: (err_msg) =>
local severity, message, detail, position
error_data = {}
offset = 1
while offset <= #err_msg
t = err_msg\sub offset, offset
str = err_msg\match "[^%z]+", offset + 1
break unless str
offset += 2 + #str
if field = ERROR_TYPES[t]
error_data[field] = str
switch t
when ERROR_TYPES.severity
severity = str
when ERROR_TYPES.message
message = str
when ERROR_TYPES.position
position = str
when ERROR_TYPES.detail
detail = str
msg = "#{severity}: #{message}"
if position
msg = "#{msg} (#{position})"
if detail
msg = "#{msg}\n#{detail}"
msg, error_data
parse_row_desc: (row_desc) =>
num_fields = @decode_int row_desc\sub(1,2)
offset = 3
fields = for i=1,num_fields
name = row_desc\match "[^%z]+", offset
offset += #name + 1
-- 4: object id of table
-- 2: attribute number of column (4)
-- 4: object id of data type (6)
data_type = @decode_int row_desc\sub offset + 6, offset + 6 + 3
data_type = @PG_TYPES[data_type] or "string"
-- 2: data type size (10)
-- 4: type modifier (12)
-- 2: format code (16)
-- we only know how to handle text
format = @decode_int row_desc\sub offset + 16, offset + 16 + 1
assert 0 == format, "don't know how to handle format"
offset += 18
{name, data_type}
fields
parse_data_row: (data_row, fields) =>
-- 2: number of values
num_fields = @decode_int data_row\sub(1,2)
out = {}
offset = 3
for i=1,num_fields
field = fields[i]
continue unless field
{field_name, field_type} = field
-- 4: length of value
len = @decode_int data_row\sub offset, offset + 3
offset += 4
if len < 0
out[field_name] = @NULL if @convert_null
continue
value = data_row\sub offset, offset + len - 1
offset += len
switch field_type
when "number"
value = tonumber value
when "boolean"
value = value == "t"
when "string"
nil
else
if fn = @type_deserializers[field_type]
value = fn @, value, field_type
out[field_name] = value
out
parse_notification: (msg) =>
pid = @decode_int msg\sub 1, 4
offset = 4
channel, payload = msg\match "^([^%z]+)%z([^%z]*)%z$", offset + 1
unless channel
error "parse_notification: failed to parse notification"
{
operation: "notification"
pid: pid
channel: channel
payload: payload
}
wait_until_ready: =>
while true
t, msg = @receive_message!
return nil, msg unless t
if MSG_TYPE.error == t
@disconnect!
return nil, @parse_error(msg)
break if MSG_TYPE.ready_for_query == t
true
receive_message: =>
t, err = @sock\receive 1
unless t
@disconnect!
return nil, "receive_message: failed to get type: #{err}"
len, err = @sock\receive 4
unless len
@disconnect!
return nil, "receive_message: failed to get len: #{err}"
len = @decode_int len
len -= 4
msg = @sock\receive len
t, msg
send_startup_message: =>
assert @config.user, "missing user for connect"
assert @config.database, "missing database for connect"
data = {
@encode_int 196608
"user", NULL
@config.user, NULL
"database", NULL
@config.database, NULL
"application_name", NULL
@config.application_name, NULL
NULL
}
@sock\send {
@encode_int _len(data) + 4
data
}
send_ssl_message: =>
success, err = @sock\send {
@encode_int 8,
@encode_int 80877103
}
return nil, err unless success
t, err = @sock\receive 1
return nil, err unless t
if t == MSG_TYPE.status
switch @sock_type
when "nginx"
@sock\sslhandshake false, nil, @config.ssl_verify
when "luasocket"
@sock\sslhandshake @config.luasec_opts or @create_luasec_opts!
when "cqueues"
@sock\starttls @config.cqueues_openssl_context or @create_cqueues_openssl_context!
else
error "don't know how to do ssl handshake for socket type: #{@sock_type}"
elseif t == MSG_TYPE.error or @config.ssl_required
@disconnect!
nil, "the server does not support SSL connections"
else
true -- no SSL support, but not required by client
send_message: (t, data, len) =>
len = _len data if len == nil
len += 4 -- includes the length of the length integer
@sock\send {
t
@encode_int len
data
}
decode_int: (str, bytes=#str) =>
switch bytes
when 4
d, c, b, a = str\byte 1, 4
a + lshift(b, 8) + lshift(c, 16) + lshift(d, 24)
when 2
b, a = str\byte 1, 2
a + lshift(b, 8)
else
error "don't know how to decode #{bytes} byte(s)"
-- create big endian binary string of number
encode_int: (n, bytes=4) =>
switch bytes
when 4
a = band n, 0xff
b = band rshift(n, 8), 0xff
c = band rshift(n, 16), 0xff
d = band rshift(n, 24), 0xff
string.char d, c, b, a
else
error "don't know how to encode #{bytes} byte(s)"
decode_bytea: (str) =>
if str\sub(1, 2) == '\\x'
str\sub(3)\gsub '..', (hex) ->
string.char tonumber hex, 16
else
str\gsub '\\(%d%d%d)', (oct) ->
string.char tonumber oct, 8
encode_bytea: (str) =>
string.format "E'\\\\x%s'", str\gsub '.', (byte) ->
string.format '%02x', string.byte byte
escape_identifier: (ident) =>
'"' .. (tostring(ident)\gsub '"', '""') .. '"'
escape_literal: (val) =>
switch type val
when "number"
return tostring val
when "string"
return "'#{(val\gsub "'", "''")}'"
when "boolean"
return val and "TRUE" or "FALSE"
error "don't know how to escape value: #{val}"
__tostring: =>
"<Postgres socket: #{@sock}>"
{ :Postgres, new: Postgres, :VERSION }
| 24.683453 | 113 | 0.616195 |
e206f61b3656bf1b74f86ef36adf444b6df64d33 | 2,029 |
luasocket = do
import flatten from require "pgmoon.util"
proxy_mt = {
__index: (key) =>
sock = @sock
original = sock[key]
if type(original) == "function"
fn = (_, ...) ->
original sock, ...
@[key] = fn
fn
else
original
}
overrides = {
send: true
getreusedtimes: true
sslhandshake: true,
settimeout: true
}
{
tcp: (...) ->
socket = require "socket"
sock = socket.tcp ...
proxy = setmetatable {
:sock
send: (...) => @sock\send flatten ...
getreusedtimes: => 0
settimeout: (t) =>
if t
t = t/1000
@sock\settimeout t
sslhandshake: (verify, opts={}) =>
ssl = require "ssl"
params = {
mode: "client"
protocol: opts.ssl_version or "any"
key: opts.key
certificate: opts.cert
cafile: opts.cafile
verify: verify and "peer" or "none"
options: { "all", "no_sslv2", "no_sslv3", "no_tlsv1" }
}
sec_sock, err = ssl.wrap @sock, params
return false, err unless sec_sock
success, err = sec_sock\dohandshake!
return false, err unless success
-- purge memoized socket closures
for k, v in pairs @
@[k] = nil unless type(v) ~= "function" or overrides[k]
@sock = sec_sock
true
}, proxy_mt
proxy
}
{
new: (socket_type) ->
if socket_type == nil
-- choose the default socket, try to use nginx, otherwise default to
-- luasocket
socket_type = if ngx and ngx.get_phase! != "init"
"nginx"
else
"luasocket"
socket = switch socket_type
when "nginx"
ngx.socket.tcp!
when "luasocket"
luasocket.tcp!
when "cqueues"
require("pgmoon.cqueues").CqueuesSocket!
else
error "unknown socket type: #{socket_type}"
socket, socket_type
}
| 22.544444 | 74 | 0.513553 |
134cf04322b2638c88d2499cddf9b8c7586ccb26 | 10,613 | api = vim.api
loop = vim.loop
Utils = require'neotags/utils'
class Neotags
new: (opts) =>
@opts = {
enable: true,
ft_conv: {
['c++']: 'cpp',
['moonscript']: 'moon',
['c#']: 'cs',
},
ft_map: {
cpp: { 'cpp', 'c' },
c: { 'c', 'cpp' },
},
hl: {
patternlength: 2048,
prefix: [[\C\<]],
suffix: [[\>]],
},
tools: {
find: nil,
},
ctags: {
run: true,
directory: vim.fn.expand('~/.vim_tags'),
verbose: false,
binary: 'ctags'
args: {
'--fields=+l',
'--c-kinds=+p',
'--c++-kinds=+p',
'--sort=no',
'-a',
},
},
ignore: {
'cfg',
'conf',
'help',
'mail',
'markdown',
'nerdtree',
'nofile',
'readdir',
'qf',
'text',
'plaintext'
},
notin: {
'.*String.*',
'.*Comment.*',
'cIncluded',
'cCppOut2',
'cCppInElse2',
'cCppOutIf2',
'pythonDocTest',
'pythonDocTest2',
}
}
@languages = {}
@syntax_groups = {}
@ctags_handle = nil
@find_handle = nil
setup: (opts) =>
@opts = vim.tbl_deep_extend('force', @opts, opts) if opts
return if not @opts.enable
vim.api.nvim_create_augroup('NeotagsLua', { clear: true })
vim.api.nvim_create_autocmd(
{ 'FileType', 'User NeotagsCtagsComplete' }
{
group: 'NeotagsLua',
pattern: '*',
callback: () -> require'neotags'.highlight()
}
)
vim.api.nvim_create_autocmd(
'BufWritePost',
{
group: 'NeotagsLua',
pattern: '*',
callback: () -> require'neotags'.update()
}
)
@run('highlight')
currentTagfile: () =>
path = vim.fn.getcwd()
path = path\gsub('[%.%/]', '__')
return "#{@opts.ctags.directory}/#{path}.tags"
runCtags: (files) =>
return if @ctags_handle
tagfile = @currentTagfile()
args = @opts.ctags.args
args = Utils.concat(args, { '-f', tagfile })
args = Utils.concat(args, files)
stderr = loop.new_pipe(false) if @opts.ctags.verbose
stdout = loop.new_pipe(false)
@ctags_handle = loop.spawn(
@opts.ctags.binary, {
args: args,
cwd: vim.fn.getcwd(),
stdio: {nil, stdout, stderr},
},
vim.schedule_wrap(() ->
stdout\read_stop()
stdout\close()
if @opts.ctags.verbose
stderr\read_stop()
stderr\close()
@ctags_handle\close()
vim.bo.tags = tagfile
vim.cmd("doautocmd User NeotagsCtagsComplete")
@ctags_handle = nil
)
)
loop.read_start(stdout, (err, data) -> print(data) if data)
if @opts.ctags.verbose
loop.read_start(stderr, (err, data) -> print(data) if data)
update: () =>
return if not @opts.enable
@findFiles((files) -> @runCtags(files))
findFiles: (callback) =>
path = vim.fn.getcwd()
return callback({ '-R', path }) if not @opts.tools.find
return if @find_handle
stdout = loop.new_pipe(false)
stderr = loop.new_pipe(false)
files = {}
args = Utils.concat(@opts.tools.find.args, { path })
@find_handle = loop.spawn(
@opts.tools.find.binary, {
args: args,
cwd: path,
stdio: {nil, stdout, stderr},
},
vim.schedule_wrap(() ->
stdout\read_stop()
stdout\close()
stderr\read_stop()
stderr\close()
@find_handle\close()
@find_handle = nil
callback(files)
)
)
loop.read_start(stdout, (err, data) ->
return unless data
for _, file in ipairs(Utils.explode('\n', data))
table.insert(files, file)
)
loop.read_start(stderr, (err, data) -> print data if data)
run: (func) =>
co = nil
switch func
when 'highlight'
tagfile = @currentTagfile()
if vim.fn.filereadable(tagfile) == 0
@update()
elseif vim.bo.tags != tagfile
vim.bo.tags = tagfile
co = coroutine.create(() -> @highlight())
when 'clear'
co = coroutine.create(() -> @clearsyntax())
return if not co
while true do
_, cmd = coroutine.resume(co)
-- vim.cmd("echo '#{cmd}'")
vim.cmd(cmd) if cmd
break if coroutine.status(co) == 'dead'
toggle: () =>
@opts.enable = not @opts.enable
@setup() if @opts.enable
@run('clear') if not @opts.enable
language: (lang, opts) =>
@languages[lang] = opts
clearsyntax: () =>
vim.cmd[[
augroup NeotagsLua
autocmd!
augroup END
]]
for _, hl in pairs(@syntax_groups)
coroutine.yield("silent! syntax clear #{hl}")
@syntax_groups = {}
makesyntax: (lang, kind, group, opts, content, added) =>
hl = "_Neotags_#{lang}_#{kind}_#{opts.group}"
matches = {}
keywords = {}
prefix = opts.prefix or @opts.hl.prefix
suffix = opts.suffix or @opts.hl.suffix
forbidden = {
'*',
}
for tag in *group
continue if Utils.contains(added, tag.name)
continue if Utils.contains(forbidden, tag.name)
if not content\find(tag.name)
table.insert(added, tag.name)
continue
if (prefix == @opts.hl.prefix and suffix == @opts.hl.suffix and
opts.allow_keyword != false and not tag.name\match('%.') and
not tag.name == 'contains' and not opt.notin)
table.insert(keywords, tag.name) if not Utils.contains(keywords, tag.name)
else
table.insert(matches, tag.name) if not Utils.contains(matches, tag.name)
table.insert(added, tag.name)
coroutine.yield("silent! syntax clear #{hl}")
coroutine.yield("hi def link #{hl} #{opts.group}")
table.sort(matches, (a, b) -> a < b)
merged = {}
if opts.extended_notin and opts.extend_notin == false
merged = opts.notin or @opts.notin or {}
else
a = @opts.notin or {}
b = opts.notin or {}
max = (#a > #b) and #a or #b
for i=1,max
merged[#merged+1] = a[i] if a[i]
merged[#merged+1] = b[i] if b[i]
notin = ''
notin = "containedin=ALLBUT,#{table.concat(merged, ',')}" if #merged > 0
for i = 1, #matches, @opts.hl.patternlength
current = {unpack(matches, i, i + @opts.hl.patternlength)}
str = table.concat(current, '\\|')
coroutine.yield("syntax match #{hl} /#{prefix}\\%(#{str}\\)#{suffix}/ #{notin} display")
table.sort(keywords, (a, b) -> a < b)
for i = 1, #keywords, @opts.hl.patternlength
current = {unpack(keywords, i, i + @opts.hl.patternlength)}
str = table.concat(current, ' ')
coroutine.yield("syntax keyword #{hl} #{str}")
table.insert(@syntax_groups, hl)
highlight: () =>
ft = vim.bo.filetype
return if #ft == 0 or Utils.contains(@opts.ignore, ft)
bufnr = api.nvim_get_current_buf()
content = table.concat(api.nvim_buf_get_lines(bufnr, 0, -1, false), '\n')
tags = vim.fn.taglist('.*')
groups = {}
for tag in *tags
continue if not tag.language
continue if tag.name\match('^[a-zA-Z]{,2}$')
continue if tag.name\match('^[0-9]+$')
continue if tag.name\match('^__anon.*$')
tag.language = tag.language\lower()
tag.language = @opts.ft_conv[tag.language] if @opts.ft_conv[tag.language]
if @opts.ft_map[ft] and not Utils.contains(@opts.ft_map[ft], tag.language)
continue
if not @opts.ft_map[ft] and not ft == tag.language
continue
-- if tag.language == 'vim'
-- print require'lsp'.format_as_json(tag)
groups[tag.language] = {} if not groups[tag.language]
groups[tag.language][tag.kind] = {} if not groups[tag.language][tag.kind]
table.insert(groups[tag.language][tag.kind], tag)
langmap = @opts.ft_map[ft] or {ft}
for _, lang in pairs(langmap)
continue if not @languages[lang] or not @languages[lang].order
cl = @languages[lang]
order = cl.order
added = {}
kinds = groups[lang]
continue if not kinds
for i = 1, #order
kind = order\sub(i, i)
continue if not kinds[kind]
continue if not cl.kinds or not cl.kinds[kind]
-- print "adding #{kinds[kind]} for #{lang} in #{kind}"
@makesyntax(lang, kind, kinds[kind], cl.kinds[kind], content, added)
export neotags = Neotags! if not neotags
return {
setup: (opts) ->
path = debug.getinfo(1).source\match('@?(.*/)')
for filename in io.popen("ls #{path}/languages")\lines()
lang = filename\gsub('%.lua$', '')
neotags.language(neotags, lang, require"neotags/languages/#{lang}")
neotags.setup(neotags, opts)
highlight: () -> neotags.run(neotags, 'highlight')
update: () -> neotags.update(neotags)
toggle: () -> neotags.toggle(neotags)
language: (lang, opts) -> neotags.language(neotags, lang, opts)
}
| 30.322857 | 100 | 0.467634 |
c5a641391600c4eb08516c0d4a1e442bfb7044f7 | 1,542 | {graphics: g} = love
class WaterParticle extends PixelParticle
life: 0.4
new: (...) =>
super ...
color = C.water
color = pick_one C.water, C.water_light
@r,@g,@b = unpack color
@size = pick_one 2,3,4,5
@vel = Vec2d 0, 20
@accel = Vec2d 0, 50
draw: =>
g.push!
g.translate @x, @y
s = pop_in @p!, 0.1, 2
g.scale s, s
g.translate -@x, -@y
super!
g.pop!
class DirtParticle extends PixelParticle
life: 0.4
new: (...) =>
super ...
color = pick_one C.skin, C.dirt_darker
@r,@g,@b = unpack color
@size = pick_one 2,3,4,5
@vel = Vec2d(0, -100)\random_heading!
@accel = Vec2d 0, 300
draw: =>
g.push!
g.translate @x, @y
s = pop_in @p!, 0.1, 2
g.scale s, s
g.translate -@x, -@y
super!
g.pop!
class WaterEmitter extends Emitter
count: 20
duration: 0.4
new: (@box, ...) =>
super ...
make_particle: =>
x = @box.x + love.math.random! * @box.w
y = @box.y + love.math.random! * @box.h
WaterParticle x, y - @box.h
draw: (...) =>
COLOR\push C.water
-- g.rectangle "line", @box\unpack!
COLOR\pop!
super ...
class DirtEmitter extends Emitter
count: 20
duration: 0.2
new: (@box, ...) =>
super ...
make_particle: =>
x = @box.x + love.math.random! * @box.w
y = @box.y + love.math.random! * @box.h
DirtParticle x, y
draw: (...) =>
COLOR\push C.dirt_darker
-- g.rectangle "line", @box\unpack!
COLOR\pop!
super ...
{ :WaterEmitter, :DirtEmitter }
| 17.930233 | 43 | 0.545396 |
d80f494210fecd523e12569f828f25f017edca4e | 1,189 | class
new: (@x, @y) =>
@acc = 17
@radius = 10
@physics = {}
with @physics
.body = love.physics.newBody game.world, @x, @y, "dynamic"
.shape = love.physics.newRectangleShape @x, @y, 24, 24
.fixture = love.physics.newFixture .body, .shape, 1
.fixture\setRestitution 0.45
@id = 1
@keys = {
"right": "right"
"left": "left"
"down": "down"
"up": "up"
}
update: (dt) =>
with love.keyboard
if .isDown @keys["right"]
@physics.body\applyForce @acc, 0
if .isDown @keys["left"]
@physics.body\applyForce -@acc, 0
if .isDown @keys["down"]
@physics.body\applyForce 0, @acc
if .isDown @keys["up"]
@physics.body\applyForce 0, -@acc
with game
wx, wy, ww, wh = .camera\getWorld!
x, y = @physics.body\getWorldCenter!
dx, dy = @physics.body\getLinearVelocity!
.camera.x = math.lerp .camera.x, x + dx / 1.25, dt * 2
.camera.y = math.lerp .camera.y, y + dy / 1.25, dt * 2
draw: =>
with love.graphics
.setColor 255, 255, 255
.polygon "fill", @physics.body\getWorldPoints @physics.shape\getPoints!
| 24.770833 | 77 | 0.547519 |
626da1f9ed247c1394ea06c020d793fa4519d9fe | 963 | import Model, enum from require "lapis.db.model"
import create_table, types, add_column, drop_column from require "lapis.db.schema"
import band, bor from require "bit"
Users = require "lazuli.modules.user_management.models.users"
config = (require "lapis.config").get!
class Timeline_Entries extends Model
@relations: {
{"user", belongs_to: "Users"}
{"acl", belongs_to: "ACLs"}
}
@types: enum {
text: 1
image: 2
video: 3
comment: 4
like: 5
profile: 6
}
@get_relation_model: (name)=> switch name
when "Users"
require "lazuli.modules.user_management.models.users"
when "ACLs"
require "models.acls"
@migrations: {
->
create_table "timeline_entries", {
{"id", types.serial}
{"user_id", types.integer}
{"acl_id", types.integer}
{"type", types.integer}
{"target_id", types.integer}
"PRIMARY KEY (id)"
}
}
| 24.075 | 82 | 0.607477 |
183ddf49bfdfcd13d887949fc95a2d7e17314f45 | 2,430 | -- tildeath.astw
-- AST Walker for ~ATH
-- By daelvn
import colorize from require "ansikit.style"
import recompile from require "tildeath.util"
inspect = require "inspect"
io.stdout\setvbuf "no"
get = (path, t) ->
for idx in *path
t = t[idx]
return t
-- prompt
prompt = ->
io.write ">>> "
return io.read "*l"
tn = (n) -> if nn = tonumber n then nn else n
interactiveASTWalk = (ast) ->
print colorize "%{blue}Welcome to the ~ATH AST walker!"
path = {}
while true do
-- path
node = get path, ast
-- prompt
tcmd = prompt!
parts = [part for part in tcmd\gmatch "%S+"]
cmd = parts[1]
cmd2 = parts[2]
switch cmd
when "help", "h"
print [[
help, h - displays this message
quit, exit, q, e - exits the AST walker
statements, s - shows all statements in chunk
pick, p - pretty prints a node
inspect, i - inspects the structure of a node
into, n - goes into a node
back, b - backsteps from a node
list, l - list subnodes
run, r - run program
]]
when "quit", "exit", "q", "e"
return true
when "statements", "s"
for n, statement in ipairs node do print "#{n}. #{recompile statement}"
when "pick", "p"
if cmd2
print style "%{red}Statement does not exist!" unless node[tn cmd2]
print "#{cmd2}. #{recompile node[tn cmd2]}" if node[tn cmd2]
else
print recompile node
when "inspect", "i"
if cmd2
print style "%{red}Statement does not exist!" unless node[tn cmd2]
print "#{cmd2}. #{inspect node[tn cmd2]}" if node[tn cmd2]
else
print inspect node
when "into", "n"
print style "%{red}Statement does not exist!" unless node[tn cmd2]
table.insert path, tn cmd2
print "Current path: #{table.concat path, "."}" if node[tn cmd2]
when "back", "b"
table.remove path, #path
print "Current path: #{table.concat path, "."}"
when "list", "l"
if cmd2
for k, _ in pairs node[tn cmd2]
print " #{k}"
else
for k, _ in pairs node
print " #{k}"
when "run", "r"
import run from require "tildeath.runtime"
run {}, node
{
:interactiveASTWalk
} | 30 | 79 | 0.534568 |
01c1a91366079750e59b6061ff576560a9428a10 | 61 |
love.conf = =>
@screen.width = 300
@screen.height = 400
| 12.2 | 22 | 0.606557 |
c29c4636ae36bee33091de9846983d01d3ab9380 | 2,320 | import Postgres from require "pgmoon"
import psql, HOST, PORT, USER, PASSWORD, DB from require "spec.util"
describe "pgmoon with server", ->
local pg
setup ->
os.execute "spec/postgres.sh start ssl"
r = { psql "drop database if exists #{DB}" }
assert 0 == r[#r], "failed to execute psql: drop database"
r = { psql "create database #{DB}" }
assert 0 == r[#r], "failed to execute psql: create database"
teardown ->
os.execute "spec/postgres.sh stop"
it "connects without ssl on ssl server", ->
pg = Postgres {
database: DB
port: PORT
user: USER
password: PASSWORD
host: HOST
}
assert pg\connect!
assert pg\query "select * from information_schema.tables"
pg\disconnect!
it "connects with ssl on ssl server (defaults to highest available, TLSv1.3)", ->
pg = Postgres {
database: DB
port: PORT
user: USER
password: PASSWORD
host: HOST
ssl: true
ssl_required: true
}
assert pg\connect!
res = assert pg\query [[SELECT version FROM pg_stat_ssl WHERE pid=pg_backend_pid()]]
assert.same 'TLSv1.3', res[1].version
pg\disconnect!
it "connects with TLSv1.2 on ssl server", ->
pg = Postgres {
database: DB
port: PORT
user: USER
password: PASSWORD
host: HOST
ssl: true
ssl_required: true
ssl_version: "tlsv1_2"
}
assert pg\connect!
res = assert pg\query [[SELECT version FROM pg_stat_ssl WHERE pid=pg_backend_pid()]]
assert.same 'TLSv1.2', res[1].version
pg\disconnect!
it "connects with TLSv1.3 on ssl server", ->
pg = Postgres {
database: DB
port: PORT
user: USER
password: PASSWORD
host: HOST
ssl: true
ssl_required: true
ssl_version: "tlsv1_3"
}
assert pg\connect!
res = assert pg\query [[SELECT version FROM pg_stat_ssl WHERE pid=pg_backend_pid()]]
assert.same 'TLSv1.3', res[1].version
pg\disconnect!
it "connects with ssl using cqueues", ->
pg = Postgres {
database: DB
port: PORT
user: USER
password: PASSWORD
host: HOST
ssl: true
socket_type: "cqueues"
}
assert pg\connect!
assert pg\query "select * from information_schema.tables"
pg\disconnect!
| 23.673469 | 88 | 0.618103 |
00b22895b427df8e728cea1ad11af89d28731633 | 262 | require "test"
test class PointTest
zero_test: ->
p = Point!
assert p.x == 0
assert p.y == 0
assign_test: ->
p = Point!
p.x = 1
p.y = 2
assert p.x == 1
assert p.y == 2
initialize_test: ->
p = Point 4, 5
assert p.x == 4
assert p.y == 5 | 13.789474 | 20 | 0.549618 |
56171d673d85a3ac60eb5ded7e2f9e60fd19e01a | 1,912 | -- Copyright 2014 Harley Laue
-- Copyright 2014 Leaf Corcoran
-- The runner function is basically lapis.serve
-- The mixin function is from moonscript's moon/init.moon
import dispatch from require "gimlet.dispatcher"
gimlet_cache = {}
runner = (gimlet_cls) ->
gimlet = gimlet_cache[gimlet_cls]
unless gimlet
gimlet = if type(gimlet_cls) == "string"
require(gimlet_cls)!
elseif gimlet_cls.__base
gimlet_cls!
else
gimlet_cls
gimlet_cache[gimlet_cls] = gimlet
dispatch gimlet
-- mixin class properties into self, call new
mixin = (cls, ...) =>
for key, val in pairs cls.__base
self[key] = val if not key\match"^__"
cls.__init self, ...
import Logger from require "gimlet.logger"
import Router from require "gimlet.router"
import Static from require "gimlet.static"
import validate_handler from require "gimlet.utils"
class Gimlet
new: =>
@action = =>
@_handlers = {}
@_mapped = { gimlet: @ }
-- Sets the entire middleware table with the given handlers.
-- This will clear any current middleware handlers.
-- error will be inoked if any handler is not a callable function.
handlers: (...) =>
@_handlers = {}
for _, h in pairs {...}
@use h
-- Sets the handler that will be called after the middleware has been invoked.
-- This is set to Router in Classic
set_action: (handler) =>
validate_handler handler
@action = handler
-- Use adds a middleware handler to the stack.
-- Midleware handlers are invoked in the order that they are added.
-- error is invoked if the handler is not a callable function.
use: (handler) =>
validate_handler handler
table.insert @_handlers, handler
map: (name, value) =>
@_mapped[name] = value
-- Run the application
run: =>
runner @
class Classic
new: (log = io.stdout) =>
mixin self, Gimlet
mixin self, Router
@use Logger log
@use Static "/public", :log
@set_action @handle
{:Gimlet, :Classic}
| 23.604938 | 79 | 0.705544 |
4add665b38b57c6875736d16ea7475633ba593d6 | 2,755 |
import insert from table
import Set from require "moonscript.data"
import Block from require "moonscript.compile"
-- globals allowed to be referenced
default_whitelist = Set {
'_G'
'_VERSION'
'assert'
'bit32'
'collectgarbage'
'coroutine'
'debug'
'dofile'
'error'
'getfenv'
'getmetatable'
'io'
'ipairs'
'load'
'loadfile'
'loadstring'
'math'
'module'
'next'
'os'
'package'
'pairs'
'pcall'
'print'
'rawequal'
'rawget'
'rawlen'
'rawset'
'require'
'select'
'setfenv'
'setmetatable'
'string'
'table'
'tonumber'
'tostring'
'type'
'unpack'
'xpcall'
"nil"
"true"
"false"
}
class LinterBlock extends Block
new: (whitelist_globals=default_whitelist, ...) =>
super ...
@lint_errors = {}
vc = @value_compilers
@value_compilers = setmetatable {
ref: (block, val) ->
name = val[2]
unless block\has_name(name) or whitelist_globals[name] or name\match "%."
insert @lint_errors, {
"accessing global #{name}"
val[-1]
}
vc.ref block, val
}, __index: vc
block: (...) =>
with super ...
.block = @block
.value_compilers = @value_compilers
format_lint = (errors, code, header) ->
return unless next errors
import pos_to_line, get_line from require "moonscript.util"
formatted = for {msg, pos} in *errors
if pos
line = pos_to_line code, pos
msg = "line #{line}: #{msg}"
line_text = "> " .. get_line code, line
sep_len = math.max #msg, #line_text
table.concat {
msg
"="\rep sep_len
line_text
}, "\n"
else
msg
table.insert formatted, 1, header if header
table.concat formatted, "\n\n"
-- {
-- whitelist_globals: {
-- ["some_file_pattern"]: {
-- "some_var", "another_var"
-- }
-- }
-- }
whitelist_for_file = do
local lint_config
(fname) ->
unless lint_config
lint_config = {}
pcall -> lint_config = require "lint_config"
return default_whitelist unless lint_config.whitelist_globals
final_list = {}
for pattern, list in pairs lint_config.whitelist_globals
if fname\match(pattern)
for item in *list
insert final_list, item
setmetatable Set(final_list), __index: default_whitelist
lint_code = (code, name="string input", whitelist_globals) ->
parse = require "moonscript.parse"
tree, err = parse.string code
return nil, err unless tree
scope = LinterBlock whitelist_globals
scope\stms tree
format_lint scope.lint_errors, code, name
lint_file = (fname) ->
f, err = io.open fname
return nil, err unless f
lint_code f\read("*a"), fname, whitelist_for_file fname
{ :lint_code, :lint_file }
| 19.820144 | 81 | 0.621779 |
ca80bc25db14ae5beb738e26a6b73713f3a8ee8d | 2,811 |
import ntype, mtype, build from require "moonscript.types"
import NameProxy from require "moonscript.transform.names"
import insert from table
import unpack from require "moonscript.util"
import user_error from require "moonscript.errors"
join = (...) ->
with out = {}
i = 1
for tbl in *{...}
for v in *tbl
out[i] = v
i += 1
has_destructure = (names) ->
for n in *names
return true if ntype(n) == "table"
false
extract_assign_names = (name, accum={}, prefix={}) ->
i = 1
for tuple in *name[2]
value, suffix = if #tuple == 1
s = {"index", {"number", i}}
i += 1
tuple[1], s
else
key = tuple[1]
s = if ntype(key) == "key_literal"
key_name = key[2]
if ntype(key_name) == "colon_stub"
key_name
else
{"dot", key_name}
else
{"index", key}
tuple[2], s
suffix = join prefix, {suffix}
switch ntype value
when "value", "ref", "chain", "self"
insert accum, {value, suffix}
when "table"
extract_assign_names value, accum, suffix
else
user_error "Can't destructure value of type: #{ntype value}"
accum
build_assign = (scope, destruct_literal, receiver) ->
extracted_names = extract_assign_names destruct_literal
names = {}
values = {}
inner = {"assign", names, values}
obj = if scope\is_local(receiver) or #extracted_names == 1
receiver
else
with obj = NameProxy "obj"
inner = build.do {
build.assign_one obj, receiver
{"assign", names, values}
}
for tuple in *extracted_names
insert names, tuple[1]
chain = if obj
NameProxy.chain obj, unpack tuple[2]
else
"nil"
insert values, chain
build.group {
{"declare", names}
inner
}
-- applies to destructuring to a assign node
split_assign = (scope, assign) ->
names, values = unpack assign, 2
g = {}
total_names = #names
total_values = #values
-- We have to break apart the assign into groups of regular
-- assigns, and then the destructuring assignments
start = 1
for i, n in ipairs names
if ntype(n) == "table"
if i > start
stop = i - 1
insert g, {
"assign"
for i=start,stop
names[i]
for i=start,stop
values[i]
}
insert g, build_assign scope, n, values[i]
start = i + 1
if total_names >= start or total_values >= start
name_slice = if total_names < start
{"_"}
else
for i=start,total_names do names[i]
value_slice = if total_values < start
{"nil"}
else
for i=start,total_values do values[i]
insert g, {"assign", name_slice, value_slice}
build.group g
{ :has_destructure, :split_assign, :build_assign }
| 22.133858 | 68 | 0.59196 |
546186e50d797518d36c30e109a4703d9de002e8 | 32 | array =>
(get array "length")
| 10.666667 | 22 | 0.59375 |
01e311159517027bbd74a6bb4352680f5318983a | 532 | { :gsub, :split } = require('std.string')
export req = (path, file) ->
pathParts = split(gsub(path, '/', '.'), '%.')
firstFilePart = split(gsub(file, '/', '.'), '%.')[1]
dir = ''
for part in *pathParts
if part == firstFilePart then break
dir ..= "#{part}."
require(dir .. file)
{
_: req(..., 'lib.lodash'),
display: req(..., 'lib.display'),
Enum: req(..., 'lib.enum'),
geo: req(..., 'lib.geo'),
Loader: req(..., 'lib.loader'),
math: req(..., 'lib.math'),
Queue: req(..., 'lib.queue'),
run: req(..., 'lib.run'),
}
| 24.181818 | 53 | 0.526316 |
d3be3960393941a08d345fce1d6b820548a3fa4e | 1,372 | import encode_base64 from require 'lapis.util.encoding'
--------------------------------------------------------------------------------
isempty = (s)-> s == nil or s == ''
--------------------------------------------------------------------------------
settings_basic_auth = (item)->
'Basic ' .. encode_base64("#{item.ba_login}:#{item.ba_pass}")
--------------------------------------------------------------------------------
basic_auth = (app, setting, page_info)->
if app.req.headers['authorization']
if settings_basic_auth(setting) == app.req.headers['authorization'] or
settings_basic_auth(page_info.folder) == app.req.headers['authorization'] or
settings_basic_auth(page_info.page) == app.req.headers['authorization']
app.session.basic_auth = app.req.headers['authorization']
--------------------------------------------------------------------------------
is_auth = (app, setting, page_info)->
(
isempty(setting.ba_login) and
isempty(page_info.page.ba_login) and
isempty(page_info.folder.ba_login)
) or
app.session.basic_auth == settings_basic_auth(setting) or
app.session.basic_auth == settings_basic_auth(page_info.folder) or
app.session.basic_auth == settings_basic_auth(page_info.page)
--------------------------------------------------------------------------------
-- expose methods
{ :basic_auth, :is_auth } | 52.769231 | 83 | 0.513848 |
ff51e338d0808d76ba9cb8a2589c1ea47f5070ee | 150 | export modinfo = {
type: "function"
id: "Output6"
func: (message, color, recipient, stick) ->
TabletMerge message, color, recipient, stick, 6
}
| 18.75 | 49 | 0.68 |
ca8903c872f79d616f8ccfbbb28dfcd3be8653bb | 4,245 | -- buildshaders.moon
--
-- shader builder (in moonscript I guess?)
mc = require "dev/miniconsole.t"
sutil = require "util/string.t"
async = require "async"
argparse = require "util/argparse.t"
local app
listdir = (dir) -> [{fn, "#{dir}/#{fn}"} for fn in *(truss.list_directory dir)]
is_shader = (fn) -> (fn != 'varying.def.sc') and ((fn\sub -3) == '.sc')
find_loose_shaders = (dir) ->
[{fn, p} for {fn, p} in *(listdir dir) when (is_shader fn) and (not truss.is_archived p)]
find_shader_dirs = (dir) ->
[p for {_, p} in *(listdir dir) when truss.is_directory p]
normpath = (path) ->
if truss.os == 'Windows'
path\gsub("/", "\\")
else
path
extend = (a, b) ->
for v in *b
a[#a+1] = v
a
SHADER_DIR = "shaders"
WIN_SHADER_TYPES = {
f: "ps_4_0"
v: "vs_4_0"
c: "cs_5_0"
}
PLATFORMS = {
windows: "dx11",
linux: "glsl",
osx: "mtl",
vulkan: "spirv"
}
PLATFORM_ALIASES = {
vulkan: "linux"
}
CHARS = if truss.os == "OSX"
{vert: "│", term: "└"}
else
{vert: "\179", term: "\192"}
make_cmd = (shader_type, platform, input_fn, output_fn) ->
args = if platform == "linux" or platform == "osx"
{"./bin/shadercRelease"}
else
{"bin/shadercRelease"}
extend args, {
"-f", input_fn,
"-o", output_fn,
"--type", shader_type,
"-i", "#{SHADER_DIR}/raw/common/",
"--platform", PLATFORM_ALIASES[platform] or platform
}
extend args, switch platform
when "linux"
{"-p", "120"}
when "windows"
{"-p", WIN_SHADER_TYPES[shader_type],
"-O", "3"}
when "osx"
{"-p", "metal"}
when "vulkan"
{"-p", "spirv"}
args[#args+1] = "2>&1"
normpath table.concat args, " "
do_cmd = (cmd) ->
f = io.popen cmd, 'r'
s = f\read '*a'
f\close!
s
header = (s, n = 80, char = "=") ->
n -= (#s + 2)
pre = math.floor n / 2
"#{string.rep(char, pre)} #{s} #{string.rep(char, n - pre)}"
do_file = (fn, path, platforms) ->
prefix = fn\sub(1,1)
errors = ""
errlangs = ""
for platform, lang in pairs platforms
cmd = make_cmd prefix, platform, path, "#{SHADER_DIR}/#{lang}/#{fn\sub(1,-4)}.bin"
res = do_cmd cmd
if #res > 2
errors ..= (header lang, 80, '-') .. "\n" .. res
errlangs ..= " " .. lang
if #errors > 0
errors, errlangs
else
nil, nil
concat = (t) ->
table.concat ["#{header(k)}\n#{v}" for k,v in pairs t], "\n"
stdout_print = (_, text, fg, bg) ->
print(text)
finish = -> if app.finish then app\finish!
export init = ->
args = argparse.parse!
app = if args['--repl']
app = mc.ConsoleApp {title: 'Shader Compiler'}
else
{print: stdout_print, update: ->, clear: ->, finish: truss.quit}
platforms = if args['--platform']
p = args['--platform']\lower()
{[p]: PLATFORMS[p]}
else
PLATFORMS
if #[k for k,v in pairs platforms] == 0
app\print "Invalid platform #{args['--platform']}"
finish!
return
platlist = [v for k,v in pairs platforms]
table.sort platlist
platlist = table.concat platlist, " "
async.run ->
app\clear!
app\print "Compiling shaders (#{platlist}):"
errors = {}
total_errors = 0
shader_dirs = if args['-i']
{"#{SHADER_DIR}/raw/#{args['-i']}"}
else
find_shader_dirs "#{SHADER_DIR}/raw"
for dir in *shader_dirs
loose_shaders = find_loose_shaders dir
if #loose_shaders == 0 then continue
app\print dir
nerrs, nshaders = 0, 0
for {fn, path} in *loose_shaders
errors[fn], errlangs = do_file fn, path, platforms
if errors[fn]
app\print "#{CHARS.vert}!#{fn} -> #{errlangs}"
nerrs += 1
elseif args['-v']
app\print "#{CHARS.vert} #{fn}"
nshaders += 1
async.await_frames 1
app\print "#{CHARS.term} #{nshaders - nerrs} / #{nshaders}"
total_errors += nerrs
app\print "Done."
errstr = (concat errors, '\n')
if total_errors > 0
if args['-o']
app\print "Errors during compilation; see #{args['-o']}"
truss.save_string args['-o'], errstr
else
app\print "Errors during shader compilation: "
app\print errstr
else
app\print "All shaders compiled successfully."
finish!
export update = ->
async\update!
app\update! | 24.257143 | 91 | 0.571967 |
6e81ab74fec1dca24e13c29ffeeae5a0bc1e3122 | 3,317 | return (ASS, ASSFInst, yutilsMissingMsg, createASSClass, Functional, LineCollection, Line, logger, SubInspector, Yutils) ->
{:list, :math, :string, :table, :unicode, :util, :re } = Functional
round = math.round
CommandBase = createASSClass "Draw.CommandBase", ASS.Tag.Base, {}, {}, {precision: 3}
CommandBase.new = (args, y) =>
-- most drawing commands (l, m, n) represent a single point
if @compatible[ASS.Point]
argType = type args
@x, @y = if argType == "number"
args, y or 0
elseif argType == "table" and args.__raw
args[1] or 0, args[2] or args[1] or 0
else
args = y == nil and args or {args, y}
@readProps args
@getArgs args, 0, true
else
-- any other drawing command either consist of multiple (b, s) or no (c) points
-- do note that this constructor is fairly slow in the context of drawings
-- which is why faster overrides are specified for common drawing commands
for i = 1, #args, 2
j = (i+1)/2
@[@__meta__.order[j]] = @__meta__.types[j]{args[i], args[i+1] or args[i]}
return @
CommandBase.getTagParams = (precision = @__tag.precision) =>
return round(@x, precision), round(@y, precision) if @compatible[ASS.Point]
params, parts = @__meta__.order, {}
i, j = 1, 1
while i <= @__meta__.rawArgCnt
parts[i], parts[i+1] = @[params[j]]\getTagParams!
i += @[params[j]].__meta__.rawArgCnt
j += 1
return unpack parts
CommandBase.getLength = (prevCmd) =>
assert Yutils, yutilsMissingMsg
-- get end coordinates (cursor) of previous command
x0, y0 = if prevCmd
if prevCmd.class == ASS.Draw.Bezier
prevCmd.p3.x, prevCmd.p3.y
elseif prevCmd.compatible[ASS.Point]
prevCmd.x, prevCmd.y
else prevCmd\get!
else 0, 0
-- save cursor for further processing
@cursor = ASS.Point x0, y0
name = @__tag.name
len = switch name
when "b"
-- TODO: make less grievously slow, drop Yutils
shapeSection = ASS.Draw.DrawingBase{ASS.Draw.Move(@cursor.x, @cursor.y), @}
--save flattened shape for further processing
@flattened = ASS.Draw.DrawingBase{str: Yutils.shape.flatten shapeSection\getTagParams!}
@flattened\getLength!
when "l"
x, y = @get!
math.vector2.distance x0, y0, x, y
else 0 -- m, n
-- save length for further processing
@length = len
return len
CommandBase.getPositionAtLength = (len, useCachedLengths, useCurveTime) =>
assert Yutils, yutilsMissingMsg
@parent\getLength! unless @length and @cursor and useCachedLengths
pos = switch @__tag.name
when useCurveTime and "b"
px, py = Yutils.math.bezier math.min(len/@length, 1), {{@cursor.x, @cursor.y}, {@p1.x, @p1.y},
{@p2.x, @p2.y}, {@p3.x, @p3.y}}
ASS.Point px, py
when "b"
-- we already know this data is up-to-date because @parent\getLength! was run
@getFlattened(true)\getPositionAtLength len, true
when "l"
ASS.Point @copy!\scaleToLength len, true
when "m"
ASS.Point @
pos.__tag.name = "position"
return pos
CommandBase.getPoints = (allowCompatible) =>
return allowCompatible and {@} or {ASS.Point{@}}
return CommandBase
| 33.505051 | 123 | 0.622852 |
50453718a18a05a431461279f760745bbc25d773 | 116 | {
Scene: require "moon-mission.Scene"
Game: require "moon-mission.Game"
utils: require "moon-mission.utils"
}
| 19.333333 | 37 | 0.706897 |
fdc4027d431bc9c1594015f631412aa9fab6a332 | 1,883 |
class PostgresArray
getmetatable(PostgresArray).__call = (t) =>
setmetatable t, @__base
default_escape_literal = nil
encode_array = do
append_buffer = (escape_literal, buffer, values) ->
for item in *values
-- plain array
if type(item) == "table" and not getmetatable(item)
table.insert buffer, "["
append_buffer escape_literal, buffer, item
buffer[#buffer] = "]" -- strips trailing comma
table.insert buffer, ","
else
table.insert buffer, escape_literal item
table.insert buffer, ","
buffer
(tbl, escape_literal) ->
escape_literal or= default_escape_literal
unless escape_literal
import Postgres from require "kpgmoon"
default_escape_literal = (v) ->
Postgres.escape_literal nil, v
escape_literal = default_escape_literal
buffer = append_buffer escape_literal, {"ARRAY["}, tbl
buffer[#buffer] = "]" -- strips trailing comma
table.concat buffer
convert_values = (array, fn) ->
for idx, v in ipairs array
if type(v) == "table"
convert_values v, fn
else
array[idx] = fn v
array
decode_array = do
import P, R, S, V, Ct, C, Cs from require "lpeg"
g = P {
"array"
array: Ct V"open" * (V"value" * (P"," * V"value")^0)^-1 * V"close"
value: V"invalid_char" + V"string" + V"array" + V"literal"
string: P'"' * Cs(
(P([[\\]]) / [[\]] + P([[\"]]) / [["]] + (P(1) - P'"'))^0
) * P'"'
literal: C (P(1) - S"},")^1
invalid_char: S" \t\r\n" / -> error "got unexpected whitespace"
open: P"{"
delim: P","
close: P"}"
}
(str, convert_fn) ->
out = (assert g\match(str), "failed to parse postgresql array")
setmetatable out, PostgresArray.__base
if convert_fn
convert_values out, convert_fn
else
out
{ :encode_array, :decode_array, :PostgresArray }
| 22.963415 | 70 | 0.601168 |
729303982effcca6ce02825e8ce53642d07f5eea | 473 | -> {
sprite: game.sprites.gun.handgun
pivot_x: 8 -- spin around this
pivot_y: 3 -- ... and this
off_x: 0 -- relative to player right now :/
off_y: 4
ammo: 10
fire_rate: 0.025 -- second
spread: 0.1 -- randomly deviate by percent of 90*
recoil: 5 -- move mother by this much(tm)
radius: 6 -- the radius of the circle on which the gun orbits the mother
bullet_sprite: game.sprites.bullet.pill_lg
bullet_speed: 300
} | 33.785714 | 81 | 0.627907 |
53d91742abbc2a0ccdf6e63c27365f9197d3b8ee | 178 | name = "test_next"
parent = ...
TK = require("PackageToolkit")
case = (require parent..".case")["case"]
M = {}
M[name] = ->
case {1,2}, 2, "case 1"
return true
return M | 17.8 | 40 | 0.573034 |
f09e3647842aa1a385939f703be26d71d62a70b6 | 2,230 | export modinfo = {
type: "command"
desc: "bigdeek"
alias: {"bigdeek"}
func: getDoPlayersFunction (v) ->
color = "Pastel brown"
pcall ->
rm = v.Character["Nice thing"]
rm.Parent = nil
D = CreateInstance"Model"{
Parent: v.Character
Name: "Nice thing"
}
bg = CreateInstance"BodyGyro"{
Parent: v.Character.Torso
}
d = CreateInstance"Part"{
TopSurface: 0
BottomSurface: 0
Name: "Main"
Parent: D
FormFactor: 3
Size: Vector3.new(.6 * 2, 2.5 * 2, .6 * 2)
BrickColor: BrickColor.new(color)
Position: v.Character.Head.Position
CanCollide: false
}
cy = CreateInstance"CylinderMesh"{
Parent: d
}
w = CreateInstance"Weld"{
Parent: v.Character.Head
Part0: d
Part1: v.Character.Head
C0: CFrame.new(0, .25, 2.1)*CFrame.Angles(math.rad(45),0,0)
}
c = CreateInstance"Part"{
Name: "Mush"
BottomSurface: 0
TopSurface: 0
FormFactor: 3
Size: Vector3.new(.6 * 2, .6 * 2, .6 * 2)
CFrame: CFrame.new(d.Position)
BrickColor: BrickColor.new("Pink")
CanCollide: false
Parent: D
}
msm = CreateInstance"SpecialMesh"{
Parent: c
MeshType: "Sphere"
}
cw = CreateInstance"Weld"{
Parent: c
Part0: d
Part1: c
C0: CFrame.new(0, 2.6, 0)
}
ball1 = CreateInstance"Part"{
Parent: D
Name: "Left Ball"
BottomSurface: 0
TopSurface: 0
CanCollide: false
FormFactor: 3
Size: Vector3.new(1 * 2, 1 * 2, 1 * 2)
CFrame: CFrame.new(v.Character["Left Leg"].Position)
BrickColor: BrickColor.new(color)
}
bsm = CreateInstance"SpecialMesh"{
Parent: ball1
MeshType: "Sphere"
}
b1w = CreateInstance"Weld"{
Parent: ball1
Part0: v.Character["Left Leg"]
Part1: ball1
C0: CFrame.new(0, .5, -.5)
}
ball2 = CreateInstance"Part"{
Parent: D
Name: "Right Ball"
BottomSurface: 0
CanCollide: false
TopSurface: 0
FormFactor: 3
Size: Vector3.new(1 * 2, 1 * 2, 1 * 2)
CFrame: CFrame.new(v.Character["Right Leg"].Position)
BrickColor: BrickColor.new(color)
}
b2sm = CreateInstance"SpecialMesh"{
Parent: ball2
MeshType: "Sphere"
}
b2w = CreateInstance"Weld"{
Parent: ball2
Part0: v.Character["Right Leg"]
Part1: ball2
C0: CFrame.new(0, .5, -.5)
}
} | 22.3 | 62 | 0.63139 |
a363602dd94fc27280974341529990f37268519a | 7,020 |
import type, tostring, pairs, select from _G
import concat from table
import
FALSE
NULL
TRUE
build_helpers
format_date
is_raw
raw
is_list
list
is_encodable
from require "lapis.db.base"
local conn, logger
local *
BACKENDS = {
-- the raw backend is a debug backend that lets you specify the function that
-- handles the query
raw: (fn) -> fn
luasql: ->
config = require("lapis.config").get!
mysql_config = assert config.mysql, "missing mysql configuration"
luasql = require("luasql.mysql").mysql!
conn_opts = { mysql_config.database, mysql_config.user, mysql_config.password }
if mysql_config.host
table.insert conn_opts, mysql_config.host
if mysql_config.port then table.insert conn_opts, mysql_config.port
conn = assert luasql\connect unpack(conn_opts)
(q) ->
logger.query q if logger
cur = assert conn\execute q
has_rows = type(cur) != "number"
result = {
affected_rows: has_rows and cur\numrows! or cur
last_auto_id: conn\getlastautoid!
}
if has_rows
colnames = cur\getcolnames!
coltypes = cur\getcoltypes!
assert #colnames == #coltypes
name2type = {}
for i = 1, #colnames do
colname = colnames[i]
coltype = coltypes[i]
name2type[colname] = coltype
while true
if row = cur\fetch {}, "a"
for colname, value in pairs(row)
coltype = name2type[colname]
if coltype == 'number(1)'
value = if value == '1' then true else false
elseif coltype\match 'number'
value = tonumber(value)
row[colname] = value
table.insert result, row
else
break
result
resty_mysql: ->
import after_dispatch, increment_perf from require "lapis.nginx.context"
config = require("lapis.config").get!
mysql_config = assert config.mysql, "missing mysql configuration for resty_mysql"
host = mysql_config.host or "127.0.0.1"
port = mysql_config.port or 3306
path = mysql_config.path
database = assert mysql_config.database, "`database` missing from config for resty_mysql"
user = assert mysql_config.user, "`user` missing from config for resty_mysql"
password = mysql_config.password
ssl = mysql_config.ssl
ssl_verify = mysql_config.ssl_verify
timeout = mysql_config.timeout or 10000 -- 10 seconds
max_idle_timeout = mysql_config.max_idle_timeout or 10000 -- 10 seconds
pool_size = mysql_config.pool_size or 100
mysql = require "resty.mysql"
(q) ->
logger.query q if logger
db = ngx and ngx.ctx.resty_mysql_db
unless db
db, err = assert mysql\new()
db\set_timeout(timeout)
options = {
:database, :user, :password, :ssl, :ssl_verify
}
if path
options.path = path
else
options.host = host
options.port = port
if mysql_config.resty_mysql
for k,v in pairs mysql_config.resty_mysql
options[k] = v
assert db\connect options
if ngx
ngx.ctx.resty_mysql_db = db
after_dispatch ->
db\set_keepalive(max_idle_timeout, pool_size)
start_time = if ngx and config.measure_performance
ngx.update_time!
ngx.now!
res, err, errcode, sqlstate = assert db\query q
local result
if err == 'again'
result = {res}
while err == 'again'
res, err, errcode, sqlstate = assert db\read_result!
table.insert result, res
else
result = res
if start_time
ngx.update_time!
increment_perf "db_time", ngx.now! - start_time
increment_perf "db_count", 1
result
}
set_backend = (name, ...) ->
backend = BACKENDS[name]
unless backend
error "Failed to find MySQL backend: #{name}"
raw_query = backend ...
set_raw_query = (fn) ->
raw_query = fn
get_raw_query = ->
raw_query
escape_literal = (val) ->
switch type val
when "number"
return tostring val
when "string"
if conn
return "'#{conn\escape val}'"
else if ngx
return ngx.quote_sql_str(val)
else
connect!
return escape_literal val
when "boolean"
return val and "TRUE" or "FALSE"
when "table"
return "NULL" if val == NULL
if is_list val
escaped_items = [escape_literal item for item in *val[1]]
assert escaped_items[1], "can't flatten empty list"
return "(#{concat escaped_items, ", "})"
return val[1] if is_raw val
error "unknown table passed to `escape_literal`"
error "don't know how to escape value: #{val}"
escape_identifier = (ident) ->
return ident[1] if is_raw ident
ident = tostring ident
'`' .. (ident\gsub '`', '``') .. '`'
init_logger = ->
config = require("lapis.config").get!
logger = if ngx or os.getenv("LAPIS_SHOW_QUERIES") or config.show_queries
require "lapis.logging"
init_db = ->
config = require("lapis.config").get!
backend = config.mysql and config.mysql.backend
unless backend
backend = if ngx
"resty_mysql"
else
"luasql"
set_backend backend
connect = ->
init_logger!
init_db! -- replaces raw_query to default backend
raw_query = (...) ->
connect!
raw_query ...
interpolate_query, encode_values, encode_assigns, encode_clause = build_helpers escape_literal, escape_identifier
append_all = (t, ...) ->
for i=1, select "#", ...
t[#t + 1] = select i, ...
add_cond = (buffer, cond, ...) ->
append_all buffer, " WHERE "
switch type cond
when "table"
encode_clause cond, buffer
when "string"
append_all buffer, interpolate_query cond, ...
query = (str, ...) ->
if select("#", ...) > 0
str = interpolate_query str, ...
raw_query str
_select = (str, ...) ->
query "SELECT " .. str, ...
_insert = (tbl, values, ...) ->
buff = {
"INSERT INTO "
escape_identifier(tbl)
" "
}
encode_values values, buff
raw_query concat buff
_update = (table, values, cond, ...) ->
buff = {
"UPDATE "
escape_identifier(table)
" SET "
}
encode_assigns values, buff
if cond
add_cond buff, cond, ...
raw_query concat buff
_delete = (table, cond, ...) ->
buff = {
"DELETE FROM "
escape_identifier(table)
}
if cond
add_cond buff, cond, ...
raw_query concat buff
_truncate = (table) ->
raw_query "TRUNCATE " .. escape_identifier table
-- To be implemented
-- {
-- :parse_clause
--
-- }
{
:connect
:raw, :is_raw, :NULL, :TRUE, :FALSE
:list, :is_list
:is_encodable
:encode_values
:encode_assigns
:encode_clause
:interpolate_query
:query
:escape_literal
:escape_identifier
:format_date
:init_logger
:set_backend
:set_raw_query
:get_raw_query
select: _select
insert: _insert
update: _update
delete: _delete
truncate: _truncate
}
| 23.016393 | 113 | 0.622222 |
7fd67c663e4973e191501b5d1f8e5a103d6c50a8 | 2,968 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, interact from howl
class SearchInteraction
new: (@operation, @type, opts={}) =>
@searcher = app.editor.searcher
@opts = moon.copy opts
@keymap = moon.copy @keymap
for keystroke in *opts.backward_keys
@keymap[keystroke] = -> @searcher\previous!
for keystroke in *opts.forward_keys
@keymap[keystroke] = -> @searcher\next!
init: (@command_line) =>
@command_line.prompt = @opts.prompt
@command_line.title = @opts.title
@command_line.notification\show!
on_text_changed: (text) =>
@searcher[@operation] @searcher, text, @type
help: {
{
key: 'up'
action: 'Select previous match'
}
{
key: 'down'
action: 'Select next match'
}
}
keymap:
up: => @searcher\previous!
down: => @searcher\next!
enter: => @command_line\finish @command_line.text
escape: =>
@searcher\cancel!
@command_line\finish!
interact.register
name: 'search'
description: 'Generic search interaction'
handler: (operation, type, opts={}) ->
error 'operation and type required' unless operation and type
search_interaction = SearchInteraction operation, type, opts
app.window.command_panel\run search_interaction, text: opts.text
interact.register
name: 'forward_search'
description: ''
handler: (opts) ->
interact.search 'forward_to', 'plain'
prompt: opts.prompt
text: opts.text
title: opts.title or 'Forward Search'
forward_keys: howl.bindings.keystrokes_for('buffer-search-forward', 'editor')
backward_keys: howl.bindings.keystrokes_for('buffer-search-backward', 'editor')
interact.register
name: 'backward_search'
description: ''
handler: (opts) ->
interact.search 'backward_to', 'plain'
prompt: opts.prompt
text: opts.text
title: opts.title or 'Backward Search'
forward_keys: howl.bindings.keystrokes_for('buffer-search-forward', 'editor')
backward_keys: howl.bindings.keystrokes_for('buffer-search-backward', 'editor')
interact.register
name: 'forward_search_word'
description: ''
handler: (opts) ->
interact.search 'forward_to', 'word',
prompt: opts.prompt
text: opts.text
title: opts.title or 'Forward Word Search'
forward_keys: howl.bindings.keystrokes_for('buffer-search-word-forward', 'editor')
backward_keys: howl.bindings.keystrokes_for('buffer-search-word-backward', 'editor')
interact.register
name: 'backward_search_word'
description: ''
handler: (opts) ->
interact.search 'backward_to', 'word',
prompt: opts.prompt
text: opts.text
title: opts.title or 'Backward Word Search',
forward_keys: howl.bindings.keystrokes_for('buffer-search-word-forward', 'editor')
backward_keys: howl.bindings.keystrokes_for('buffer-search-word-backward', 'editor')
| 30.916667 | 90 | 0.684636 |
3be84e42272993b7b3f41a0eba8b09d1b5e6bcee | 11,301 | require "spec.helpers" -- for one_of
db = require "lapis.db.postgres"
schema = require "lapis.db.postgres.schema"
unpack = unpack or table.unpack
value_table = { hello: "world", age: 34 }
tests = {
-- lapis.db.postgres
{
-> db.escape_identifier "dad"
'"dad"'
}
{
-> db.escape_identifier "select"
'"select"'
}
{
-> db.escape_identifier 'love"fish'
'"love""fish"'
}
{
-> db.escape_identifier db.raw "hello(world)"
"hello(world)"
}
{
-> db.escape_literal 3434
"3434"
}
{
-> db.escape_literal "cat's soft fur"
"'cat''s soft fur'"
}
{
-> db.escape_literal db.raw "upper(username)"
"upper(username)"
}
{
-> db.escape_literal db.list {1,2,3,4,5}
"(1, 2, 3, 4, 5)"
}
{
-> db.escape_literal db.list {"hello", "world", db.TRUE}
"('hello', 'world', TRUE)"
}
{
-> db.escape_literal db.list {"foo", db.raw "lower(name)"}
"('foo', lower(name))"
}
{
-> db.escape_literal db.array {1,2,3,4,5}
"ARRAY[1,2,3,4,5]"
}
{
-> db.interpolate_query "select * from cool where hello = ?", "world"
"select * from cool where hello = 'world'"
}
{
-> db.encode_values(value_table)
[[("hello", "age") VALUES ('world', 34)]]
[[("age", "hello") VALUES (34, 'world')]]
}
{
-> db.encode_assigns(value_table)
[["hello" = 'world', "age" = 34]]
[["age" = 34, "hello" = 'world']]
}
{
-> db.encode_assigns thing: db.NULL
[["thing" = NULL]]
}
{
-> db.encode_clause thing: db.NULL
[["thing" IS NULL]]
}
{
-> db.encode_clause cool: true, id: db.list {1,2,3,5}
[["id" IN (1, 2, 3, 5) AND "cool" = TRUE]]
[["cool" = TRUE AND "id" IN (1, 2, 3, 5)]]
}
{
-> db.interpolate_query "update items set x = ?", db.raw"y + 1"
"update items set x = y + 1"
}
{
-> db.interpolate_query "update items set x = false where y in ?", db.list {"a", "b"}
"update items set x = false where y in ('a', 'b')"
}
{
-> db.select "* from things where id = ?", "cool days"
[[SELECT * from things where id = 'cool days']]
}
{
-> db.insert "cats", age: 123, name: "catter"
[[INSERT INTO "cats" ("name", "age") VALUES ('catter', 123)]]
[[INSERT INTO "cats" ("age", "name") VALUES (123, 'catter')]]
}
{
-> db.update "cats", { age: db.raw"age - 10" }, "name = ?", "catter"
[[UPDATE "cats" SET "age" = age - 10 WHERE name = 'catter']]
}
{
-> db.update "cats", { age: db.raw"age - 10" }, { name: db.NULL }
[[UPDATE "cats" SET "age" = age - 10 WHERE "name" IS NULL]]
}
{
-> db.update "cats", { age: db.NULL }, { name: db.NULL }
[[UPDATE "cats" SET "age" = NULL WHERE "name" IS NULL]]
}
{
-> db.update "cats", { color: "red" }, { weight: 1200, length: 392 }
[[UPDATE "cats" SET "color" = 'red' WHERE "weight" = 1200 AND "length" = 392]]
[[UPDATE "cats" SET "color" = 'red' WHERE "length" = 392 AND "weight" = 1200]]
}
{
-> db.update "cats", { color: "red" }, { weight: 1200, length: 392 }, "weight", "color"
[[UPDATE "cats" SET "color" = 'red' WHERE "weight" = 1200 AND "length" = 392 RETURNING "weight", "color"]]
[[UPDATE "cats" SET "color" = 'red' WHERE "length" = 392 AND "weight" = 1200 RETURNING "weight", "color"]]
}
{
-> db.update "cats", { age: db.NULL }, { name: db.NULL }, db.raw "*"
[[UPDATE "cats" SET "age" = NULL WHERE "name" IS NULL RETURNING *]]
}
{
-> db.delete "cats"
[[DELETE FROM "cats"]]
}
{
-> db.delete "cats", "name = ?", "rump"
[[DELETE FROM "cats" WHERE name = 'rump']]
}
{
-> db.delete "cats", name: "rump"
[[DELETE FROM "cats" WHERE "name" = 'rump']]
}
{
-> db.delete "cats", name: "rump", dad: "duck"
[[DELETE FROM "cats" WHERE "name" = 'rump' AND "dad" = 'duck']]
[[DELETE FROM "cats" WHERE "dad" = 'duck' AND "name" = 'rump']]
}
{
-> db.delete "cats", { color: "red" }, "name", "color"
[[DELETE FROM "cats" WHERE "color" = 'red' RETURNING "name", "color"]]
}
{
-> db.delete "cats", { color: "red" }, db.raw "*"
[[DELETE FROM "cats" WHERE "color" = 'red' RETURNING *]]
}
{
-> db.insert "cats", { hungry: true }
[[INSERT INTO "cats" ("hungry") VALUES (TRUE)]]
}
{
-> db.insert "cats", { age: 123, name: "catter" }, "age"
[[INSERT INTO "cats" ("name", "age") VALUES ('catter', 123) RETURNING "age"]]
[[INSERT INTO "cats" ("age", "name") VALUES (123, 'catter') RETURNING "age"]]
}
{
-> db.insert "cats", { age: 123, name: "catter" }, "age", "name"
[[INSERT INTO "cats" ("name", "age") VALUES ('catter', 123) RETURNING "age", "name"]]
[[INSERT INTO "cats" ("age", "name") VALUES (123, 'catter') RETURNING "age", "name"]]
}
-- lapis.db.postgres.schema
{
-> schema.add_column "hello", "dads", schema.types.integer
[[ALTER TABLE "hello" ADD COLUMN "dads" integer NOT NULL DEFAULT 0]]
}
{
-> schema.rename_column "hello", "dads", "cats"
[[ALTER TABLE "hello" RENAME COLUMN "dads" TO "cats"]]
}
{
-> schema.drop_column "hello", "cats"
[[ALTER TABLE "hello" DROP COLUMN "cats"]]
}
{
-> schema.rename_table "hello", "world"
[[ALTER TABLE "hello" RENAME TO "world"]]
}
{
-> tostring schema.types.integer
"integer NOT NULL DEFAULT 0"
}
{
-> tostring schema.types.integer null: true
"integer DEFAULT 0"
}
{
-> tostring schema.types.integer null: true, default: 100, unique: true
"integer DEFAULT 100 UNIQUE"
}
{
-> tostring schema.types.integer array: true, null: true, default: '{1}', unique: true
"integer[] DEFAULT '{1}' UNIQUE"
}
{
-> tostring schema.types.text array: true, null: false
"text[] NOT NULL"
}
{
-> tostring schema.types.text array: true, null: true
"text[]"
}
{
-> tostring schema.types.integer array: 1
"integer[] NOT NULL"
}
{
-> tostring schema.types.integer array: 3
"integer[][][] NOT NULL"
}
{
-> tostring schema.types.serial
"serial NOT NULL"
}
{
-> tostring schema.types.time
"timestamp NOT NULL"
}
{
-> tostring schema.types.time timezone: true
"timestamp with time zone NOT NULL"
}
{
->
import foreign_key, boolean, varchar, text from schema.types
schema.create_table "user_data", {
{"user_id", foreign_key}
{"email_verified", boolean}
{"password_reset_token", varchar null: true}
{"data", text}
"PRIMARY KEY (user_id)"
}
[[CREATE TABLE "user_data" (
"user_id" integer NOT NULL,
"email_verified" boolean NOT NULL DEFAULT FALSE,
"password_reset_token" character varying(255),
"data" text NOT NULL,
PRIMARY KEY (user_id)
);]]
}
{
->
import foreign_key, boolean, varchar, text from schema.types
schema.create_table "join_stuff", {
{"hello_id", foreign_key}
{"world_id", foreign_key}
}, if_not_exists: true
[[CREATE TABLE IF NOT EXISTS "join_stuff" (
"hello_id" integer NOT NULL,
"world_id" integer NOT NULL
);]]
}
{
-> schema.drop_table "user_data"
[[DROP TABLE IF EXISTS "user_data";]]
}
{
-> schema.drop_index "user_data", "one", "two", "three"
[[DROP INDEX IF EXISTS "user_data_one_two_three_idx"]]
}
{
-> db.parse_clause ""
{}
}
{
-> db.parse_clause "where something = TRUE"
{
where: "something = TRUE"
}
}
{
-> db.parse_clause "where something = TRUE order by things asc"
{
where: "something = TRUE "
order: "things asc"
}
}
{
-> db.parse_clause "where something = 'order by cool' having yeah order by \"limit\" asc"
{
having: "yeah "
where: "something = 'order by cool' "
order: '"limit" asc'
}
}
{
-> db.parse_clause "where not exists(select 1 from things limit 100)"
{
where: "not exists(select 1 from things limit 100)"
}
}
{
-> db.parse_clause "order by color asc"
{
order: "color asc"
}
}
{
-> db.parse_clause "ORDER BY color asc"
{
order: "color asc"
}
}
{
-> db.parse_clause "group BY height"
{
group: "height"
}
}
{
-> db.parse_clause "where x = limitx 100"
{
where: "x = limitx 100"
}
}
{
-> db.parse_clause "join dads on color = blue where hello limit 10"
{
limit: "10"
where: "hello "
join: {
{"join", " dads on color = blue "}
}
}
}
{
-> db.parse_clause "inner join dads on color = blue left outer join hello world where foo"
{
where: "foo"
join: {
{"inner join", " dads on color = blue "}
{"left outer join", " hello world "}
}
}
}
{
-> schema.gen_index_name "hello", "world"
"hello_world_idx"
}
{
-> schema.gen_index_name "yes", "please", db.raw "upper(dad)"
"yes_please_upper_dad_idx"
}
{
-> schema.gen_index_name "hello", "world", index_name: "override_me_idx"
"override_me_idx"
}
{
-> db.encode_case("x", { a: "b" })
[[CASE x
WHEN 'a' THEN 'b'
END]]
}
{
-> db.encode_case("x", { a: "b", foo: true })
[[CASE x
WHEN 'a' THEN 'b'
WHEN 'foo' THEN TRUE
END]]
[[CASE x
WHEN 'foo' THEN TRUE
WHEN 'a' THEN 'b'
END]]
}
{
-> db.encode_case("x", { a: "b" }, false)
[[CASE x
WHEN 'a' THEN 'b'
ELSE FALSE
END]]
}
{
-> db.is_encodable "hello"
true
}
{
-> db.is_encodable 2323
true
}
{
-> db.is_encodable true
true
}
{
-> db.is_encodable ->
false
}
{
->
if _G.newproxy
db.is_encodable newproxy!
else
-- cjson.empty_array is a userdata
db.is_encodable require("cjson").empty_array
false
}
{
-> db.is_encodable db.array {1,2,3}
true
}
{
-> db.is_encodable db.NULL
true
}
{
-> db.is_encodable db.TRUE
true
}
{
-> db.is_encodable db.FALSE
true
}
{
-> db.is_encodable {}
false
}
{
-> db.is_encodable nil
false
}
{
-> db.is_raw "hello"
false
}
{
-> db.is_raw db.raw "hello wrold"
true
}
{
-> db.is_raw db.list {1,2,3}
false
}
}
local old_query_fn
describe "lapis.db.postgres", ->
setup ->
old_query_fn = db.set_backend "raw", (q) -> q
teardown ->
db.set_backend "raw", old_query_fn
for group in *tests
it "should match", ->
output = group[1]!
if #group > 2
assert.one_of output, { unpack group, 2 }
else
assert.same group[2], output
it "should create index", ->
input = schema.create_index "user_data", "one", "two"
assert.same input, [[CREATE INDEX "user_data_one_two_idx" ON "user_data" ("one", "two");]]
it "should create index with expression", ->
input = schema.create_index "user_data", db.raw("lower(name)"), "height"
assert.same input, [[CREATE INDEX "user_data_lower_name_height_idx" ON "user_data" (lower(name), "height");]]
it "should create not create duplicate index", ->
old_select = db.select
db.select = -> { { c: 1 } }
input = schema.create_index "user_data", "one", "two", if_not_exists: true
assert.same input, nil
db.select = old_select
| 20.289048 | 113 | 0.548889 |
815887db6374d37f5f9f40bd10668d522e4767c7 | 2,901 | Caste = require('vendor/caste/lib/caste')
{ :Vector } = require('vendor/hug/lib/geo')
class Steering extends Caste
new: (@host) =>
@steering = Vector.ZERO\clone()
if not @host.velocity then @host\set('velocity', Vector.ZERO\clone())
reset: () =>
@steering\reset()
return @
add: (vector) =>
if vector then @steering\add(vector)
return @
init: (dt) =>
@maxSpeed = @host.maxSpeed * dt
return @
update: (dt) =>
{ :position, :velocity, :mass, :maxForce } = @host\get()
@steering\truncate(maxForce)
-- @steering\scale(1 / mass)
velocity\add(@steering)
velocity\truncate(@maxSpeed)
direct: (...) => @add(@doDirect(...))
seek: (target, slowingRadius = 50) => @add(@doSeek(target, slowingRadius))
flee: (target, fleeRadius = 50) => @add(@doFlee(target, fleeRadius))
pursue: (target, slowingRadius = 50) => @add(@doPursue(target, slowingRadius))
evade: (target, fleeRadius = 50) => @add(@doEvade(target, fleeRadius))
wander: (...) => @add(@doWander(...))
-- Direct path to target
doDirect: (target) => target - @host.position
-- Steers toward target
doSeek: (target, slowingRadius = 0) =>
idealVelocity = @doDirect(target)
distance = #idealVelocity
factor = @maxSpeed
if distance < slowingRadius then factor *= distance / slowingRadius
return with idealVelocity
\normalize()
\scale(factor)
\subtract(@host.velocity)
-- Steers away from target
doFlee: (target, fleeRadius = math.huge) =>
idealVelocity = -@doDirect(target)
distance = #idealVelocity
if distance >= fleeRadius then return
return with idealVelocity
\normalize()
\scale(@maxSpeed)
\subtract(@host.velocity)
-- Steers toward target's future projection
doPursue: (target, slowingRadius) =>
distance = target.position\distanceTo(@host.position)
updatesNeeded = distance / @maxSpeed
tv = target.velocity or Vector.ZERO
tv = tv\clone()\scale(updatesNeeded)
targetFuturePosition = target.position\clone()\add(tv)
return @doSeek(targetFuturePosition, slowingRadius)
-- Steers away from target's future projection
doEvade: (target, fleeRadius) =>
distance = target.position\distanceTo(@host.position)
updatesNeeded = distance / @maxSpeed
tv = target.velocity or Vector.ZERO
tv = tv\clone()\scale(updatesNeeded)
targetFuturePosition = target.position\clone()\add(tv)
return @doFlee(targetFuturePosition, fleeRadius)
wanderTheta: love.math.random() * math.tau
-- Roams the land
doWander: (radius = 25, distance = 80, thetaLimit = math.tau) =>
@wanderTheta += love.math.random() * thetaLimit - 0.5 * thetaLimit
circlePos = with @host.velocity\clone()
\normalize()
\multiply(distance)
\add(@host.position)
heading = @host.velocity\getHeading()
angle = @wanderTheta + heading
circleOffset = Vector(radius * math.cos(angle), radius * math.sin(angle))
target = circlePos + circleOffset
return @doSeek(target)
| 29.01 | 79 | 0.69252 |
6cb2b830d8444e6e6f2d73e980098f9da36317c0 | 1,091 |
functions = require "lapis.util.functions"
moon = require "moon"
describe "lapis.util.functions", ->
upvalue = "hello"
fn = -> "the upvalue #{upvalue}"
other_fn = -> "what up, upvalue #{upvalue}"
it "should run the function", ->
clone = functions.locked_fn fn
assert.are_not.equal fn, clone
assert.same fn!, clone!
functions.release_fn clone
it "should reuse a clone", ->
clone = functions.locked_fn fn
functions.release_fn clone
second_clone = functions.locked_fn fn
assert.same clone, second_clone
it "should make multiple clones", ->
clone_1 = functions.locked_fn fn
clone_2 = functions.locked_fn fn
assert.are_not.equal clone_1, clone_2
assert.same fn!, clone_1!
assert.same fn!, clone_2!
functions.release_fn clone_1
functions.release_fn clone_2
it "should run two functions", ->
clone = functions.locked_fn fn
other_clone = functions.locked_fn other_fn
assert.same fn!, clone!
assert.same other_fn!, other_clone!
functions.release_fn other_clone
functions.release_fn clone
| 23.717391 | 46 | 0.697525 |
22550c22c275fde5d3c4b897d396c97230affb43 | 237 | make = (x, y) ->
floor = {}
floor.draw = ->
with love.graphics
.setColor 1, 1, 1
.draw sprites.grass, x, y, 0, 24 / sprites.grass\getWidth!, 24 / sprites.grass\getHeight!
floor
{
:make
} | 18.230769 | 101 | 0.506329 |
4b90638c65858fc6319e1a2fb1c6a3ad70cee844 | 5,511 | --- Copyright 2012-2017 The Howl Developers
--- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import config, interact, Project from howl
import StyledText from howl.ui
append = table.insert
stringify = (value, to_s) ->
return to_s(value) if type(value) != 'table'
[stringify o, to_s for o in *value]
option_completions = (def) ->
options = def.options
options = options! if callable options
options = stringify options, def.tostring or tostring
table.sort options, (a, b) ->
return a < b if type(a) != 'table'
return a[1] < b[1]
columns = { { header: 'Option', style: 'string' } }
if type(options[1]) == 'table'
append columns, { header: 'Description', style: 'comment' }
return options, columns
option_current_value = (def, options, current_buffer) ->
cur_val = tostring current_buffer.config[def.name] or config.get def.name
for option in *options
if option == cur_val or (type(option) == 'table' and option[1] == cur_val)
return option
scope_str = (scope_name, layer=nil) ->
scope_name ..= "[#{layer}]" if layer
return scope_name
scope_item = (def, scope_name, target, description='', layer=nil) ->
if layer
target = target.for_layer layer
to_s = def.tostring or tostring
{
scope_str(scope_name, layer), to_s(target[def.name]), description,
:scope_name, :layer, :target,
quick_select: scope_str(scope_name, layer) .. '='
}
scope_items = (def, buffer) ->
items = {}
append items, scope_item(def, 'global', config)
return items if def.scope == 'global' or not buffer
mode_layer = buffer.mode.config_layer
mode_name = buffer.mode.name
append items, scope_item(
def, 'global', config, "For all buffers with mode #{mode_name}", mode_layer)
if buffer.file
project = Project.for_file buffer.file
if project
append items, scope_item(
def, 'project', project.config,
"For all files under #{project.root.short_path}")
append items, scope_item(
def, 'project', project.config,
"For all files under #{project.root.short_path} with mode #{mode_name}", mode_layer)
append items, scope_item(
def, 'buffer', buffer.config,
"For #{buffer.title} only")
return items
get_vars = ->
vars = [{name, def.description, :def, quick_select: {name..'=', name..'@'}} for name, def in pairs config.definitions]
table.sort vars, (a, b) -> a[1] < b[1]
return vars
interact.register
name: 'get_variable_assignment'
description: 'Get config variable and value selected by user'
handler: ->
command_line = howl.app.window.command_line
buffer = howl.app.editor.buffer
interact.sequence {'var', 'scope', 'value'},
var: -> interact.select
title: 'Select Variable'
items: get_vars!
columns: {
{ header: 'Variable', style: 'string' }
{ header: 'Description', style: 'comment' }
}
scope: (state, from_state) ->
def = state.var.selection.def
if def.scope == 'global'
if from_state == 'value'
return { back: true }
else
return { selection: { 'global', scope_name: 'global', target: config } }
interact.select
title: def.name
items: scope_items def, buffer
columns: {
{ header: 'Scope', style: 'key' }
{ header: 'Value', style: 'string' }
{ header: '', style: 'comment' }
}
cancel_on_back: true
value: (state) ->
def = state.var.selection.def
title = "#{def.name} for #{state.scope.selection.scope_name}"
if def.options
items, columns = option_completions def
selected = interact.select
:title
:items
:columns
selection: option_current_value def, items, buffer
cancel_on_back: true
return unless selected
return selected if selected.back
if type(selected.selection) == 'table'
return selected.selection[1]
return selected.selection
else
interact.read_text
:title
cancel_on_back: true
update: (state) ->
prompt = ''
if state.var
prompt ..= state.var.selection.def.name .. '@'
if state.scope
item = state.scope.selection
prompt ..= scope_str item.scope_name, item.layer
prompt ..= '='
command_line.prompt = prompt
local caption
if state.var
def = state.var.selection.def
caption = StyledText def.description .. '\n', {}
if state.scope
caption ..= StyledText '\n', {}
caption ..= StyledText.for_table scope_items(def, buffer), {
{ style: 'key' },
{ style: 'string' }
{ style: 'comment' }
}
if caption
caption_widget = howl.ui.NotificationWidget!
command_line\add_widget 'caption', caption_widget, 'top'
with caption_widget
\caption caption
\show!
else
command_line\remove_widget 'caption'
finish: (state) ->
return unless state
return {
target: state.scope.selection.target,
var: state.var.selection.def.name,
value: state.value
scope_name: state.scope.selection.scope_name,
layer: state.scope.selection.layer,
:buffer
}
| 30.447514 | 120 | 0.598621 |
de93ed03478edffda6a99bde526fb60c0b689814 | 7,060 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import config, mode from howl
import formatting from howl.editing
import style from howl.ui
append = table.insert
is_comment = (line, comment_prefix) ->
line\umatch r"^\\s*#{r.escape comment_prefix}"
class DefaultMode
completers: { 'in_buffer' }
code_blocks: {}
indent: (editor) =>
indent_level = editor.buffer.config.indent
dont_indent_styles = comment: true, string: true
buffer = editor.buffer
current_line = editor.cursor.line
editor\transform_active_lines (lines) ->
comment_prefix = @_comment_pair!
local prev_line
for line in *lines
continue if line.is_blank and line.nr != current_line
local indent
prev_line or= line.previous_non_blank
if comment_prefix and prev_line and is_comment(prev_line, comment_prefix)
indent = prev_line.indentation
else
line_start_style = style.at_pos buffer, line.start_pos
continue if dont_indent_styles[line_start_style]
indent = @indent_for line, indent_level
line.indentation = indent if indent != line.indentation
prev_line = line
with editor
.cursor.column = .current_line.indentation + 1 if .cursor.column < .current_line.indentation
comment: (editor) =>
prefix, suffix = @_comment_pair!
return unless prefix
prefix ..= ' '
suffix = ' ' .. suffix unless suffix.is_empty
buffer, cursor = editor.buffer, editor.cursor
current_column = cursor.column
tab_expansion = string.rep ' ', buffer.config.tab_width
editor\transform_active_lines (lines) ->
min_indent = math.huge
min_indent = math.min(min_indent, l.indentation) for l in *lines when not l.is_blank
for line in *lines
unless line.is_blank
text = line\gsub '\t', tab_expansion
new_text = text\usub(1, min_indent) .. prefix .. text\usub(min_indent + 1) .. suffix
line.text = new_text
cursor.column = current_column + #prefix unless current_column == 1
uncomment: (editor) =>
prefix, suffix = @_comment_pair!
return unless prefix
buffer, cursor = editor.buffer, editor.cursor
pattern = r"()#{r.escape prefix}\\s?().*?()\\s?#{r.escape suffix}()$"
current_column = cursor.column
cur_line = editor.current_line
cur_line_length = #cur_line
cursor_delta = nil
editor\transform_active_lines (lines) ->
for line in *lines
pfx_start, middle_start, sfx_start, trail_start = line\umatch pattern
if pfx_start
head = line\usub 1, pfx_start - 1
middle = line\usub middle_start, sfx_start - 1
trail = line\usub trail_start
line.text = head .. middle .. trail
cursor_delta = middle_start - pfx_start if line == cur_line
if cursor_delta
cursor.column = math.max 1, current_column - cursor_delta
toggle_comment: (editor) =>
prefix, suffix = @_comment_pair!
return unless prefix
pattern = r"^\\s*#{r.escape prefix}.*"
if editor.active_lines[1]\umatch pattern
@uncomment editor
else
@comment editor
structure: (editor) =>
buffer = editor.buffer
buf_indent = buffer.config.indent
threshold = buffer.config.indentation_structure_threshold
line_levels = {}
lines = {}
cur_line = nil
max_level = 0
for line in *editor.buffer.lines
unless line.is_blank
indentation = line.indentation
if cur_line and indentation > cur_line.indentation
unless cur_line\match '%a'
prev = cur_line.previous
cur_line = prev if prev and prev.indentation == cur_line.indentation
if cur_line and cur_line\match '%a'
level = cur_line.indentation / buf_indent
max_level = math.max level, max_level
line_levels[level] = 1 + (line_levels[level] or 0)
append lines, { line: cur_line, :level }
cur_line = line
cut_off = 0
count = 0
for i = 0, max_level
level_count = line_levels[i]
if level_count
cut_off = i
count += level_count
break if count >= threshold
[l.line for l in *lines when l.level <= cut_off]
resolve_type: (context) =>
pfx = context.prefix
parts = {}
leading = pfx\umatch r'((?:\\w+[.:])*\\w+)[.:]\\w*$'
parts = [p for p in leading\gmatch '%w+'] if leading
leading, parts
on_char_added: (args, editor) =>
if args.key_name == 'return'
buffer = editor.buffer
if buffer.config.auto_format
for code_block in * (@code_blocks.multiline or {})
return true if formatting.ensure_block editor, table.unpack code_block
cur_line = editor.current_line
prev_line = cur_line.previous_non_blank
cur_line.indentation = prev_line.indentation if prev_line
@indent editor
true
indent_for: (line, indent_level) =>
prev_line = line.previous_non_blank
if prev_line
spec = @indentation or {}
dedent_delta = -indent_level if @patterns_match line.text, spec.less_for
indent_delta = indent_level if @patterns_match prev_line.text, spec.more_after
indent_delta = indent_level if not indent_delta and @patterns_match line.text, spec.more_for
same_delta = 0 if @patterns_match prev_line.text, spec.same_after
if indent_delta or dedent_delta or same_delta
delta = (dedent_delta or 0) + (indent_delta or 0) + (same_delta or 0)
new = prev_line.indentation + delta
if new < prev_line.indentation and line.indentation <= new
return line.indentation unless spec.less_for.authoritive
return new
-- unwarranted indents
if spec.more_after and spec.more_after.authoritive != false and line.indentation > prev_line.indentation
return prev_line.indentation
if spec.less_for and spec.less_for.authoritive != false and line.indentation < prev_line.indentation
return prev_line.indentation
return prev_line.indentation if line.is_blank
alignment_adjustment = line.indentation % indent_level
line.indentation + alignment_adjustment
patterns_match: (text, patterns) =>
return false unless patterns
for p in *patterns
neg_match = nil
if typeof(p) == 'table'
p, neg_match = p[1], p[2]
match = text\umatch p
if text\umatch(p) and (not neg_match or not text\umatch neg_match)
return true
false
_comment_pair: =>
return unless @comment_syntax
prefix, suffix = @comment_syntax, ''
if type(@comment_syntax) == 'table'
{prefix, suffix} = @comment_syntax
prefix, suffix
-- Config variables
with config
.define
name: 'indentation_structure_threshold'
description: 'The indentation structure parsing will stop once this number of lines has been collected'
default: 10
type_of: 'number'
mode.register name: 'default', create: DefaultMode
DefaultMode
| 31.101322 | 110 | 0.667564 |
44052187b9852f3fdc8cea92a6936354476ef441 | 5,659 | unless RETURN
require'opeth.common.opname'
import deepcpy, isk from require'opeth.common.utils'
optbl = require'opeth.opeth.common.optbl'
inspect = require'inspect'
toint = math.tointeger
printer = require'opeth.bytecode.printer'
__ENV = deepcpy _ENV
switchmatch = (str, t) ->
for i = 1, #t, 2
if (type(t[i]) ~= "string") or type(t[i + 1]) ~= "function"
error "switchmatch failed"
matches = {str\match t[i]}
if #matches > 0
return t[i + 1] unpack matches
t.default! if t.default
COLOR = 93
CURRENT_COLOR = 96
coloring = (color, str) -> "\027[#{color}m#{str}\027[0m"
level_tostring = => (coloring COLOR, (table.concat ["[#{i}]=" for i in *@])) .. (coloring CURRENT_COLOR, "[$status]=> ")
initsrc = (fnblock) -> {pc: 0, reg: {}, src: fnblock}
class VMctrler
class VMCo
new: (co) => @co = coroutine.create co
status: => coroutine.status @co
resume: => coroutine.resume @co
new: (@fnblock, @filename = "(closure)", @src = (initsrc @fnblock), @levels = {}) =>
@vmco = @create_vm fnblock, @src
@indialogue = true
@bp = nil
run: =>
while @indialogue
@doprompt!
line = if l = io.read! then l else break
switchmatch line, {
"^bp%s+(%d+)%s*$", (pc) ->
@bp = toint pc
"^r%s*$", ->
while @vmco\resume!
if @bp and @bp == @src.pc + 1
print "breakpoint #{@bp}"
break
if @vmco\status! == "dead"
print "[#{@filename}: exited program]"
"^n%s*$", ->
if @vmco\status! == "dead"
print "[#{@filename}: exited program]"
else @vmco\resume!
"^d%s*$", -> print inspect @src
"^dp%s*$", -> printer.fnblock @fnblock, @filename
"^q%s*$", -> @indialogue = false
"^%s*$", ->
default: ->
io.write "command:\n",
"\tbp <pc>: set a breakpoint to <pc>\n",
"\tr: run the code. if the breakpoint is set, stop at <pc>\n",
"\tn: execute the next instruction\n",
"\td: dump the current register and PC\n",
"\tdp: dump the bytecode structure\n",
"\tq: quit\n"
}
@src
linestatus: => @vmco\status! == "dead" and "(dead)" or toint @src.pc + 1
doprompt: => io.write ((level_tostring @levels)\gsub "%$status", @linestatus!)
create_vm: (upreg = {}) =>
{:constant, :instruction, :upvalue, :prototype} = @fnblock
{:reg} = @src
getrk = (rk) ->
if isk rk
constant[-rk].val
else
reg[rk]
VMCo ->
_ENV = deepcpy __ENV
while @src.pc < #instruction
@src.pc += 1
ins = instruction[@src.pc]
{RA, RB, RC, op: opec} = ins
switch opec
when MOVE
reg[RA] = reg[RB]
when LOADK
reg[RA] = constant[RB + 1].val
when LOADKX
assert instruction[@src.pc + 1].op == EXTRAARG
reg[RA] = constant[(513 + instruction[@src.pc + 1][1]) % 256].val
@src.pc += 1
when LOADBOOL
reg[RA] = RB == 0
if RC != 0
@src.pc += 1
-- when LOADNIL
when GETUPVAL
reg[RA] = upreg[RB + 1]
when GETTABUP
reg[RA] = if upvalue[RB + 1].instack == 0
_ENV[constant[-RC].val]
when GETTABLE
reg[RA] = reg[RB][getrk RC]
when SETTABUP
_ENV[-RB] = constant[-RC]
when SETUPVAL
upreg[RA] = reg[RB]
when SETTABLE
reg[RA][getrk RB] = getrk RC
when NEWTABLE
reg[RA] = {}
when SELF
reg[RA + 1] = reg[RB]
reg[RA] = reg[RB][getrk RC]
when ADD, SUB, MUL, DIV, BAND, BOR, BXOR, SHL, SHR, MOD, IDIV, POW
reg[RA] = optbl[opec] (getrk RB), (getrk RC)
when UNM
reg[RA] = -reg[RB]
when BNOT
reg[RA] = ~ reg[RB]
when NOT
reg[RA] = not reg[RB]
when LEN
reg[RA] = #reg[RB]
when CONCAT
for r = RB, RC
reg[RA] ..= reg[r]
when JMP
@src.pc += RB
when EQ, LT, LE
@src.pc += 1 if (optbl[opec] (getrk RB), (getrk RC)) != RA
when TEST
@src.pc += 1 unless reg[RA]
when TESTSET
if reg[RB]
reg[RA] = reg[RB]
else
@src.pc += 1
when CALL
fn = reg[RA]
calllimit = RB == 0 and #reg or (RA + RB - 1)
retvals = if (type fn) == "table" and fn.regnum
with nreg = {}
for r = 0, calllimit - (RA + 1)
nreg[r] = reg[RA + 1 + r]
table.insert @levels, @src.pc
runnerfn = VMctrler fn, "inner closure", (initsrc fn), @levels
runnerfn\run!
table.remove @levels, #@levels
for i = 0, calllimit - (RA + 1)
nreg[r] = runnerfn.src.reg[i]
else {fn unpack reg, (RA + 1), calllimit}
retlimit = RC == 0 and #retvals or (RC - 2)
for r = RA, RA + retlimit
reg[r] = retvals[r - RA + 1]
when TAILCALL
fn = reg[RA]
return fn unpack reg, (RA + 1), (RA + RB - 1)
when RETURN
retlimit = switch RB
when 0 then #reg
when 1 then 0
else RB - 2
@src.reg = {unpack reg, RA, (RA + retlimit)}
reg = @src.reg
break
when FORLOOP
reg[RA] += reg[RA + 2]
if reg[RA] <= reg[RA + 1]
@src.pc += RB
reg[RA + 3] = reg[RA]
when FORPREP
reg[RA] -= reg[RA + 2]
@src.pc += RB
when TFORCALL
cb = RA + 3
reg[cb + 2] = reg[RA + 2]
reg[cb + 1] = reg[RA + 1]
reg[cb] = reg[RA]
fn = reg[cb]
retvals = {fn unpack reg, cb + 1, cb + RC}
table.move retvals, 1, RC, cb, reg
assert instruction[@src.pc + 1].op == TFORLOOP
when TFORLOOP
if reg[RA + 1]
reg[RA] = reg[RA + 1]
@src.pc += instruction[@src.pc][2]
when SETLIST
for i = 1, RB
reg[RA][RC - 1 + i] = reg[RA + i]
when CLOSURE
reg[RA] = prototype[RB + 1]
coroutine.yield!
reg
VMctrler
| 25.263393 | 120 | 0.530129 |
ed6f2b13fa89ec7a2e6a1e9c5f225b9f332adba5 | 2,022 | {
"unknown": -1
-- Alpha-numeric
"0": 7
"1": 8
"2": 9
"3": 10
"4": 11
"5": 12
"6": 13
"7": 14
"8": 15
"9": 16
"a": 29
"b": 30
"c": 31
"d": 32
"e": 33
"f": 34
"g": 35
"h": 36
"i": 37
"j": 38
"k": 39
"l": 40
"m": 41
"n": 42
"o": 43
"p": 44
"q": 45
"r": 46
"s": 47
"t": 48
"u": 49
"v": 50
"w": 51
"x": 52
"y": 53
"z": 54
-- Symbols
"*": 17
"#": 18
",": 55
".": 56
"`": 68
"-": 69
"=": 70
"[": 71
"]": 72
"\\": 73
";": 74
":": 243
"'": 75
"/": 76
"@": 77
"+": 81
-- Keypad
"kp0": 144
"kp1": 145
"kp2": 146
"kp3": 147
"kp4": 148
"kp5": 149
"kp6": 150
"kp7": 151
"kp8": 152
"kp9": 153
-- Function
"f1": 244
"f2": 245
"f3": 246
"f4": 247
"f5": 248
"f6": 249
"f7": 250
"f8": 251
"f9": 252
"f10": 253
"f11": 254
"f12": 255
-- Navigation
"up": 19
"down": 20
"left": 21
"right": 22
"center": 23
"end": 132
"pageup": 92
"pagedown": 93
-- Command
"insert": 133
"delete": 67
"backspace": 67
-- Gamepad
"btna": 96
"btnb": 97
"btnc": 98
"btnx": 99
"btny": 100
"btnz": 101
"btnl1": 102
"btnr1": 103
"btnl2": 104
"btnr2": 105
"btnthumbl": 106
"btnthumbr": 107
"btnstart": 108
"btnselect": 109
"btnmode": 110
-- D-pad
"dpup": 19
"dpdown": 20
"dpleft": 21
"dpright": 22
"dpcenter": 23
-- Special
"lalt": 57
"ralt": 58
"lshift": 59
"rshift": 60
"tab": 61
"space": 62
"lctrl": 129
"rctrl": 130
"escape": 131
"return": 66
-- Media
"volumeup": 24
"volumedown": 25
"pause": 85
"stop": 86
"next": 87
"prev": 88
"rewind": 89
"fastforward": 90
"mute": 91
-- Other
"sleft": 1
"sright": 2
"home": 3
"back": 4
"call": 5
"endcall": 6
"power": 26
"camera": 27
"menu": 82
"notification": 83
"search": 84
"clear": 28
"sym": 63
"www": 64
"mail": 65
"num": 78
"headsethook": 79
"focus": 80
"pictsymbols": 94
"charset": 95
"forwarddelete": 112
}
| 12.6375 | 22 | 0.450049 |
2effb671ebdcbe0435197df94c864dd7349751bd | 263 | export ^
class StateStack
-- General purpose class to handle multiple state in LOVE games
new: =>
@stack = {}
push: (state) =>
table.insert @stack, state
pop: =>
table.remove @stack
peek: =>
@stack[#@stack]
| 16.4375 | 67 | 0.543726 |
156e240beaab75ab81673b2f53960bc138414290 | 106 |
version = "0.2.6"
{
version: version,
print_version: ->
print "MoonScript version #{version}"
}
| 11.777778 | 41 | 0.622642 |
d03ce0b372eb9b1096f21cacbecdebfb054d2070 | 10,356 | -- Copyright 2012-2017 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import bundle from howl
import File from howl.io
describe 'bundle', ->
after_each ->
_G.bundles = {}
bundle.dirs = {}
with_bundle_dir = (name, f) ->
with_tmpdir (dir) ->
b_dir = dir / name
b_dir\mkdir!
status, err = pcall f, b_dir
error(err) unless status
mod_name = name\lower!\gsub '[%s%p]+', '_'
pcall(bundle.unload, mod_name) if _G.bundles[mod_name]
bundle_init = (info = {}, spec = {}) ->
ret = ''
ret ..= "#{spec.code}\n" if spec.code
mod = author: 'bundle_spec', description: 'spec_bundle', license: 'MIT'
mod[k] = v for k,v in pairs info
ret ..= 'return { info = {'
ret ..= table.concat [k .. '="' .. v .. '"' for k,v in pairs mod], ','
ret ..= '}, '
if spec.other_returns
ret ..= table.concat [k .. '="' .. tostring(v) .. '"' for k,v in pairs spec.other_returns], ','
if spec.unload
ret ..= "unload = #{spec.unload} }"
else
ret ..= 'unload = function() end }'
ret
describe 'load_from_dir(dir)', ->
it 'raises an error if dir is not a directory', ->
assert.raises 'directory', -> bundle.load_from_dir File '/not-a-directory'
it 'raises an error if the bundle init file is missing or incomplete', ->
with_tmpdir (dir) ->
assert.raises 'find file', -> bundle.load_from_dir dir
init = dir / 'init.lua'
init\touch!
assert.raises 'Incorrect bundle', -> bundle.load_from_dir dir
init.contents = 'return {}'
assert.raises 'info missing', -> bundle.load_from_dir dir
init.contents = 'return { info = {} }'
assert.raises 'missing info field', -> bundle.load_from_dir dir
it 'assigns the returned bundle table to bundles using the dir basename', ->
mod = author: 'bundle_spec', description: 'spec_bundle', license: 'MIT'
with_bundle_dir 'foo', (dir) ->
dir\join('init.lua').contents = bundle_init mod
bundle.load_from_dir dir
assert.same _G.bundles.foo.info, mod
assert.is_equal 'function', type _G.bundles.foo.unload
it 'massages the assigned module name to fit with naming standards if necessary', ->
with_bundle_dir 'Test-hello 2', (dir) ->
dir\join('init.lua').contents = bundle_init!
bundle.load_from_dir dir
assert.not_nil _G.bundles.test_hello_2
it 'does nothing if the bundle is already loaded', ->
with_bundle_dir 'two_times', (dir) ->
dir\join('init.lua').contents = bundle_init!
bundle.load_from_dir dir
bundle.load_from_dir dir
context 'exposed bundle helpers', ->
it 'bundle_file provides access to bundle files', ->
with_bundle_dir 'test', (dir) ->
dir\join('init.lua').contents = [[
local file = bundle_file('bundle_aux.lua')
return {
info = {
author = 'spec',
description = 'desc',
license = 'MIT',
},
unload = function() end,
file = file
}
]]
bundle.load_from_dir dir
assert.equal _G.bundles.test.file, dir / 'bundle_aux.lua'
describe 'provide_module(name, prefix = nil)', ->
it 'makes a sub directory available for loading globally with require', ->
with_bundle_dir 'test', (dir) ->
mod = dir\join('testmod')
mod\mkdir_p!
mod\join('init.moon').contents = '{root: true}'
mod\join('other.moon').contents = '{other: true}'
dir\join('init.lua').contents = bundle_init nil, {
code: 'provide_module("testmod")'
}
bundle.load_from_dir dir
assert.same {root: true}, require 'testmod'
assert.same {other: true}, require 'testmod.other'
describe 'require_bundle', ->
it 'ensures the required bundle is loaded before the dependent one', ->
with_tmpdir (dir) ->
bundle.dirs = {dir}
first_dir = dir\join('first')
first_dir\mkdir!
second_dir = dir\join('second')
second_dir\mkdir!
third_dir = dir\join('third')
third_dir\mkdir!
first_dir\join('init.lua').contents = bundle_init!
third_dir\join('init.lua').contents = bundle_init!
second_dir\join('init.lua').contents = bundle_init nil, {
code: 'require_bundle("third")\nrequire_bundle("first")'
}
bundle.load_from_dir second_dir
assert.is_not_nil _G.bundles.first
assert.is_not_nil _G.bundles.third
it 'detects cyclic dependencies', ->
with_tmpdir (dir) ->
bundle.dirs = {dir}
first_dir = dir\join('first')
first_dir\mkdir!
second_dir = dir\join('second')
second_dir\mkdir!
first_dir\join('init.lua').contents = bundle_init nil, {
code: 'require_bundle("second")'
}
second_dir\join('init.lua').contents = bundle_init nil, {
code: 'require_bundle("first")'
}
assert.raises 'Cyclic dependency', ->
bundle.load_from_dir second_dir
it 'raises an error upon implicit global writes', ->
with_tmpdir (dir) ->
dir\join('init.lua').contents = [[
file = bundle_file('bundle_aux.lua')
return {
info = {
author = 'spec',
description = 'desc',
license = 'MIT',
},
file = file
}
]]
assert.raises 'implicit global', -> bundle.load_from_dir dir
describe 'load_all()', ->
it 'loads all found bundles in all directories in bundle.dirs', ->
with_tmpdir (dir) ->
bundle.dirs = {dir}
for name in *{'foo', 'bar'}
b_dir = dir / name
b_dir\mkdir!
b_dir\join('init.lua').contents = bundle_init :name
bundle.load_all!
assert.not_nil _G.bundles.foo
assert.not_nil _G.bundles.bar
it 'skips any hidden entries', ->
with_tmpdir (dir) ->
bundle.dirs = {dir}
b_dir = dir / '.hidden'
b_dir\mkdir!
b_dir\join('init.lua').contents = bundle_init name: 'hidden'
bundle.load_all!
assert.same [name for name, _ in pairs _G.bundles], {}
it 'raises an error if bundle names conflict', ->
with_tmpdir (dir) ->
for name in *{'foo', 'bar'}
b_dir = dir / name / 'my_bundle'
b_dir\mkdir_p!
b_dir\join('init.lua').contents = bundle_init :name
bundle.dirs = {dir\join('foo'), dir\join('bar')}
assert.raises 'conflict', -> bundle.load_all!
describe 'load_by_name(name)', ->
it 'loads the bundle with the specified name, if not already loaded', ->
with_tmpdir (dir) ->
bundle.dirs = {dir}
b_dir = dir / 'named'
b_dir\mkdir!
b_dir\join('init.lua').contents = bundle_init name: 'named'
bundle.load_by_name 'named'
assert.not_nil _G.bundles.named
-- should be a no-op
bundle.load_by_name 'named'
it 'raises an error if the bundle could not be found', ->
assert.raises 'not found', -> bundle.load_by_name 'oh_bundle_where_art_thouh'
describe 'unload(name)', ->
it 'raises an error if no bundle with the given name exists', ->
assert.raises 'not found', -> bundle.unload 'serenity'
context 'for an existing bundle', ->
mod = name: 'bunny'
it 'calls the bundle unload function and removes the bundle from _G.bundles', ->
with_bundle_dir 'bunny', (dir) ->
dir\join('init.lua').contents = bundle_init mod, unload: 'function() _G.bunny_bundle_unload = true end'
bundle.load_from_dir dir
bundle.unload 'bunny'
assert.is_true _G.bunny_bundle_unload
assert.is_nil _G.bundles.bunny
it 'returns early with an error if the unload function raises an error', ->
with_bundle_dir 'bad_seed', (dir) ->
dir\join('init.lua').contents = bundle_init mod, unload: 'function() error("barf!") end'
bundle.load_from_dir dir
assert.raises 'barf!', -> bundle.unload 'bad_seed'
assert.is_not_nil _G.bundles.bad_seed
it 'transforms the given name to match the module name', ->
with_bundle_dir 'dash-love', (dir) ->
dir\join('init.lua').contents = bundle_init name: 'dash-love'
bundle.load_from_dir dir
assert.no_error -> bundle.unload 'dash-love'
it 'removes any references to provided modules', ->
with_bundle_dir 'test', (dir) ->
mod = dir\join('testmod')
mod\mkdir_p!
mod\join('init.moon').contents = '{root: true}'
mod\join('other.moon').contents = '{other: true}'
dir\join('init.lua').contents = bundle_init nil, {
code: 'provide_module("testmod")'
}
bundle.load_from_dir dir
assert.same {root: true}, require 'testmod'
assert.same {other: true}, require 'testmod.other'
bundle.unload 'test'
assert.is_false pcall require, 'testmod'
assert.is_false pcall require, 'testmod.other'
describe 'from_file(file)', ->
it 'returns the adjusted name of the containing bundle if any', ->
with_tmpdir (dir) ->
bundle.dirs = {dir}
b_dir = dir / 'my-bundle'
init = b_dir\join('init.lua')
assert.equal 'my_bundle', bundle.from_file(init)
assert.is_nil bundle.from_file(File('/bin/ls'))
assert.is_nil bundle.from_file(dir\join('directly_under_root'))
it '.unloaded holds the adjusted names of any unloaded bundles', ->
with_tmpdir (dir) ->
bundle.dirs = {dir}
for name in *{'foo-bar', 'frob_nic'}
b_dir = dir / name
b_dir\mkdir!
b_dir\join('init.lua').contents = bundle_init :name
assert.same { 'foo_bar', 'frob_nic' }, bundle.unloaded
bundle.load_by_name 'foo_bar'
assert.same { 'frob_nic' }, bundle.unloaded
bundle.unload 'foo_bar'
assert.same { 'foo_bar', 'frob_nic' }, bundle.unloaded
| 36.985714 | 113 | 0.582464 |
52406bd1f098f2a76f3daa3fd3862dcc2fc1d85b | 3,395 | require "grid"
require "gridview"
require "game"
require "level"
require "state"
helper = require "helper"
export ^
makeMenuGrid = ->
require("patterns")
g = Grid 20
g\set_stepTime 0.5
g\placePattern patterns.noahsark, 20, 15
g\start_simulation!
return g
class BoundingBox
new: (@x, @y, @w, @h) =>
test: (x, y) =>
-- return true if x,y is in boundingBox
xTest = @x <= x and x <= @x + @w
yTest = @y <= y and y <= @y + @h
return xTest and yTest
class Menu extends State
new: =>
@grid = makeMenuGrid!
@view = GridView @grid, wScr!, hScr!
@view\setScale 2
@fontBig = love.graphics.newFont "res/font/GreatVibes-Regular.otf", 80
@fontMed = love.graphics.newFont "res/font/GreatVibes-Regular.otf", 60
@fontSma = love.graphics.newFont "res/font/Inconsolata.otf", 20
resources.bgm_menu\play!
@colorUnselected = {0, 0, 0}
@colorSelected = {189, 252, 201} -- mint
@text = {}
table.insert @text, "Start Game"
table.insert @text, "Level Selection"
table.insert @text, "Sandbox Mode"
table.insert @text, "Quit Game"
@textBoundBox = {}
for i=1,#@text
table.insert @textBoundBox, BoundingBox wScr!/4 - 150,
hScr!/3 + (i-1) * 100 - 50,
350, 100
@selected = 0
update: (dt) =>
@grid\update dt
mX, mY = love.mouse.getX!, love.mouse.getY!
debagel\monitor "mouse", "#{mX} #{mY}"
for i=1,#@text
if @textBoundBox[i]\test mX, mY
if @selected ~= i
@selected = i
debagel\monitor "selected", @selected
draw: =>
@view\draw!
love.graphics.setFont @fontBig
love.graphics.printf "Game of Löve",
wScr! / 2, 10, wScr! / 2 - 10, "right"
love.graphics.setFont(@fontMed)
for i=1,#@text
bb = @textBoundBox[i]
x, y, w, h = bb.x, bb.y, bb.w, bb.h
if i == @selected
love.graphics.setColor {0, 0, 0, 100}
love.graphics.rectangle("fill", x, y, w, h)
love.graphics.setColor if i == @selected then @colorSelected else @colorUnselected
love.graphics.printf @text[i], x, y + 5, w, "center"
love.graphics.setColor {0, 0, 0}
love.graphics.setFont @fontSma
love.graphics.printf "A game by Altom",
3 * wScr! / 4, hScr! - 30, wScr! / 4 - 10, "right"
mousereleased: (x, y) =>
@itemSelected @selected
keyreleased: (key) =>
switch key
when "up"
@selected = helper.modulo_lua @selected - 1, #@text
when "down"
@selected = helper.modulo_lua @selected + 1, #@text
when "return"
@itemSelected @selected
when "escape"
love.event.quit!
itemSelected: (selected) =>
command = @text[selected]
switch command
when "Start Game"
return -- TODO
when "Level Selection"
return -- TODO
when "Sandbox Mode"
resources.bgm_menu\stop!
resources.bgm_sandbox\play!
statestack\push Game makeSandboxLevel!
when "Quit Game"
love.event.quit!
| 30.863636 | 94 | 0.526657 |
84e61c5024073e46f594067ce36eadc3c3f36a62 | 297 | tokenList = zb2rharZc7GhmUrL3oaZbDaqrpSh1Z6Efc4NVzaCPdPNkZ7Po
arrayFoldr = zb2rhbTuYiZm5fGUHUhd3sQNRDhEW6FVjXLp8UyWk5hE9nQ5F
symbol =>
match = token => (cmp (get token "symbol") symbol)
(arrayFoldr
token => result => (if (match token) token result)
(get tokenList "0")
tokenList)
| 29.7 | 62 | 0.747475 |
5428bdf1f8ff9a47f7deb59e24b77732e454f3da | 115 | export class Spire extends Sprite
new: (x, y) =>
super x, y, "resource/spire.png"
@height = 8
@offset.y = 8 | 19.166667 | 34 | 0.626087 |
1c4107ee8992c1aa51f15b68031ea92010b53255 | 371 | core = require 'ljglibs.core'
require 'ljglibs.cdefs.gobject'
ffi = require 'ffi'
C = ffi.C
core.auto_loading 'gobject', {
gc_ptr: (o) ->
return nil if o == nil
if C.g_object_is_floating(o) != 0
C.g_object_ref_sink(o)
ffi.gc(o, C.g_object_unref)
ref_ptr: (o) ->
return nil if o == nil
C.g_object_ref o
ffi.gc(o, C.g_object_unref)
}
| 17.666667 | 37 | 0.630728 |
826f82f699bf9183fd7c47ba138e696b36b42876 | 730 | [[
joli-lune
small framework for love2d
MIT License (see licence file)
]]
System = require "src.systems.system"
class Position extends System
__tostring: => return "position"
onCreate: (x=0,y=0,z=0,r=0,sx=1,sy=1,ox=0,oy=0) =>
@x,@y,@z,@r,@scalex,@scaley,@originx,@originy=x,y,z,r,sx,sy,ox,oy
@oldz = @z
get: => @x+@originx+(@shakex or 0),@y+@originy+(@shakey or 0),@z,@r,@scalex,@scaley
scale: (x=1,y=x) => @scalex,@scaley = x,y
move: (x,y) =>
collider = @entity.collider
oldx,oldy = x,y
if collider
x,y = collider\move(x,y)
@x,@y = x, y
if oldx ~= @x and oldy ~= @y
return true
else
return false
update: (dt) =>
if @oldz ~= @z
@entity.scene\sortEntities!
@old = @z
return Position | 19.72973 | 84 | 0.612329 |
ef416606dec23ccdad1f77a7d477b941e9df0f61 | 11,439 | -- Copyright 2016 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:activities, :app, :bindings, :command, :config, :inspection, :interact, :log, :signal, :timer} = howl
{:ActionBuffer, :BufferPopup, :highlight} = howl.ui
{:Process, :process_output} = howl.io
{:pcall} = _G
{:sort} = table
append = table.insert
local popup, last_display_position
unavailable_warnings = {}
update_inspections_display = (editor) ->
text = ''
count = #editor.buffer.markers\find(name: 'inspection')
if count > 0
keys = bindings.keystrokes_for 'cursor-goto-inspection', 'editor'
access = #keys > 0 and keys[1] or 'cursor-goto-inspection'
text = "(#{count} inspection#{count > 1 and 's' or ''} - #{access} to view)"
editor.indicator.inspections.text = text
resolve_inspector = (name, inspector, buffer) ->
if inspector.is_available
available, msg = inspector.is_available(buffer)
unless available
unless unavailable_warnings[name]
log.warning "Inspector '#{name}' unavailable: #{msg}"
unavailable_warnings[name] = true
return nil
return inspector unless inspector.cmd\find '<file>', 1, true
return nil if not buffer.file or buffer.modified
copy = {k,v for k, v in pairs inspector}
copy.cmd = copy.cmd\gsub '<file>', buffer.file.path
copy.write_stdin = false
copy
load_inspectors = (buffer, scope = 'idle') ->
to_load = if scope == 'all'
{'inspectors_on_idle', 'inspectors_on_save'}
else
{"inspectors_on_#{scope}"}
inspectors = {}
for variable in *to_load
for inspector in *buffer.config[variable]
conf = inspection[inspector]
if conf
instance = conf.factory buffer
unless callable(instance)
if type(instance) == 'string'
instance = resolve_inspector inspector, {cmd: instance}, buffer
elseif type(instance) == 'table'
unless instance.cmd
error "Missing cmd key for inspector returned for '#{inspector}'"
instance = resolve_inspector inspector, instance, buffer
if instance
append inspectors, instance
else
log.warn "Invalid inspector '#{inspector}' specified for '#{buffer.title}'"
inspectors
merge = (found, criticisms) ->
for c in *found
l_nr = c.line
criticisms[l_nr] or= {}
append criticisms[l_nr], {
message: c.message,
type: c.type,
search: c.search,
start_col: c.start_col,
end_col: c.end_col,
byte_start_col: c.byte_start_col,
byte_end_col: c.byte_end_col,
}
get_line_segment = (line, criticism) ->
start_col = criticism.start_col
end_col = criticism.end_col
line_text = nil
if not start_col and criticism.byte_start_col
line_text or= line.text
start_col = line_text\char_offset criticism.byte_start_col
if not end_col and criticism.byte_end_col
line_text or= line.text
end_col = line_text\char_offset criticism.byte_end_col
if not (start_col and end_col) and criticism.search
p = r"\\b#{r.escape(criticism.search)}\\b"
line_text or= line.text
s, e = line_text\ufind p, start_col or 1
if s
unless line\ufind p, s + 1
start_col = s
end_col = e + 1
if not start_col and not line.is_empty
start_col = 1 + line.indentation
-- check spec coverage end_pos
start_pos = start_col and line.start_pos + start_col - 1 or line.start_pos
end_pos = end_col and line.start_pos + end_col - 1 or line.end_pos
start_pos, end_pos
mark_criticisms = (buffer, criticisms) ->
{:lines, :markers} = buffer
ms = {}
line_nrs = [nr for nr in pairs criticisms]
sort line_nrs
for nr in *line_nrs
line = lines[nr]
list = criticisms[nr]
continue unless line and #list > 0
for c in *list
start_pos, end_pos = get_line_segment line, c
ms[#ms + 1] = {
name: 'inspection',
flair: c.type or 'error',
start_offset: start_pos,
end_offset: end_pos
message: c.message
}
if #ms > 0
markers\add ms
return #ms
parse_errors = (out, inspector) ->
if inspector.parse
return inspector.parse out
inspections = {}
for loc in *process_output.parse(out)
complaint = {
line: loc.line_nr,
message: loc.message,
}
if loc.tokens
complaint.search = loc.tokens[1]
complaint.type = inspector.type or loc.message\umatch(r'^(warning|error)')
append inspections, complaint
if inspector.post_parse
inspector.post_parse inspections
inspections
launch_inspector_process = (opts, buffer) ->
write_stdin = true unless opts.write_stdin == false
p = Process {
cmd: opts.cmd,
read_stdout: true,
read_stderr: true,
write_stdin: write_stdin
env: opts.env,
shell: opts.shell,
working_directory: opts.working_directory
}
if write_stdin
p.stdin\write buffer.text
p.stdin\close!
p
inspect = (buffer, opts = {}) ->
criticisms = {}
processes = {}
inspector_scope = opts.scope or 'all'
for inspector in *load_inspectors(buffer, inspector_scope)
if callable(inspector)
status, ret = pcall inspector, buffer
if status
merge(ret or {}, criticisms)
else
log.error "inspector '#{inspector}' failed: #{ret}"
else
p = launch_inspector_process inspector, buffer
processes[#processes + 1] = { process: p, :inspector }
-- finish off processes
for p in *processes
out, err = activities.run_process {title: 'Reading inspection results'}, p.process
buf = out
buf ..= "\n#{err}" unless err.is_blank
inspections = parse_errors buf, p.inspector
merge(inspections, criticisms)
criticisms
criticize = (buffer, criticisms, opts = {}) ->
criticisms or= inspect buffer
if opts.clear
buffer.markers\remove name: 'inspection'
mark_criticisms buffer, criticisms
update_buffer = (buffer, editor, scope) ->
return if buffer.read_only
return if buffer.data.is_preview
data = buffer.data
if data.last_inspect
li = data.last_inspect
if scope == 'idle' and li.ts >= buffer.last_changed
return
-- we mark this automatic inspection run with a serial
update_serial = (data.inspections_update or 0) + 1
data.inspections_update = update_serial
criticisms = inspect buffer, :scope
-- check serial to avoid applying out-of-date criticisms
unless data.inspections_update == update_serial
log.warn "Ignoring stale inspection update - slow inspection processes?"
return
criticize buffer, criticisms
buffer.data.last_inspect = ts: buffer.last_changed, :scope
editor or= app\editor_for_buffer buffer
if editor
update_inspections_display editor
show_popup = (editor, inspections, pos) ->
popup or= BufferPopup ActionBuffer!
buf = popup.buffer
buf\as_one_undo ->
buf.text = ''
prefix = #inspections > 1 and '- ' or ''
for i = 1, #inspections
buf\append "#{prefix}#{inspections[i].message}", inspections[i].type
unless i == #inspections
buf\append "\n"
with popup.view
.cursor.line = 1
.base_x = 0
editor\show_popup popup, {
position: pos,
keep_alive: true,
}
display_inspections = ->
timer.on_idle (config.display_inspections_delay / 1000), display_inspections
editor = app.editor
return unless editor.has_focus
pos = editor.view.cursor.pos
-- if we've already displayed the message at this position, punt
return if pos == last_display_position
a_markers = editor.buffer.markers.markers
markers = a_markers\at pos
if #markers == 0 and pos > 1
markers = a_markers\at pos - 1
markers = [{message: m.message, type: m.flair} for m in *markers when m.message]
if #markers > 0
last_display_position = pos
show_popup editor, markers, editor.cursor.pos
on_idle = ->
timer.on_idle 0.5, on_idle
editor = app.editor
-- if there's a popup open already of any sorts, don't interfere
return if editor.popup
b = editor.buffer
if b.config.auto_inspect == 'on'
if b.size < 1024 * 1024 * 5 -- 5 MB
update_buffer b, editor, 'idle'
signal.connect 'buffer-modified', (args) ->
with args.buffer
.markers\remove name: 'inspection'
editor = app\editor_for_buffer args.buffer
if editor
editor.indicator.inspections.text = ''
signal.connect 'buffer-saved', (args) ->
b = args.buffer
return unless b.size < 1024 * 1024 * 5 -- 5 MB
return if b.config.auto_inspect == 'off'
-- what to load? if config says 'save', all, otherwise save inspectors
-- but if the idle hasn't had a chance to run we also run all
scope = if b.config.auto_inspect == 'save_only'
'all'
elseif b.data.last_inspect and b.data.last_inspect.ts < b.last_changed
'all'
else
'save'
update_buffer b, nil, scope
signal.connect 'after-buffer-switch', (args) ->
update_inspections_display args.editor
signal.connect 'preview-opened', (args) ->
args.editor.indicator.inspections.text = ''
signal.connect 'preview-closed', (args) ->
update_inspections_display args.editor
signal.connect 'cursor-changed', (args) ->
last_display_position = nil
signal.connect 'editor-defocused', (args) ->
last_display_position = nil
signal.connect 'app-ready', (args) ->
timer.on_idle 0.5, on_idle
timer.on_idle (config.display_inspections_delay / 1000), display_inspections
highlight.define_default 'error',
type: highlight.WAVY_UNDERLINE
foreground: 'red'
line_width: 1
line_type: 'solid'
highlight.define_default 'warning',
type: highlight.WAVY_UNDERLINE
foreground: 'orange'
line_width: 1
line_type: 'solid'
command.register
name: 'buffer-inspect'
description: 'Inspects the current buffer for abberations'
handler: ->
buffer = app.editor.buffer
criticize buffer
editor or= app\editor_for_buffer buffer
if editor
update_inspections_display editor
command.register
name: 'cursor-goto-inspection'
description: 'Goes to a specific inspection in the current buffer'
input: ->
editor = app.editor
buffer = editor.buffer
inspections = buffer.markers\find(name: 'inspection')
unless #inspections > 0
log.info "No inspections for the current buffer"
return nil
last_line = 0
items = {}
pbuf = howl.ui.ActionBuffer!
popup = howl.ui.BufferPopup pbuf
for i in *inspections
l = buffer.lines\at_pos i.start_offset
item = items[#items]
if l.nr != last_line
item = {
tostring(l.nr),
l.chunk,
:buffer,
line_nr: l.nr,
inspections: {},
highlights: {},
offset: i.start_offset
}
append item.inspections, {
message: i.message,
type: i.flair,
}
append item.highlights, {
start_pos: i.start_offset,
end_pos: i.end_offset
}
if l.nr != last_line
append items, item
last_line = l.nr
on_change = (selection) ->
show_popup editor, selection.inspections, selection.offset
return interact.select_location
title: "Inspections in #{buffer.title}"
editor: editor
items: items,
force_preview: true
selection: items[1]
:on_change
handler: (res) ->
if res
app.editor.cursor.pos = res.selection.offset
hl = res.selection.highlights[1]
app.editor\highlight start_pos: hl.start_pos, end_pos: hl.end_pos
:inspect, :criticize
| 27.106635 | 103 | 0.672174 |
75faf4f94d0a2c419668808af1e8b1fa4abe23ae | 2,042 | random = require 'lqc.random'
r = require 'lqc.report'
command = require 'lqc.fsm.command'
fsm = require 'lqc.fsm'
state = require 'lqc.fsm.state'
lqc = require 'lqc.quickcheck'
lqc_gen = require 'lqc.lqc_gen'
frequency = lqc_gen.frequency
oneof = lqc_gen.oneof
elements = lqc_gen.elements
do_setup = ->
random.seed!
lqc.init 100, 100
lqc.properties = {}
r.report = ->
-- 'example code to test':
new_counter = ->
Counter =
x: 0
add: (y) => @x += y
value: => @x
reset: => @x = 0
Counter
ctr = new_counter!
counter_add = (x) -> ctr\add(x)
counter_reset = -> ctr\reset!
-- FSM specification:
describe 'statemachine specification', ->
before_each(do_setup)
it 'should be possible to define a FSM', ->
r.report_success = spy.new(r.report_success)
fsm 'counter'
commands: (state) ->
-- NOTE: conditional commands can be added with an if, ... before returning list
frequency {
{ 1, command.stop },
{ 10, oneof {
command { 'increment', counter_add, { elements { 1, 2, 3 } } },
command { 'reset', counter_reset, {} }
} }
}
initial_state: -> 0
states: {
state 'increment'
precondition: (state, args) -> -- args are in a table!
true -- always allowed
next_state: (state, value, args) -> -- called after applying command from commands function
state + args[1]
postcondition: (state, result, args) -> -- result is actual value returned by command
ctr\value! == state + args[1]
state 'reset'
precondition: (state, args) -> true
next_state: (state, value, args) -> 0,
postcondition: (state, result, args) -> ctr\value! == 0
}
cleanup: (state) -> ctr = new_counter!
when_fail: (history, state, result) ->
print action\to_string! for action in *history
assert.equal(1, #lqc.properties)
lqc.check()
assert.spy(r.report_success).was.called(lqc.numtests)
| 27.226667 | 102 | 0.591087 |
63f504922f66ceb0db8d9802580111fea8addd27 | 221 | #!/usr/bin/env moon
buildah = require"buildah".from "docker://gcr.io/distroless/static", "pwndrop"
COPY "pwndrop"
COPY "admin"
WIPE "directories"
ENTRYPOINT "/pwndrop"
PUSH "pwndrop", "1.0.1"
| 27.625 | 78 | 0.624434 |
154430281a2b7a4d5149603bd0aefc90280bd1ff | 901 | require "tests/init"
describe "Translation completeness check", ->
english = ulx.Lang "english"
allLangs = ulx.Directory.GetFiles "locale", "*.json", true
allLangs = [ulx.Path.GetFileNameWithoutExtension(path) for path in *allLangs]
allLangs = ulx.TableX.RemoveDuplicateValues( allLangs )
allLangsButEnglish = [lang for lang in *allLangs when lang ~= "english"]
it "ensures other languages have all phrases included in English", ->
messageAccum = ""
basePhrases = english.Phrases
for lang in *allLangsButEnglish
langInstance = ulx.Lang lang
langPhrases = langInstance.Phrases
diff = ulx.TableX.DifferenceByKey basePhrases, langPhrases
diff = [k for k, v in pairs(diff)]
if #diff > 0
messageAccum ..= "\nLanguage '#{lang}' does not contain the following phrases:\n#{table.concat(diff, "\n")}\n\n"
if #messageAccum > 0
assert false, messageAccum
return
return
| 34.653846 | 116 | 0.72586 |
3f08deaa02626b336d93d0f0477d844ec5c6bb7b | 2,398 |
lfs = require "lfs"
json = require "cjson"
DIRS = {
"locales/"
"locales/documents/"
"locales/tags/"
}
SOURCE_LOCALE = "en"
import types from require "tableshape"
flatten_nested = (t, prefix="", out={}) ->
for k,v in pairs t
if type(v) == "table"
flatten_nested v, "#{prefix}#{k}.", out
else
out["#{prefix}#{k}"] = v
out
each_translation_file = (fn) ->
for dir in *DIRS
local source_texts
rows = for file in assert lfs.dir dir
continue if file\match "^%.+$"
name = file\match "^([%w_-]+).json$"
continue unless name
handle = assert io.open "#{dir}/#{file}"
contents = assert handle\read "*a"
contents = flatten_nested json.decode contents
if name == SOURCE_LOCALE
assert not source_texts, "duplicate source texts"
source_texts = contents
{ dir, name, contents}
for r in *rows
args = {unpack r}
table.insert args, source_texts
fn unpack args
import parse_tags from require "helpers.compiler"
import find_variables from require "helpers.code_gen"
describe "parses", ->
each_translation_file (dir, name, strings, source_strings) ->
describe "#{dir} #{name}", ->
for key, text in pairs strings
it "#{key}", ->
syntax = parse_tags\match(text)
unless syntax
error "failed to parse:\n#{text}"
return if strings == source_strings
-- is it included in source text?
singular_key = key\gsub("_%d+$", "")\gsub("_plural$", "")
source_text = source_strings[singular_key] or source_strings[singular_key.."_plural"]
unless source_text
error "extra key '#{key}':\n#{text}"
-- see if the variables match
source_variables = find_variables parse_tags\match source_text
expected_variables = types.equivalent source_variables
unless expected_variables find_variables syntax
ignore_error = types.shape {
name: types.one_of { "pt_PT" }
source: types.shape {
count: "simple"
}
syntax: types.shape {}
}
unless ignore_error {
:name
source: source_variables
syntax: find_variables syntax
}
error "variables do not match:\n#{source_text}\n#{text}"
| 26.065217 | 95 | 0.585488 |
1b44d68eea0267c38123dd37243a059d7156c11f | 3,316 | lapis = require "lapis"
db = require "lapis.db"
date = require "date"
i18n = require "i18n"
import to_json from require "lapis.util"
import
capture_errors
assert_error
respond_to
from require "lapis.application"
import
error_404
error_500
assert_csrf_token
error_bad_request
from require "utils"
import
UserFollowings
Resources
ResourceAdmins
ResourceScreenshots
Comments
Users
from require "models"
class UserApplication extends lapis.Application
path: "/user"
name: "user."
@before_filter =>
-- try to find the user by username
@user = Users\find [db.raw "lower(slug)"]: @params.username\lower!
-- throw a 404 if it doesn't exist
unless @user
return @write error_404 @
-- get (or create if it doesn't exist) userdata
@data = @user\get_userdata!
@data = @user\create_userdata! unless @data
[profile: "/:username"]: capture_errors {
on_error: error_404
=>
if @active_user
-- get following state
@isFollowing = @active_user\is_following @user
tab = @params.tab
accessed = false -- use this to detect if tab is resources or not
if tab == "followers"
@followers = @user\get_followers "users.*, user_followings.created_at as followed_at"
@followers_count = #@followers
accessed = true
else
@followers_count = UserFollowings\count "following = ?", @user.id
if tab == "following"
@following = @user\get_following "users.*, user_followings.created_at as followed_at"
@following_count = #@following
accessed = true
else
@following_count = UserFollowings\count "follower = ?", @user.id
if tab == "screenshots"
@screenshots = @user\get_screenshots!
Resources\include_in @screenshots, "resource", as: "resource"
@screenshots_count = #@screenshots
accessed = true
else
@screenshots_count = ResourceScreenshots\count "uploader = ?", @user.id
if tab == "comments"
@comments = @user\get_comments!
Users\include_in @comments, "author", as: "author"
@comments_count = #@comments
accessed = true
else
@comments_count = Comments\count "author = ?", @user.id
if accessed
@resources_count = (Resources\count "creator = ?", @user.id) + (ResourceAdmins\count "\"user\" = ?", @user.id)
else
@resources = @user\get_resources!
@resources_count = #@resources
render: true
}
[follow: "/:username/follow"]: capture_errors respond_to
on_error: error_500
before: =>
if @active_user.id == @user.id
@write error_bad_request @, i18n "users.errors.cannot_follow_self"
@isFollowing = @active_user\is_following @user
GET: => render: true
POST: capture_errors =>
assert_csrf_token @
if @params.intent == "follow"
if @isFollowing
return error_bad_request @, i18n "users.errors.already_following"
UserFollowings\create {follower: @active_user.id, following: @user.id}
elseif @params.intent == "unfollow"
unless @isFollowing
return error_bad_request @, i18n "users.errors.not_currently_following"
uf = UserFollowings\find {follower: @active_user.id, following: @user.id}
uf\delete! if uf
redirect_to: @url_for "user.profile", (username: @user.slug), (tab: @params.tab)
| 27.404959 | 115 | 0.670989 |
35b23f1b223054a4c4fff9f2a5a2cc4e6882ab1d | 1,531 | export modinfo = {
type: "function"
id: "ParseAsset"
func: (id) ->
if not id
error("id not provided")
if type(id) ~= "string"
id = tostring(id)
if not id
error("tostring failed")
if string.sub(id, 1, 11) == "rbxasset://"
return id --leave it alone
elseif string.sub(id, 1, 13) == "rbxassetid://"
return id --leave it alone
elseif string.sub(id, 1, 10) == "rbxhttp://"
return id --leave it alone
elseif string.sub(id, 1, 7) == "http://"
return id --leave it alone
elseif string.sub(id, 1, 8) == "https://"
return id --leave it alone
elseif string.sub(id, 1, 18) == "rbxthumb420x420://"
return ParseAsset(("rbxhttp://Thumbs%sAsset.ashx?assetId=%s&imageFormat=png&width=420&height=420")\format(string.rep("/", 1e4), string.sub(id, 19)))
elseif string.sub(id, 1, 18) == "rbxvhumb420x420://"
return ParseAsset(("rbxhttp://Game%sTools/ThumbnailAsset.ashx?assetVersionId=%u&fmt=png&wd=420&ht=420")\format(string.rep("/", 1e4), string.sub(id, 19)))
elseif string.sub(id, 1, 15) == "rbxassethash://"
hash = string.sub(id, 16)
if #hash ~= 32
error("invalid hash length")
id = string.format("%s%sAsset?hash=%s", RobloxWebsite, string.rep("/", 1e4), hash) --Add more slashes so it's harder to get the asset
return id
elseif #id == 32 --this is a hash
id = string.format("%s%sAsset?hash=%s", RobloxWebsite, string.rep("/", 1e4), id)
return id
elseif tonumber(id)
id = string.format("rbxassetid://%u", id)
return id
else
error("invalid asset")
}
| 36.452381 | 156 | 0.636185 |
ca0f307c4d9ab9e61abc505840450697029eb2bf | 3,682 | require "globals"
describe "globals", ->
it "string.split splits on separator", ->
str = "a,b,c"
assert.same {"a","b","c"}, str\split(",")
it "string.split preserves empty 'items'", ->
str = "a,b,,c"
assert.same {"a","b","","c"}, str\split(",")
it "string.split splits by reserved pattern operator", ->
str = "a.b..c"
assert.same {"a","b","","c"}, str\split(".")
it "string.split splits by character", ->
str = "abcd"
assert.same {"a","b","c","d"}, str\split!
assert.same {"a","b","c","d"}, str\split ''
it "string.trim removes leading and trailing whitespace", ->
str1 = " leading"
str2 = "trailing "
str3 = " leading and trailing "
assert.same "leading", str1\trim!
assert.same "trailing", str2\trim!
assert.same "leading and trailing", str3\trim!
it "table.merge merges two tables", ->
t1 = {a: 1, b: 2}
t2 = {c: 3, a: 4}
assert.same {a:4, b:2, c:3}, table.merge(t1, t2)
it "table.index_of returns the index of value or nil if missing", ->
t = {"one", "two", "three", "four"}
assert.equal 3, table.index_of(t, "three")
assert.nil table.index_of(t, "five")
it "table.clear clears an indexed table", ->
t = {"one", "two", "three", "four"}
table.clear t
assert.same {}, t
it "table.clear clears a key/value table", ->
t = {one: 1, two: 2, three: 3, four: 4}
table.clear t
assert.same {}, t
it "math.round rounds to nearest integer by default", ->
num = 11.6
assert.equal 12, math.round(num)
it "math.round rounds to nearest number by supplied number of decimal digits", ->
num = 11.667
assert.equal 11.67, math.round(num, 2)
assert.equal 11.7, math.round(num, 1)
it "take_while takes until given function returns false", ->
t = {0,2,5,8,8.1,9,11,16}
upto_eight = take_while (item) -> item != 8.1
nt = [a for a in *t when upto_eight(a)]
assert.same {0,2,5,8}, nt
it "drop_while drops items until given function returns false", ->
t = {0,2,5,8,8.1,9,11,16}
t = {'drop', 'drop', 'take', 'drop', 'drop'}
drop_drops = drop_while (item) -> item == 'drop'
nt = [a for a in *t when drop_drops(a)]
assert.same {'take', 'drop', 'drop'}, nt
describe "getting/changing directory", ->
local cwd
before_each ->
p = io.popen("pwd")
if p
cwd = p\read!
p\close!
else
error "Couldn't open pipe for reading from command 'pwd'"
after_each ->
chdir(cwd)
it "getcwd gets the current working directory", ->
assert.same cwd, getcwd!
it "chdir changes working directory", ->
cwd = getcwd!
assert.true chdir("#{cwd}/lib")
assert.same "#{cwd}/lib", getcwd!
it "chdir returns nil when changing dir fails", ->
cwd = getcwd!
assert.nil chdir("#{cwd}/no-such-directory")
assert.same cwd, getcwd!
describe "chdir takes a function", ->
it "function is executed after switching directory", ->
cwd = getcwd!
success, r1, r2 = chdir "#{cwd}/lib", (chdir_successful) ->
assert.true chdir_successful
assert.same "#{cwd}/lib", getcwd!
123, 345
assert.true success
assert.equal 123, r1
assert.equal 345, r2
assert.same cwd, getcwd!
it "function receives success status of chdir", ->
cwd = getcwd!
success, r1, r2 = chdir "#{cwd}/failing-doesnt-exist", (chdir_successful) ->
assert.nil chdir_successful
assert.same cwd, getcwd!
123, 345
assert.nil success
assert.equal 123, r1
assert.equal 345, r2
assert.same cwd, getcwd!
| 30.429752 | 84 | 0.582835 |
13a9a2cbf9c82a47d50713d3b0726b68dbad20a7 | 5,938 |
util = require "lapis.util"
json = require "cjson"
tests = {
{
-> util.parse_query_string "field1=value1&field2=value2&field3=value3"
{
{"field1", "value1"}
{"field2", "value2"}
{"field3", "value3"}
field1: "value1"
field2: "value2"
field3: "value3"
}
}
{
-> util.parse_query_string "blahblah"
{
{ "blahblah"}
blahblah: true
}
}
{
-> util.parse_query_string "hello=wo%22rld&thing"
{
{ "hello", 'wo"rld' }
{ "thing" }
hello: 'wo"rld'
thing: true
}
}
{
-> util.underscore "ManifestRocks"
"manifest_rocks"
}
{
-> util.underscore "ABTestPlatform"
"abtest_platform"
}
{
-> util.underscore "HELLO_WORLD"
"" -- TODO: fix
}
{
-> util.underscore "whats_up"
"whats__up" -- TODO: fix
}
{
-> util.camelize "hello"
"Hello"
}
{
-> util.camelize "world_wide_i_web"
"WorldWideIWeb"
}
{
-> util.camelize util.underscore "ManifestRocks"
"ManifestRocks"
}
{
->
util.encode_query_string {
{"dad", "day"}
"hello[hole]": "wor=ld"
}
"dad=day&hello%5bhole%5d=wor%3dld"
}
{ -- stripping invalid types
->
json.decode util.to_json {
color: "blue"
data: {
height: 10
fn: =>
}
}
{
color: "blue", data: { height: 10}
}
}
{
->
util.build_url {
path: "/test"
scheme: "http"
host: "localhost.com"
port: "8080"
fragment: "cool_thing"
query: "dad=days"
}
"http://localhost.com:8080/test?dad=days#cool_thing"
}
{
-> util.time_ago os.time! - 34234349
{
{"years", 1}
{"days", 31}
{"hours", 5}
{"minutes", 32}
{"seconds", 29}
years: 1
days: 31
hours: 5
minutes: 32
seconds: 29
}
}
{
-> util.time_ago os.time! + 34234349
{
{"years", 1}
{"days", 31}
{"hours", 5}
{"minutes", 32}
{"seconds", 29}
years: 1
days: 31
hours: 5
minutes: 32
seconds: 29
}
}
{
-> util.time_ago_in_words os.time! - 34234349
"1 year ago"
}
{
-> util.time_ago_in_words os.time! - 34234349, 2
"1 year, 31 days ago"
}
{
-> util.time_ago_in_words os.time! - 34234349, 10
"1 year, 31 days, 5 hours, 32 minutes, 29 seconds ago"
}
{
-> util.time_ago_in_words os.time!
"0 seconds ago"
}
{
-> util.parse_cookie_string "__utma=54729783.634507326.1355638425.1366820216.1367111186.43; __utmc=54729783; __utmz=54729783.1364225235.36.12.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/Q95kO2iEje; __utma=163024063.1111023767.1355638932.1367297108.1367341173.42; __utmb=163024063.1.10.1367341173; __utmc=163024063; __utmz=163024063.1366693549.37.11.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/UYMGwvGJNo"
{
__utma: '163024063.1111023767.1355638932.1367297108.1367341173.42'
__utmz: '163024063.1366693549.37.11.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/UYMGwvGJNo'
__utmb: '163024063.1.10.1367341173'
__utmc: '163024063'
}
}
{
-> util.slugify "What is going on right now?"
"what-is-going-on-right-now"
}
{
-> util.slugify "what-about-now"
"what-about-now"
}
{
-> util.uniquify { "hello", "hello", "world", "another", "world" }
{ "hello", "world", "another" }
}
{
-> util.trim "what the heck"
"what the heck"
}
{
-> util.trim "
blah blah "
"blah blah"
}
{
-> util.trim_filter {
" ", " thing ",
yes: " "
okay: " no "
}
{ -- TODO: fix indexing?
nil, "thing", okay: "no"
}
}
{
-> util.trim_filter {
hello: " hi"
world: " hi"
yeah: " "
}, {"hello", "yeah"}, 0
{ hello: "hi", yeah: 0 }
}
{
->
util.key_filter {
hello: "world"
foo: "bar"
}, "hello", "yeah"
{ hello: "world" }
}
{
-> "^%()[12332]+$"\match(util.escape_pattern "^%()[12332]+$") and true
true
}
{
-> util.title_case "hello"
"Hello"
}
{
-> util.title_case "hello world"
"Hello World"
}
{
-> util.title_case "hello-world"
"Hello-world"
}
{
-> util.title_case "What my 200 Dollar thing You love to eat"
"What My 200 Dollar Thing You Love To Eat"
}
}
describe "lapis.nginx.postgres", ->
for group in *tests
it "should match", ->
input = group[1]!
if #group > 2
assert.one_of input, { unpack group, 2 }
else
assert.same input, group[2]
it "should autoload", ->
package.loaded["things.hello_world"] = "yeah"
package.loaded["things.cool_thing"] = "cool"
mod = util.autoload "things", {}
assert.equal "yeah", mod.HelloWorld
assert.equal "cool", mod.cool_thing
assert.equal nil, mod.not_here
assert.equal nil, mod.not_here
assert.equal "cool", mod.cool_thing
describe "lapis.util.mixin", ->
it "should mixin mixins", ->
import insert from table
log = {}
class Mixin
new: =>
insert log, "initializing Mixin"
@thing = { "hello" }
pop: =>
add_one: (num) =>
insert log, "Before add_one (Mixin), #{num}"
class Mixin2
new: =>
insert log, "initializing Mixin2"
add_one: (num) =>
insert log, "Before add_one (Mixin2), #{num}"
class One
util.mixin Mixin
util.mixin Mixin2
add_one: (num) =>
num + 1
new: =>
insert log, "initializing One"
o = One!
assert.equal 13, o\add_one(12)
assert.same {
"initializing One"
"initializing Mixin"
"initializing Mixin2"
"Before add_one (Mixin2), 12"
"Before add_one (Mixin), 12"
}, log
| 18.159021 | 430 | 0.53385 |
680b226e608e34c3dea665922496aa17287ad243 | 567 | export id
class block
size: 20
density: 200000
img: love.graphics.newImage("asset.png")
new: (x, y) =>
@body = love.physics.newBody(world, x, y, "dynamic")
@shape = love.physics.newRectangleShape(x, y, @size, @size)
@fix = love.physics.newFixture @body, @shape, @density
@id = id
id += 1
draw: =>
love.graphics.setColor 40*@id, 10*@id, 35*@id
love.graphics.polygon "fill", @body.getWorldPoints(@body, @shape.getPoints(@shape))
--love.graphics.draw(@img, @body\getX!, @body\getY!, 0, 0.3 , 0.3, 10, 10)
print "Draw Block"
| 33.352941 | 87 | 0.62963 |
2daac20e08c3d5c3e116e08609f0f3f59c901bf4 | 5,386 | import highlight, theme, ActionBuffer from howl.ui
import Scintilla, Buffer from howl
describe 'highlight', ->
indicator_on = (buffer, pos, number) ->
b_pos = buffer.text\byte_offset pos
on = buffer.sci\indicator_all_on_for b_pos - 1
return on and bit.band(on, number + 1) != 0
describe '.define(name, definition)', ->
it 'defines a highlight', ->
highlight.define 'custom', color: '#334455'
assert.equal highlight.custom.color, '#334455'
it 'automatically redefines the highlight in any existing sci', ->
highlight.define 'custom', color: '#334455'
sci = Scintilla!
buffer = Buffer {}, sci
number = highlight.number_for 'custom', buffer
highlight.define 'custom', color: '#665544'
set_fore = buffer.sci\indic_get_fore number
assert.equal set_fore, '#665544'
describe 'define_default(name, definition)', ->
it 'defines the highlight only if it is not already defined', ->
highlight.define_default 'new_one', color: '#334455'
assert.equal highlight.new_one.color, '#334455'
highlight.define_default 'new_one', color: '#101010'
assert.equal highlight.new_one.color, '#334455'
describe '.apply(name, buffer, pos, length)', ->
it 'activates the highlight for the specified range', ->
buffer = Buffer {}
buffer.text = 'hƏllo'
highlight.define 'custom', color: '#334455'
number = highlight.number_for 'custom', buffer
highlight.apply 'custom', buffer, 2, 2
assert.is_false indicator_on buffer, 1, number
assert.is_true indicator_on buffer, 2, number
assert.is_true indicator_on buffer, 3, number
assert.is_false indicator_on buffer, 4, number
describe '.number_for(name, buffer, sci)', ->
it 'automatically assigns an indicator number and defines the highlight in sci', ->
buffer = Buffer {}, Scintilla!
highlight.define 'my_highlight_a', color: '#334455'
highlight.define 'my_highlight_b', color: '#334455'
highlight_num = highlight.number_for 'my_highlight_a', buffer
set_fore = buffer.sci\indic_get_fore highlight_num
assert.equal set_fore, '#334455'
assert.is_not.equal highlight.number_for('my_highlight_b', buffer), highlight_num
it 'remembers the highlight number used for a particular highlight', ->
buffer = Buffer {}
highlight.define 'got_it', color: '#334455'
highlight_num = highlight.number_for 'got_it', buffer
highlight_num2 = highlight.number_for 'got_it', buffer
assert.equal highlight_num2, highlight_num
it 'raises an error if the number of highlights are exhausted', ->
buffer = Buffer {}
for i = 1, Scintilla.INDIC_MAX + 2
highlight.define 'my_highlight' .. i, color: '#334455'
assert.raises 'highlights exceeded', ->
for i = 1, Scintilla.INDIC_MAX + 2
highlight.number_for 'my_highlight' .. i, buffer
it 'raises an error if the highlight is not defined', ->
assert.raises 'Could not find highlight', -> highlight.number_for 'mystery highlight', {}
it '.set_for_buffer(sci, buffer) initializes any previously used buffer highlights', ->
sci = Scintilla!
buffer = Buffer {}
highlight.define 'highlight_foo', color: '#334455'
number = highlight.number_for 'highlight_foo', buffer
highlight.set_for_buffer sci, buffer
defined_fore = sci\indic_get_fore number
assert.equal defined_fore, '#334455'
it '.at_pos(buffer, pos) returns a list of the active highlights at pos', ->
highlight.define 'highlight_bar', color: '#334455'
highlight.define 'highlight_foo', color: '#334455'
buffer = Buffer {}
buffer.text = 'hƏllo'
highlight.apply 'highlight_bar', buffer, 1, 4
assert.same highlight.at_pos(buffer, 1), { 'highlight_bar' }
assert.same highlight.at_pos(buffer, 5), { }
describe '.remove_all(name, buffer)', ->
it 'removes all highlights with <name> in <buffer>', ->
highlight.define 'foo', color: '#334455'
buffer = Buffer {}
buffer.text = 'ʘne twʘ'
highlight.apply 'foo', buffer, 1, 3
highlight.apply 'foo', buffer, 5, 3
highlight.remove_all 'foo', buffer
assert.same highlight.at_pos(buffer, 1), { }
assert.same highlight.at_pos(buffer, 4), { }
assert.same highlight.at_pos(buffer, 5), { }
assert.same highlight.at_pos(buffer, 8), { }
it 'does nothing when no highlights have been set', ->
highlight.define 'foo', color: '#334455'
buffer = Buffer {}
buffer.text = 'one two'
highlight.remove_all 'foo', buffer
describe '.remove_in_range(name, buffer, start_pos, end_pos)', ->
it 'removes all highlights with <name> in <buffer> in the range specified (inclusive)', ->
highlight.define 'foo', color: '#334455'
buffer = Buffer {}
buffer.text = 'ʘne twʘ'
highlight.apply 'foo', buffer, 1, 3
highlight.apply 'foo', buffer, 5, 3
highlight.remove_in_range 'foo', buffer, 4, 7
assert.same highlight.at_pos(buffer, 3), { 'foo' }
assert.same highlight.at_pos(buffer, 5), { }
assert.same highlight.at_pos(buffer, 8), { }
it 'does nothing when no highlights have been set', ->
highlight.define 'foo', color: '#334455'
buffer = Buffer {}
buffer.text = 'ʘne twʘ'
highlight.remove_in_range 'foo', buffer, 1, #buffer
| 40.496241 | 95 | 0.667286 |
95eedaddb7e703dcec64585869275dbb59353c8c | 919 | --copy this file to custom_config.moon to set secrets
import config from require "lazuli.config"
config {"development","test","production"},->
set "appname", "KinkyEureka"
set "projectStage", "alpha"
--set "projectStage", "beta"
--set "projectStage", "1.0"
config {"development","test"}, ->
postgres ->
database "<EDIT THIS>"
password "<EDIT THIS>"
session_name "<EDIT THIS>"
secret "<EDIT THIS>"
port 8080
acl_cache_size "1m"
timeline_cache_size "1m"
static_url_prefix "/static"
modules ->
user_management ->
providers ->
--set "lazuli.modules.user_management.providers.example_false", true
config "production", ->
postgres ->
database "<EDIT THIS>"
password "<EDIT THIS>"
port 8081 -- EDIT THIS
page_cache_size "10m"
acl_cache_size "5m"
timeline_cache_size "5m"
static_url_prefix "/static"
session_name "<EDIT THIS>"
secret "<EDIT THIS>"
| 24.184211 | 76 | 0.675734 |
8b2e5b2c6df78538c96944b1abd3945bf522923b | 2,733 | -- Copyright 2013-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
howl.aux.lpeg_lexer ->
para_pair = (start, stop) ->
stop = start unless stop
stop = P(stop)
P(start) * scan_until(any(stop, eol * eol)) * stop
-- headers
h1 = line_start * any {
capture('h1', '#' * scan_until eol),
sequence {
capture('h1', scan_until eol),
capture('whitespace', eol),
capture('operator', P'='^1) * #eol
}
}
h2 = line_start * any {
capture('h2', '##' * scan_until eol),
sequence {
capture('h2', scan_until eol),
capture('whitespace', eol),
capture('operator', P'-'^1) * #eol
}
}
h3 = capture 'h3', line_start * '###' * scan_until eol
-- other syntax
not_escaped = -B'\\'
emp_start = -B(1) + B(space)
strong = emp_start * capture 'strong', any { para_pair('*'), para_pair('_') }
emphasis = emp_start * capture 'emphasis', any { para_pair('**'), para_pair('__') }
link = not_escaped * sequence {
capture('operator', '!')^-1,
capture('link_label', para_pair '[', ']'),
any({
sequence {
capture('link_url', '(' * scan_until S') \t'),
(blank^1 * capture('string', para_pair('"')) * blank^0)^-1,
capture('link_url', ')'),
}
para_pair '(', ')',
capture('link_url', P' '^-1 * para_pair '[', ']'),
})^-1
}
ref_def = sequence {
line_start,
blank^-3,
capture('link_label', para_pair '[', ']'),
':' * blank^1,
capture('link_url', complement(space)^1),
(space^1 * capture('string', any( para_pair('"'), para_pair("'"), para_pair('(', ')'))))^-1
}
fenced_code_block = sequence {
not_escaped,
capture('operator', '```'),
sub_lex_by_pattern(alpha^1, 'special', '```')
capture('operator', '```')^-1,
}
code = not_escaped * capture 'embedded', any {
paired '```',
para_pair('``'),
para_pair('`'),
line_start * (blank^4 + P'\t') * scan_until eol
}
block_quote = capture 'operator', line_start * '>'
list_item = capture 'operator', sequence {
line_start,
blank^-3,
any(digit^1 * P'.', S'*-+'),
#blank
}
h_rule = capture 'number', line_start * (S'-*_' * P' '^0)^1 * #eol
preamble_def = sequence {
capture('key', alpha^1 * ':'),
capture('string', scan_until eol),
capture('special', eol)
}
preamble = line_start * sequence {
capture('special', P'---' * eol),
preamble_def^1,
capture('special', '---'),
capture('whitespace', eol),
}
any {
preamble,
h_rule,
block_quote,
list_item,
h3,
h2,
h1,
emphasis,
strong,
ref_def,
link,
fenced_code_block,
code,
}
| 23.973684 | 95 | 0.551043 |
582339db59eb46d0926362ef1f771c39911bf5fd | 19 | -- TODO Touch.moon
| 9.5 | 18 | 0.684211 |
59e7515a418f2162f8e2eff4f4b57486988de999 | 1,020 | serpent = require 'serpent'
import File from howl.io
import SandboxedLoader from howl.aux
default_dir = ->
howl_dir = os.getenv 'HOWL_DIR'
return File(howl_dir) if howl_dir
home = os.getenv('HOME')
home and File(home)\join('.howl') or nil
class Settings
new: (dir = default_dir!) =>
unless dir.exists
if dir.parent.exists
dir\mkdir!
else
return
@dir = dir
@sysdir = @dir / 'system'
@sysdir\mkdir! unless @sysdir.exists
load_user: =>
return unless @dir
for ext in *{ 'bc', 'moon', 'lua' }
init = @dir\join "init.#{ext}"
if init.exists
loader = SandboxedLoader @dir, 'user', no_implicit_globals: true
loader -> user_load 'init'
break
save_system: (name, t) =>
file = @sysdir\join(name .. '.lua')
options = indent: ' ', fatal: true
file.contents = serpent.dump t, options
load_system: (name) =>
file = @sysdir\join(name .. '.lua')
return nil unless file.exists
(assert loadfile(file))!
| 23.72093 | 72 | 0.612745 |
f110fad61e3380f0062a475157c8506a3634a518 | 829 | M = {}
TK = require("PackageToolkit")
append = (TK.module.import ..., "_append").append
tail = (TK.module.import ..., "_tail").tail
flatten = (TK.module.import ..., "_flatten").flatten
-- take a the Cartesian product of two lists
M.cart2 = (list1, list2, merge=false) ->
aux = (list1, list2, accum) ->
if #list2 == 0 or #list1 == 0
return accum
elseif #list1 == 1
if merge
return aux list1, (tail list2), (append accum, (flatten list1[1], list2[1]))
else
return aux list1, (tail list2), (append accum, {list1[1], list2[1]})
else
return aux (tail list1), list2, (aux { list1[1] }, list2, accum)
return {} if type(list1) != "table"
return {} if type(list2) != "table"
return aux list1, list2, {}
return M | 37.681818 | 92 | 0.558504 |
a3771a75e8927e4e2c6f80d9881b4b9c41d4d321 | 1,171 | [==[
git = dofile('gitdo.moon')
gitState = tostring(git\saveState!)\sub(1, 8)
torch.save(gitState..'.t7', model)
-- years pass...
git.pushState(gitState)
torch.load(gitState..'.t7')
git.popState!
]==]
luagit = require 'luagit-ffi'
saveState = ->
repo = luagit.Repository('.')
index = with repo\getIndex!
\addAll{'*'}
stateTreeId = index\writeTree!
index\free!
repo\free!
stateTreeId
pushStashed = false
pushState = (state) ->
repo = luagit.Repository('.')
emptySig = name: '', email: '', when: os.time!
stashed, stash = repo\stashSave emptySig, state, {'KEEP_INDEX', 'INCLUDE_UNTRACKED'}
pushStashed = stashed == 0
stateTree = repo\lookupTree(state)
repo\checkout(stateTree, {strategy: {'SAFE', 'USE_OURS'}})
-- use_ours lets staged files overwrite those in the saved tree
-- notice the KEEP_INDEX during the stash
stateTree\free!
repo\free!
popState = ->
repo = luagit.Repository('.')
repo\checkout strategy: {'FORCE'}
if pushStashed
pushStashed = nil
repo\stashPop 0,
applyFlags: {'REINSTATE_INDEX'},
checkoutOpts: {strategy: {'FORCE'}}
repo\free!
{:saveState, :pushState, :popState}
| 20.189655 | 86 | 0.663535 |
b9664760027f569e1906cc0d870d5e056d0260cf | 460 | export modinfo = {
type: "command"
desc: "Fog on/off"
alias: {"fog"}
func: (Msg,Speaker) ->
light = Service"Lighting"
if string.lower(Msg) == "on"
light.FogStart = 0
light.FogEnd = 100
Output2("Fogs on",{Colors.Green})
loggit("Fogs on")
elseif(string.lower(Msg) == "off")
light.FogStart = 0
light.FogEnd = 9e9
Output2("Fogs off",{Colors.Green})
loggit("Fogs off")
else
Output2("Message must be on/off",{Colors.Red})
} | 24.210526 | 49 | 0.623913 |
cb470f394e0b2b0d4ad1ce9754875d177ff013ba | 184 | shiftr = zb2rhjBmuz6CmkbbzwtndbiietAq4jzi8JAxFoy1fUGDcxZeT
num => bits =>
(or (shiftr num bits) (if (ltn (or num 0) #(pow 2 31)) 0 (mul (sub (pow 2 bits) 1) (pow 2 (sub 32 bits)))))
| 46 | 109 | 0.668478 |
69962a99aca0d2391d9a52c6643cae6c0d5e4903 | 1,278 |
import type, getmetatable, setmetatable, rawset from _G
local Flow
is_flow = (cls) ->
return false unless cls
return true if cls == Flow
is_flow cls.__parent
-- a mediator for encapsulating logic between multiple models and a request
class Flow
expose_assigns: false
new: (@_req, obj={}) =>
assert @_req, "flow missing request"
-- get the real request if the object passed is another flow
if is_flow @_req.__class
@_req = @_req._req
old_mt = getmetatable @
proxy = setmetatable obj, old_mt
mt = {
__call: old_mt.__call
__index: (key) =>
val = proxy[key]
return val if val != nil
val = @_req[key]
-- wrap the function to run in req context
if type(val) == "function"
val = (_, ...) -> @_req[key] @_req, ...
rawset @, key, val
val
}
if expose = @expose_assigns
local allowed_assigns
if type(expose) == "table"
allowed_assigns = {name, true for name in *expose}
mt.__newindex = (key, val) =>
if allowed_assigns
if allowed_assigns[key]
@_req[key] = val
else
rawset @, key, val
else
@_req[key] = val
setmetatable @, mt
{ :Flow, :is_flow }
| 21.661017 | 75 | 0.576682 |
115815f9fb15cd8eb754e271a2ef2caaf17482b1 | 248 | import html from require"html"
import EL, launch from require"luajs"
attente = EL "div_attente"
body = EL "corps"
contenu = EL "contenu"
btn = EL "btn"
btn\on "click", ->
launch ->
contenu << html -> p "Bonjour !"
attente\hide!
body\show!
| 16.533333 | 37 | 0.66129 |
ef34d929c8cd0c2461d96753a2953dc532d05940 | 663 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import interact, mode from howl
interact.register
name: 'select_mode'
description: 'Selection list for modes'
handler: (opts={}) ->
selection = nil
if opts.buffer
selection = opts.buffer.mode.name
mode_names = mode.names
table.sort mode_names
selected_mode = interact.select
title: opts.title or 'Mode'
prompt: opts.prompt
text: opts.text
items: mode_names
columns: {{style: 'string'}}
:selection
return unless selected_mode
return mode.by_name selected_mode
| 24.555556 | 79 | 0.687783 |
5372c158a05e36175a22e60f3427ffe56a283669 | 1,052 | ffi = require 'ffi'
core = require 'ljglibs.core'
require 'ljglibs.cdefs.gtk'
C = ffi.C
core.auto_loading 'gtk', {
constants: {
prefix: 'GTK_'
-- GtkStateFlags
'STATE_FLAG_NORMAL',
'STATE_FLAG_ACTIVE',
'STATE_FLAG_PRELIGHT',
'STATE_FLAG_SELECTED',
'STATE_FLAG_INSENSITIVE',
'STATE_FLAG_INCONSISTENT',
'STATE_FLAG_FOCUSED',
-- GtkPositionType
'POS_LEFT',
'POS_RIGHT',
'POS_TOP',
'POS_BOTTOM'
-- GtkOrientation
'ORIENTATION_HORIZONTAL',
'ORIENTATION_VERTICAL',
-- GtkPackType
'PACK_START',
'PACK_END'
-- GtkJustification
'JUSTIFY_LEFT'
'JUSTIFY_RIGHT'
'JUSTIFY_CENTER'
'JUSTIFY_FILL'
-- GtkWindowPosition;
'WIN_POS_NONE'
'WIN_POS_CENTER'
'WIN_POS_MOUSE'
'WIN_POS_CENTER_ALWAYS'
'WIN_POS_CENTER_ON_PARENT'
-- GtkAlign
'ALIGN_FILL',
'ALIGN_START',
'ALIGN_END',
'ALIGN_CENTER',
'ALIGN_BASELINE',
}
cairo_should_draw_window: (cr, window) ->
C.gtk_cairo_should_draw_window(cr, window) != 0
}
| 18.45614 | 51 | 0.65019 |
bde90447bbd7fe4903220fa897d214be872e708a | 541 | export modinfo = {
type: "command"
desc: "Invisible"
alias: {"invisible", "invis"}
func: getDoPlayersFunction (v) ->
if v and v.Character
for a, obj in pairs(v.Character\GetChildren())
if obj\IsA"BasePart"
if obj.Name ~= "HumanoidRootPart"
obj.Transparency = 1
if obj\FindFirstChild"face"
obj.face.Transparency = 1
elseif obj\IsA"Hat" and obj\FindFirstChild"Handle"
obj.Handle.Transparency = 1
elseif obj\IsA"Accessory" and obj\FindFirstChild"Handle"
obj.Handle.Transparency = 1
} | 31.823529 | 60 | 0.672828 |
9c865a81f83f494904af421b95548746902ea568 | 946 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
jit = require 'jit'
require 'ljglibs.cdefs.gtk'
core = require 'ljglibs.core'
glib = require 'ljglibs.glib'
C = ffi.C
jit.off true, true
core.define 'GtkClipboard < GObject', {
get: (atom) -> C.gtk_clipboard_get atom
properties: {
text:
get: => @wait_for_text!
set: (text) => @set_text text
}
clear: => C.gtk_clipboard_clear @
store: => C.gtk_clipboard_store @
set_text: (text) => C.gtk_clipboard_set_text @, text, #text
wait_for_text: => glib.g_string C.gtk_clipboard_wait_for_text @
set_can_store: (targets) =>
nr_targets = targets and #targets or 0
if nr_targets > 0
t = ffi.new 'GtkTargetEntry[?]', nr_targets
for i = 1, nr_targets
t[i - 1] = targets[i]
targets = t
C.gtk_clipboard_set_can_store @, targets, nr_targets
}
| 24.894737 | 79 | 0.668076 |
186e0081e41e417a1ec26346cb82d82cfc330339 | 51 | {
whitelist_globals: {
["."]: {"ngx"}
}
}
| 7.285714 | 22 | 0.392157 |
f3575481d6570f9337d9b5163caad69260905230 | 13,275 |
import render_html, Widget from require "lapis.html"
render_widget = (w) ->
buffer = {}
w buffer
table.concat buffer
describe "lapis.html", ->
it "should render html", ->
output = render_html ->
b "what is going on?"
div ->
pre class: "cool", -> span "hello world"
text capture -> div "this is captured"
link rel: "icon" -- , type: "image/png", href: "dad"-- can't have multiple because of hash ordering
raw "<div>raw test</div>"
text "<div>raw test</div>"
html_5 ->
div "what is going on there?"
assert.same [[<b>what is going on?</b><div><pre class="cool"><span>hello world</span></pre></div><div>this is captured</div><link rel="icon"/><div>raw test</div><div>raw test</div><!DOCTYPE HTML><html lang="en"><div>what is going on there?</div></html>]], output
it "should render html class table syntax", ->
output = render_html ->
div class: {"hello", "world", cool: true, notcool: false}
div class: {}
div class: {ok: "fool"}
div class: {cool: nil}
assert.same '<div class="hello world cool"></div><div></div><div class="ok"></div><div></div>', output
it "should render more html", ->
output = render_html ->
element "leaf", {"hello"}, "world"
element "leaf", "one", "two", "three"
element "leaf", {hello: "world", "a"}, { no: "show", "b", "c" }
leaf {"hello"}, "world"
leaf "one", "two", "three"
leaf {hello: "world", "a"}, { no: "show", "b", "c" }
assert.same [[<leaf>helloworld</leaf><leaf>onetwothree</leaf><leaf hello="world">abc</leaf><leaf>helloworld</leaf><leaf>onetwothree</leaf><leaf hello="world">abc</leaf>]], output
-- attributes are unordered so we don't check output (for now)
it "should render multiple attributes", ->
render_html ->
link rel: "icon", type: "image/png", href: "dad"
pre id: "hello", class: "things", style: [[border: image("http://leafo.net")]]
it "should boolean attributes", ->
output = render_html ->
span required: true
div required: false
assert.same [[<span required></span><div></div>]], output
it "should capture", ->
-- we have to do it this way because in plain Lua 5.1, upvalues can't be
-- joined, we only have a copy of the value.
capture_result = {}
output = render_html ->
text "hello"
capture_result.value = capture ->
div "This is the capture"
text "world"
assert.same "helloworld", output
assert.same "<div>This is the capture</div>", capture_result.value
it "should capture into joined upvalue", ->
-- skip on lua 5.1
if _VERSION == "Lua 5.1" and not _G.jit
pending "joined upvalues not available in Lua 5.1, skipping test"
return
capture_result = {}
output = render_html ->
text "hello"
capture_result.value = capture ->
div "This is the capture"
text "world"
assert.same "helloworld", output
assert.same "<div>This is the capture</div>", capture_result.value
describe "Widget", ->
it "should render the widget", ->
class TestWidget extends Widget
content: =>
div class: "hello", @message
raw @inner
input = render_widget TestWidget message: "Hello World!", inner: -> b "Stay Safe"
assert.same input, [[<div class="hello">Hello World!</div><b>Stay Safe</b>]]
it "renders widget with inheritance", ->
class BaseWidget extends Widget
value: 100
another_value: => 200
content: =>
div class: "base_widget", ->
@inner!
inner: => error "implement me"
class TestWidget extends BaseWidget
inner: =>
text "Widget speaking, value: #{@value}, another_value: #{@another_value!}"
input = render_widget TestWidget!
assert.same input, [[<div class="base_widget">Widget speaking, value: 100, another_value: 200</div>]]
it "renders widget with inheritance and super", ->
class BaseWidget extends Widget
value: 100
another_value: => 200
content: =>
div class: "base_widget", ->
@inner!
inner: => div "Hello #{@value} #{@another_value!}"
class TestWidget extends BaseWidget
inner: =>
pre ->
-- we can't use super directly since the rendering scope is unable to set the function environment
-- this is the current 'recommended' approach to calling super
@_buffer\call super.inner, @
input = render_widget TestWidget!
assert.same input, [[<div class="base_widget"><pre><div>Hello 100 200</div></pre></div>]]
it "should include widget helper", ->
class Test extends Widget
content: =>
div "What's up! #{@hello!}"
w = Test!
w\include_helper {
id: 10
hello: => "id: #{@id}"
}
input = render_widget w
assert.same input, [[<div>What's up! id: 10</div>]]
it "helper should pass to sub widget", ->
class Fancy extends Widget
content: =>
text @cool_message!
text @thing
class Test extends Widget
content: =>
first ->
widget Fancy @
second ->
widget Fancy!
w = Test thing: "THING"
w\include_helper {
cool_message: =>
"so-cool"
}
assert.same [[<first>so-coolTHING</first><second>so-cool</second>]],
render_widget w
it "helpers should resolve correctly ", ->
class Base extends Widget
one: 1
two: 2
three: 3
class Sub extends Base
two: 20
three: 30
four: 40
content: =>
text @one
text @two
text @three
text @four
text @five
w = Sub!
w\include_helper {
one: 100
two: 200
four: 400
five: 500
}
buff = {}
w\render buff
assert.same {"1", "20", "30", "40", "500"}, buff
it "should set layout opt", ->
class TheWidget extends Widget
content: =>
@content_for "title", -> div "hello world"
@content_for "another", "yeah"
widget = TheWidget!
helper = { layout_opts: {} }
widget\include_helper helper
out = render_widget widget
assert.same { _content_for_another: "yeah", _content_for_title: "<div>hello world</div>" }, helper.layout_opts
it "should render content for", ->
class TheLayout extends Widget
content: =>
assert @has_content_for("title"), "should have title content_for"
assert @has_content_for("inner"), "should have inner content_for"
assert @has_content_for("footer"), "should have footer content_for"
assert not @has_content_for("hello"), "should not have hello content for"
div class: "title", ->
@content_for "title"
@content_for "inner"
@content_for "footer"
class TheWidget extends Widget
content: =>
@content_for "title", -> div "hello world"
@content_for "footer", "The's footer"
div "what the heck?"
layout_opts = {}
inner = {}
view = TheWidget!
view\include_helper { :layout_opts }
view inner
layout_opts._content_for_inner = -> raw inner
assert.same [[<div class="title"><div>hello world</div></div><div>what the heck?</div>The's footer]], render_widget TheLayout layout_opts
it "should append multiple content for", ->
class TheLayout extends Widget
content: =>
element "content-for", ->
@content_for "things"
class TheWidget extends Widget
content: =>
@content_for "things", -> div "hello world"
@content_for "things", "dual world"
layout_opts = {}
inner = {}
view = TheWidget!
view\include_helper { :layout_opts }
view inner
assert.same [[<content-for><div>hello world</div>dual world</content-for>]], render_widget TheLayout layout_opts
it "should instantiate widget class when passed to widget helper", ->
class SomeWidget extends Widget
content: =>
@color = "blue"
-- assert.Not.same @, SomeWidget
text "hello!"
render_html ->
widget SomeWidget
assert.same nil, SomeWidget.color
it "should render widget inside of capture", ->
capture_result = {}
class InnerInner extends Widget
content: =>
out = capture ->
span "yeah"
raw out
class Inner extends Widget
content: =>
dt "hello"
widget InnerInner
dt "world"
class Outer extends Widget
content: =>
capture_result.value = capture ->
div "before"
widget Inner!
div "after"
assert.same [[]], render_widget Outer!
assert.same [[<div>before</div><dt>hello</dt><span>yeah</span><dt>world</dt><div>after</div>]], capture_result.value
describe "widget.render_to_file", ->
class Inner extends Widget
content: =>
dt class: "cool", "hello"
p ->
strong "The world #{@t}"
@m!
dt "world"
m: =>
raw "is & here"
it "renders to string by filename", ->
time = os.time!
Inner({
t: time
})\render_to_file "widget_out.html"
written = assert(io.open("widget_out.html"))\read "*a"
assert.same [[<dt class="cool">hello</dt><p><strong>The world ]] .. time .. [[</strong>is & here</p><dt>world</dt>]], written
it "writes to file interface", ->
written = {}
fake_file = {
write: (content) =>
table.insert written, content
}
time = os.time!
Inner({
t: time
})\render_to_file fake_file
assert.same [[<dt class="cool">hello</dt><p><strong>The world ]] .. time .. [[</strong>is & here</p><dt>world</dt>]], table.concat(written)
describe "@include", ->
after_each ->
package.loaded["widgets.mymixin"] = nil
it "copies method from mixin", ->
class TestMixin
thing: ->
div class: "the_thing", ->
text "hello world"
class SomeWidget extends Widget
@include TestMixin
content: =>
div class: "outer", ->
@thing!
assert.same [[<div class="outer"><div class="the_thing">hello world</div></div>]],
render_widget SomeWidget!
it "includes by module name", ->
package.loaded["widgets.mymixin"] = class MyMixin
render_list: =>
div "I am a list"
class SomeWidget extends Widget
@include "widgets.mymixin"
content: =>
div class: "outer", ->
@render_list!
assert.same [[<div class="outer"><div>I am a list</div></div>]],
render_widget SomeWidget!
it "supports including class with inheritance", ->
class Alpha
thing: =>
li class: "the_thing", "hello"
thong: =>
li class: "the_thong", "world"
class Beta extends Alpha
thong: =>
li class: "fake_thong", "whoa"
render_list: =>
ul ->
@thing!
@thong!
class SomeWidget extends Widget
@include Beta
content: =>
div class: "outer", ->
@render_list!
assert.same [[<div class="outer"><ul><li class="the_thing">hello</li><li class="fake_thong">whoa</li></ul></div>]],
render_widget SomeWidget!
it "handles method collision", ->
class TestMixin
thing: ->
div class: "the_thing", ->
text "hello world"
hose: ->
text "test hose"
class OtherMixin
hose: ->
text "other hose"
class SomeWidget extends Widget
@include TestMixin
@include OtherMixin
thing: ->
code class: "coder", "here's the code"
content: =>
div class: "outer", ->
@thing!
@hose!
assert.same [[<div class="outer"><code class="coder">here's the code</code>other hose</div>]],
render_widget SomeWidget!
it "calls super method", ->
class TestMixin
height: => 10
class SomeWidget extends Widget
@include TestMixin
height: =>
super! + 12
content: =>
span "data-height": @height!
assert.same [[<span data-height="22"></span>]],
render_widget SomeWidget!
it "does not re-mixin Widget", ->
class MistakeMixin extends Widget
height: => 10
assert.has_error(
->
class SomeWidget extends Widget
@include MistakeMixin
"Your widget tried to include a class that extends from Widget. An included class should be a plain class and not another widget"
)
| 28.184713 | 290 | 0.556083 |
91c7f0f9257e1cdfd5e34778fb982abcabe80d0a | 167 | import Model from require "lapis.db.model"
class UserData extends Model
@primary_key: "user_id"
@relations: {
{"user_id", belongs_to: "Users"}
}
| 20.875 | 43 | 0.646707 |
aa46c61648d55a589bf23babaf6e5a7512dec49e | 747 | import Tween from require "LunoPunk.Tween"
-- Global volume fader.
class Fader extends Tween
-- Constructor.
-- @param complete Optional completion callback.
-- @param type Tween type.
new: (complete, type) =>
-- Fader information.
@__start, @__range = 0, 0
super 0, type, complete
-- Fades FP.volume to the target volume.
-- @param volume The volume to fade to.
-- @param duration Duration of the fade.
-- @param ease Optional easer function.
fadeTo: (volume, duration, ease = nil) =>
volume = 0 if volume < 0
@__start = LP.volume
@__range = volume - @__start
@__target = duration
@__ease = ease
@start!
-- @private Updates the Tween.
update: () =>
super!
LP.volume = @__start + @__range * @t
{ :Fader }
| 24.096774 | 49 | 0.662651 |
f955ac6bfe326bd542257aa71d0d460d951c9dbd | 1,682 |
--
-- Copyright (C) 2017-2020 DBotThePony
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
DLib = DLib
Notify = DLib.Notify
import HasValue from table
Notify.SetSideFunc = (val = @m_defSide, affectAlign = true) =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
assert(HasValue(@m_allowedSides, val), 'Invalid side on ' .. @@.__name)
assert(type(affectAlign) == 'boolean', 'Only booleans are allowed')
assert(not @m_isDrawn, 'Can not change side while drawing')
@m_side = val
if affectAlign and val == Notify_SIDE_RIGHT
@SetAlign(TEXT_ALIGN_RIGHT)
elseif affectAlign and val == Notify_SIDE_LEFT
@SetAlign(TEXT_ALIGN_LEFT)
return @
| 43.128205 | 92 | 0.75981 |
394672c363596e20ec8b1c5867e607e373653025 | 9,079 | import Buffer, config from howl
describe 'BufferLines', ->
buffer = (text) ->
with Buffer {}
.text = text
it '# operator returns number of lines in the buffer', ->
b = buffer 'hello\n world\nagain!'
assert.equal #b.lines, 3
describe 'Line objects', ->
buf = nil
lines = nil
before_each ->
buf = buffer 'hƏllØ\n wØrld\nagain!'
lines = buf.lines
it '.buffer points to the corresponding buffer', ->
assert.same buf, lines[1].buffer
it '.nr holds the line number', ->
assert.equal lines[1].nr, 1
it '.text returns the text of the specified line, sans linebreak', ->
assert.equal lines[1].text, 'hƏllØ'
assert.equal lines[2].text, ' wØrld'
assert.equal lines[3].text, 'again!'
it 'tostring(line) gives the same as .text', ->
assert.equal tostring(lines[1]), lines[1].text
describe '.text = <content>', ->
it 'replaces the line text with <content>', ->
lines[1].text = 'Hola'
assert.equal buf.text, 'Hola\n wØrld\nagain!'
it 'raises an error if <content> is nil', ->
assert.raises 'nil', -> lines[1].text = nil
it '.indentation returns the indentation for the line', ->
assert.equal lines[1].indentation, 0
assert.equal lines[2].indentation, 2
it '.indentation = <nr> set the indentation for the line to <nr>', ->
lines[3].indentation = 4
assert.equal 'hƏllØ\n wØrld\n again!', buf.text
it '.start_pos returns the start position for line', ->
assert.equal lines[2].start_pos, 7
buf.text = ''
assert.equal lines[1].start_pos, 1
it '.end_pos returns the end position for line, right before the newline', ->
assert.equal lines[1].end_pos, 6
buf.text = ''
assert.equal lines[1].end_pos, 1
it '.byte_start_pos returns the byte start position for line', ->
buf.text = 'åäö\nwØrld'
assert.equal lines[2].byte_start_pos, 8
buf.text = ''
assert.equal lines[1].byte_start_pos, 1
it '.byte_end_pos returns the byte end position for line', ->
buf.text = 'åäö\nwØrld'
assert.equal lines[1].byte_end_pos, 7
buf.text = ''
assert.equal lines[1].byte_end_pos, 1
it '.previous returns the line above this one, or nil if none', ->
assert.equal lines[2].previous, lines[1]
assert.is_nil lines[1].previous
it '.previous_non_blank returns the first preceding non-blank line, or nil if none', ->
assert.is_nil lines[1].previous_non_blank
assert.equal lines[1], lines[2].previous_non_blank
lines\insert 3, ''
assert.equal lines[2], lines[4].previous_non_blank
it '.next_non_blank returns the first succeding non-blank line, or nil if none', ->
assert.is_nil lines[3].next_non_blank
assert.equal lines[3], lines[2].next_non_blank
lines\insert 3, ''
assert.equal lines[4], lines[2].next_non_blank
it '.next returns the line below this one, or nil if none', ->
assert.equal lines[1].next, lines[2]
assert.is_nil lines[3].next
describe '.chunk', ->
it 'a Chunk object for the line, disregarding the newline', ->
buf.text = 'hƏllØ\nbare'
chunk = lines[1].chunk
assert.equal 'Chunk', typeof chunk
assert.equal 'hƏllØ', chunk.text
assert.equal 1, chunk.start_pos
assert.equal 5, chunk.end_pos
chunk = lines[2].chunk
assert.equal 'bare', chunk.text
assert.equal 7, chunk.start_pos
assert.equal 10, chunk.end_pos
it 'is an empty chunk for empty lines', ->
buf.text = '\n'
chunk = lines[1].chunk
assert.equal '', chunk.text
assert.equal 1, chunk.start_pos
assert.equal 0, chunk.end_pos
chunk = lines[2].chunk
assert.equal '', chunk.text
assert.equal 2, chunk.start_pos
assert.equal 1, chunk.end_pos
it '.indent() indents the line by <config.indent>', ->
config.indent = 2
buf.lines[1]\indent!
assert.equal ' hƏllØ\n wØrld\nagain!', buf.text
buf.config.indent = 1
buf.lines[3]\indent!
assert.equal ' hƏllØ\n wØrld\n again!', buf.text
it '.unindent() unindents the line by <config.indent>', ->
buf.text = ' first\n second'
config.indent = 2
buf.lines[1]\unindent!
assert.equal buf.text, 'first\n second'
buf.config.indent = 1
buf.lines[2]\unindent!
assert.equal buf.text, 'first\n second'
it '#line returns the length of the line', ->
assert.equal #lines[1], 5
it 'lines are equal if they have the same text', ->
lines[2] = 'hƏllØ'
assert.equal lines[1], lines[2]
it 'string methods can be accessed directly on the object', ->
buf.text = 'first line'
line = lines[1]
assert.equal 'fi', line\sub(1,2)
assert.equal 8, (line\find('in'))
assert.equal 'first win', (line\gsub('line', 'win'))
it 'string properties can be accessed directly on the object', ->
assert.is_false lines[1].is_empty
assert.is_false lines[1].is_blank
lines[1] = ''
assert.is_true lines[1].is_empty
assert.is_true lines[1].is_blank
describe '[nr]', ->
it 'returns a line object for the specified line', ->
lines = buffer('hello\n world\nagain!').lines
assert.equal lines[1].text, 'hello'
it 'returns nil if the line number is invalid', ->
lines = buffer('hello!').lines
assert.is_nil lines[2]
assert.is_nil lines[0]
describe '[nr] = <value>', ->
it 'replaces the text of the specified line with <value>', ->
b = buffer 'hellØ\nwØrld'
b.lines[1] = 'hØla'
assert.equal b.text, 'hØla\nwØrld'
it 'removes the entire line if value is nil', ->
b = buffer 'gØØdbye\ncruel\nwØrld'
b.lines[2] = nil
assert.equal 'gØØdbye\nwØrld', b.text
b.lines[1] = nil
assert.equal 'wØrld' ,b.text
it 'raises an error if the line number is invalid', ->
b = buffer 'hello!'
assert.raises 'Invalid index', -> b.lines['foo'] = 'bar'
it 'delete(start, end) deletes the the lines [start, end]', ->
b = buffer 'hellØ\nwØrld\nagain!'
b.lines\delete 1, 2
assert.equal b.text, 'again!'
it 'at_pos(pos) returns the line at <pos>', ->
lines = buffer('Øne\ntwØ\nthree').lines
line = lines\at_pos 5
assert.equal 'twØ', line.text
describe 'range(start, end)', ->
it 'returns a table with lines [start, end]', ->
lines = buffer('one\ntwo\nthree').lines
range = lines\range 1, 2
assert.same { lines[1], lines[2] }, range
it 'start can be greater than end', ->
lines = buffer('one\ntwo\nthree').lines
range = lines\range 2, 1
assert.same { lines[1], lines[2] }, range
describe 'for_text_range(start_pos, end_pos)', ->
it 'returns a table with lines between [start_pos, end_pos]', ->
lines = buffer('one\ntwo\nthree').lines
range = lines\for_text_range 2, 6
assert.same { lines[1], lines[2] }, range
it 'start_pos can be greater than end_pos', ->
lines = buffer('one\ntwo\nthree').lines
range = lines\for_text_range 6, 1
assert.same { lines[1], lines[2] }, range
it 'does not include lines only touched at the start or end positions', ->
lines = buffer('one\ntwo\nthree').lines
range = lines\for_text_range lines[1].end_pos, lines[3].start_pos
assert.same { lines[2] }, range
describe 'append(text)', ->
it 'append(text) appends <text> with the necessary newlines', ->
b = buffer 'one\ntwo'
b.lines\append 'three'
assert.equal b.text, 'one\ntwo\nthree\n'
b = buffer 'one\ntwo\n'
b.lines\append 'three'
assert.equal b.text, 'one\ntwo\nthree\n'
it 'returns a line object for the newly appended line', ->
b = buffer 'line'
line = b.lines\append 'omega'
assert.equal line, b.lines[2]
describe 'insert(line_nr, text)', ->
it 'inserts a new line at <nr> with <text>', ->
b = buffer 'one\ntwo'
b.lines\insert 1, 'half'
assert.equal b.text, 'half\none\ntwo'
b.lines\insert 3, '1.5'
assert.equal b.text, 'half\none\n1.5\ntwo'
it 'appends the line if line_nr is just beyond the last line', ->
b = buffer 'first\nsecond'
b.lines\insert 3, 'foo'
assert.equal b.text, 'first\nsecond\nfoo\n'
it 'raises an error if <line_nr> is invalid', ->
b = buffer 'first\nsecond'
assert.raises 'Invalid', -> b.lines\insert 0, 'foo'
assert.raises 'Invalid', -> b.lines\insert 4, 'foo'
it 'returns a line object for the newly inserted line', ->
b = buffer 'line'
line = b.lines\insert 1, 'alpha'
assert.equal line, b.lines[1]
it 'supports iterating using ipairs', ->
b = buffer 'one\ntwo\nthree'
for i, line in ipairs b.lines
assert.equal line, b.lines[i]
it 'supports iterating using pairs', ->
b = buffer 'one\ntwo\nthree'
for i, line in pairs b.lines
assert.equal line, b.lines[i]
| 33.625926 | 91 | 0.616037 |
8208ca64176d2f9bd88e5a49894f70c525577828 | 167 | Font = require "Lutron/Font/Font"
class FontBold extends Font
new: () =>
super 'Lutron/Font/FontBold.png', " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789*:|=-<>./'\"+"
| 27.833333 | 90 | 0.682635 |
aed0ecde3beae4a3699b6ced48e78e37417a2805 | 6,180 | build = (settings) ->
slotsWide = settings\getLayoutColumns()
slotsTall = settings\getLayoutRows()
numSlots = slotsWide * slotsTall
slotWidth = settings\getLayoutWidth()
slotHeight = settings\getLayoutHeight()
horizontal = settings\getLayoutHorizontal()
skinWidth = slotsWide * slotWidth
skinHeight = slotsTall * slotHeight
-- Variables
contents = table.concat({
'[Variables]'
('SkinWidth=%d')\format(skinWidth)
('SkinHeight=%d')\format(skinHeight)
('SlotWidth=%d')\format(slotWidth)
('SlotHeight=%d')\format(slotHeight)
('SlotOverlayTextSize=%d')\format(math.round(12 * slotWidth / 320))
'\n'
}, '\n')
-- Skin enabler (1)
skinSlideAnimation = settings\getSkinSlideAnimation()
if skinSlideAnimation ~= ENUMS.SKIN_ANIMATIONS.NONE
enablerX = switch skinSlideAnimation
when ENUMS.SKIN_ANIMATIONS.SLIDE_UP then 0
when ENUMS.SKIN_ANIMATIONS.SLIDE_RIGHT then skinWidth - 1
when ENUMS.SKIN_ANIMATIONS.SLIDE_DOWN then 0
when ENUMS.SKIN_ANIMATIONS.SLIDE_LEFT then 0
else
assert(nil, 'settings.build_main_skin.build')
enablerY = switch skinSlideAnimation
when ENUMS.SKIN_ANIMATIONS.SLIDE_UP then 0
when ENUMS.SKIN_ANIMATIONS.SLIDE_RIGHT then 0
when ENUMS.SKIN_ANIMATIONS.SLIDE_DOWN then skinHeight - 1
when ENUMS.SKIN_ANIMATIONS.SLIDE_LEFT then 0
else
assert(nil, 'settings.build_main_skin.build')
enablerWidth = switch skinSlideAnimation
when ENUMS.SKIN_ANIMATIONS.SLIDE_UP then skinWidth
when ENUMS.SKIN_ANIMATIONS.SLIDE_RIGHT then 1
when ENUMS.SKIN_ANIMATIONS.SLIDE_DOWN then skinWidth
when ENUMS.SKIN_ANIMATIONS.SLIDE_LEFT then 1
else
assert(nil, 'settings.build_main_skin.build')
enablerHeight = switch skinSlideAnimation
when ENUMS.SKIN_ANIMATIONS.SLIDE_UP then 1
when ENUMS.SKIN_ANIMATIONS.SLIDE_RIGHT then skinHeight
when ENUMS.SKIN_ANIMATIONS.SLIDE_DOWN then 1
when ENUMS.SKIN_ANIMATIONS.SLIDE_LEFT then skinHeight
else
assert(nil, 'settings.build_main_skin.build')
contents ..= table.concat({
'[SkinEnabler]'
'Meter=Image'
'SolidColor=0,0,0,1'
('X=%d')\format(enablerX)
('Y=%d')\format(enablerY)
('W=%d')\format(enablerWidth)
('H=%d')\format(enablerHeight)
'MouseOverAction=[!CommandMeasure "Script" "OnMouseOver()"]'
'MouseLeaveAction=[!CommandMeasure "Script" "OnMouseLeaveEnabler()"]'
'\n'
}, '\n')
-- Background (1)
contents ..= table.concat({
'[SlotsBackground]'
'Meter=Image'
'SolidColor=#SlotBackgroundColor#'
'X=0'
'Y=0'
'W=#SkinWidth#'
'H=#SkinHeight#'
'MouseScrollUpAction=[!CommandMeasure "Script" "OnScrollSlots(-1)"]'
'MouseScrollDownAction=[!CommandMeasure "Script" "OnScrollSlots(1)"]'
'MouseOverAction=[!CommandMeasure "Script" "OnMouseOver()"]'
'\n'
}, '\n')
-- Animation slot, mobile (1)
contents ..= table.concat({
'[SlotAnimation]'
'Meter=Image'
'ImageName='
'SolidColor=0,0,0,1'
'X=0'
'Y=0'
'W=0'
'H=0'
'PreserveAspectRatio=2'
'\n'
}, '\n')
-- Background with cutout (1)
contents ..= table.concat({
'[SlotsBackgroundCutout]'
'Meter=Shape'
'X=([SlotsBackground:X])'
'Y=([SlotsBackground:Y])'
'Shape=Rectangle 0,0,#SkinWidth#,#SkinHeight# | Fill Color #SlotBackgroundColor# | StrokeWidth 0'
'Shape2=Rectangle 0,0,0,0 | StrokeWidth 0'
'Shape3=Combine Shape | XOR Shape2'
'DynamicVariables=1'
'\n'
}, '\n')
-- Regular slots, static (variable)
index = 1
leftMouseAction = switch settings\getDoubleClickToLaunch()
when true then 'LeftMouseDoubleClickAction'
else 'LeftMouseUpAction'
gameSlot = (row, column) ->
slot = {}
-- String
table.extend(slot, {
('[Slot%dText]')\format(index)
'Meter=String'
'Text='
'SolidColor=0,0,0,1'
('X=([SlotsBackground:X] + %d)')\format((column - 1) * slotWidth + math.floor(slotWidth / 2))
('Y=([SlotsBackground:Y] + %d)')\format((row - 1) * slotHeight + math.floor(slotHeight / 2))
('W=%d')\format(slotWidth)
('H=%d')\format(slotHeight)
'FontSize=#SlotOverlayTextSize#'
'FontColor=#SlotOverlayTextColor#'
'StringAlign=CenterCenter'
'StringEffect=Shadow'
'StringStyle=Bold'
'AntiAlias=1'
'ClipString=1'
'DynamicVariables=1'
('%s=[!CommandMeasure "Script" "OnLeftClickSlot(%d)"]')\format(leftMouseAction, index)
('MiddleMouseUpAction=[!CommandMeasure "Script" "OnMiddleClickSlot(%d)"]')\format(index)
('MouseOverAction=[!CommandMeasure "Script" "OnHoverSlot(%d)"]')\format(index)
('MouseLeaveAction=[!CommandMeasure "Script" "OnLeaveSlot(%d)"]')\format(index)
('Group=Slots|Slot%d')\format(index)
})
table.insert(slot, '')
-- Image
table.extend(slot, {
('[Slot%dImage]')\format(index)
'Meter=Image'
'ImageName='
'SolidColor=0,0,0,1'
('X=([SlotsBackground:X] + %d)')\format((column - 1) * slotWidth)
('Y=([SlotsBackground:Y] + %d)')\format((row - 1) * slotHeight)
('W=%d')\format(slotWidth)
('H=%d')\format(slotHeight)
'PreserveAspectRatio=2'
'DynamicVariables=1'
('Group=Slots|Slot%d')\format(index)
})
table.insert(slot, '\n')
return slot
if horizontal
for row = 1, slotsTall
for column = 1, slotsWide
contents ..= table.concat(gameSlot(row, column), '\n')
index += 1
else
for column = 1, slotsWide
for row = 1, slotsTall
contents ..= table.concat(gameSlot(row, column), '\n')
index += 1
-- Overlay slot, mobile (1)
overlay = {}
-- Image
table.extend(overlay, {
'[SlotOverlayImage]'
'Meter=Image'
'ImageName='
'SolidColor=#SlotOverlayColor#'
'X=0'
'Y=0'
('W=%d')\format(slotWidth)
('H=%d')\format(slotHeight)
'PreserveAspectRatio=2'
'Group=SlotOverlay'
})
table.insert(overlay, '')
-- String
table.extend(overlay, {
'[SlotOverlayText]'
'Meter=String'
'Text='
('X=%dr')\format(math.floor(slotWidth / 2))
('Y=%dr')\format(math.floor(slotHeight / 2))
('W=%d')\format(slotWidth)
('H=%d')\format(slotHeight)
'FontSize=#SlotOverlayTextSize#'
'FontColor=#SlotOverlayTextColor#'
'StringAlign=CenterCenter'
'StringEffect=Shadow'
'StringStyle=Bold'
'AntiAlias=1'
'ClipString=1'
'Group=SlotOverlay'
})
table.insert(overlay, '')
contents ..= table.concat(overlay, '\n')
return contents
return build
| 30 | 99 | 0.685113 |
e98074595da3e49dd2b9f903d18b2758643bf639 | 3,139 | config = (require 'lapis.config').get!
mail = require 'resty.mail'
validation = require 'validation'
http = require "lapis.nginx.http"
secrets = require 'secrets'
import from_json from require "lapis.util"
import to_json from require 'lapis.util'
import decode_with_secret, encode_with_secret from require 'lapis.util.encoding'
import validate_functions, validate from require 'lapis.validate'
for i in *{ 'is_email' }
validate_functions[i] = validation[i]
import NewsletterApplications from require 'models'
class SubmitApplication
submit: (params, model, url_builder) =>
errors = { }
ret = validate params, {
{ 'firstname', exists: true, max_length: 255, 'invalid_name' },
{ 'lastname', exists: true, max_length: 255, 'invalid_name' },
{ 'email', exists: true, max_length: 255, is_email: true, 'invalid_email' }
}
-- check recaptcha
res = http.simple {
url: "https://www.google.com/recaptcha/api/siteverify"
method: 'POST'
body: {
secret: secrets.recaptcha_secret
response: params['g-recaptcha-response']
}
}
if res and not res.error
ok, res = pcall ->
from_json res
if not ok
print "Failed to parse reCAPTCHA reply as JSON: " .. res
return nil, { 'internal_error' }
if not res.success
print "reCAPTCHA failed: " .. table.concat(res['error-codes'], ', ')
return nil, { 'bad_captcha' }
else
print "Failed to send reCAPTCHA verify request: " .. res.error
return nil, { 'internal_error' }
if ret
errors[e] = true for e in *ret
err_array = { }
for k, _ in pairs errors
table.insert err_array, k
return nil, err_array if #err_array > 0
prev_app, err = NewsletterApplications\find email: params.email
if prev_app
return nil, { 'duplicate_application' }
if err
return nil, { 'internal_error' }
local application, err
with params
application, err = NewsletterApplications\create {
first_name: .firstname,
last_name: .lastname,
email: .email
}
if not application
return nil, { 'internal_error' }
mailer, err = mail.new
host: config.smtp_server,
port: config.smtp_port,
starttls: true,
username: config.smtp_username,
password: config.smtp_password
if not mailer
print err
return nil, { 'internal_error' }
local msg
with model.email
msg =
to: { params.email }
from: config.smtp_from_newsletter
subject: .subject
text: .text
ret, err = mailer\send msg
if not ret
print err
application\delete!
return nil, { 'internal_error' }
else true
| 30.182692 | 87 | 0.554954 |
35768c67a4ad3d5029e75a7c41f5d0bd5d49a3ef | 166 | big = zb2rhnKgZ66iwb9AGyxTMP6zPbkwxe5jKxrKYTofJqisdhfJU
bigToNum = zb2rhhuEY9zoiu9rsJK7Mi3UGrQbRYTTyfFwiGyxdx1SP9raW
hex =>
(div (bigToNum (big hex)) (pow 10 18))
| 27.666667 | 60 | 0.819277 |
76f491f798b31df5f26568e07891158b27764eb9 | 651 | package.path = "?.lua;?/init.lua;" .. package.path
skooma = require 'skooma'
_ = skooma.env
NAME = skooma.ast.name
describe 'skooma', ->
describe 'environment', ->
pending 'proxy', ->
it 'returns AST nodes', ->
assert.is.equal "h1", _.h1![NAME]
pending 'handles nested table arguments'
describe 'serializer', ->
it 'returns a table', ->
it 'treats empty XML tags correctly', ->
assert.is.equal '<div><span/></div>',
skooma.serialize.xml(_.div(_.span))\concat!
it 'concatenates attribute sequences', ->
assert.is.equal '<span class="foo bar baz"/>',
skooma.serialize.xml(_.span(class: {"foo", "bar", "baz"}))\concat!
| 29.590909 | 70 | 0.645161 |
67016674b1ec727504ac223e4e4fa25e756faafc | 351 | api_key = 'dc6zaTOxFJmzC'
PRIVMSG:
'^%pgiphy (.+)': (source, destination, arg) =>
ivar2.util.simplehttp "http://api.giphy.com/v1/gifs/search?q=#{ivar2.util.urlEncode arg}&api_key=#{api_key}", (json) ->
data = ivar2.util.json.decode json
if not data then return
url = data.data[1].images.original.url
say url
| 29.25 | 125 | 0.626781 |
61d3dcade33b95dafe8ea27786d74d0da476f31a | 504 | -- testing `return` propagation
-> x for x in *things
-> [x for x in *things]
-- doesn't make sense on purpose
do
return x for x in *things
do
return [x for x in *things]
do
return {x,y for x,y in *things}
->
if a
if a
a
else
b
elseif b
if a
a
else
b
else
if a
a
else
b
do
return if a
if a
a
else
b
elseif b
if a
a
else
b
else
if a
a
else
b
-> a\b
do a\b
| 9 | 33 | 0.46627 |
988c3da48a0c9d17ebc003d9fec63cdd5147b11c | 124 | config = require "lapis.config"
config "docker", ->
port os.getenv "PORT"
oleg ->
host "127.0.0.1"
port 38080
| 13.777778 | 31 | 0.604839 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.