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
|
---|---|---|---|---|---|
ee0d66225786631310f88f13ab784536941e050e | 137 |
items = {1,2,3,4,5,6}
out = {k,k*2 for k in items}
x = hello: "world", okay: 2323
copy = {k,v for k,v in pairs x when k != "okay"}
| 13.7 | 49 | 0.547445 |
1829721f9e6392476e909333d5079303b214fd09 | 8,510 | -- dev/bgfxgen.moon
--
-- generate bgfx auxilliary files
-- assumes truss has been built into "../build/"
sutil = require "util/string.t"
argparse = require "util/argparse.t"
genconstants = require "dev/genconstants.t"
BGFX_PATH = "/bgfx_EXTERNAL-prefix/src/bgfx_EXTERNAL"
os_exec = (cmd) ->
f = io.popen cmd, "r"
ret = f\read "*all"
f\close!
ret
os_copy = (srcfn, destfn) ->
cmd = if truss.os == "Windows"
"copy \"#{srcfn\gsub("/", "\\")}\" \"#{destfn\gsub("/", "\\")}\" /y"
else
"cp \"#{srcfn}\" \"#{destfn}\""
print cmd
print os_exec cmd
copy_files = (buildpath) ->
srcpath = "#{buildpath}#{BGFX_PATH}"
os_copy "#{srcpath}/include/bgfx/defines.h", "include/bgfxdefines.h"
os_copy "#{srcpath}/examples/common/shaderlib.sh", "shaders/raw/common/shaderlib.sh"
os_copy "#{srcpath}/src/bgfx_shader.sh", "shaders/raw/common/bgfx_shader.sh"
os_copy "#{srcpath}/src/bgfx_compute.sh", "shaders/raw/common/bgfx_compute.sh"
rawload = (fn) -> (io.open fn, "rt")\read "*a"
DEFINE_PATT = "^#define%s*([%w_]*)[^%(%w_]"
get_define_names = () ->
-- assumes `defines.h` has been copied to `include/bgfxdefines.h`
defnames = {}
for line in *(sutil.split_lines rawload "include/bgfxdefines.h")
name = line\match DEFINE_PATT
if name and name != ""
table.insert defnames, name
defnames
get_constants = () -> genconstants.gen_constants_file get_define_names!
to_snake_case = (s) ->
s_first = s\sub(1,1)\upper!
s_rem = s\sub 2, -1
s = s_first .. s_rem
table.concat [v\lower! for v in s\gmatch "[%u%d]+%l*"], "_"
lower_snake = (s) -> (to_snake_case s)\lower!
upper_snake = (s) -> (to_snake_case s)\upper!
remove_comment = (s) ->
fpos = s\find "%-%-"
if fpos
s = s\sub 1, fpos-1
sutil.strip s
fix5p1 = (data) ->
lines = sutil.split_lines data
outlines = {}
for linepos = 1, #lines
curline = sutil.strip lines[linepos]
if (curline\sub 1,2) == "()"
outlines[#outlines] = (remove_comment outlines[#outlines]) .. curline
else
outlines[#outlines+1] = lines[linepos]
temp = io.open "bleh.lua", "wt"
temp\write table.concat outlines, "\n"
temp\close!
table.concat outlines, "\n"
_flatten = (dest, list) ->
for v in *list
if type(v) == 'table' then
_flatten dest, v
else
dest[#dest+1] = v
dest
flatten = (lists) -> _flatten {}, lists
conflatten = (lists) -> table.concat (flatten lists), "\n"
ordered_concat = (t, keyorder, sep) ->
table.concat [t[k] for k in *keyorder], (sep or "\n\n")
key_sorted_concat = (t, sep) ->
sorted_keys = [k for k, v in pairs t]
table.sort sorted_keys
ordered_concat t, sorted_keys, sep
exec_in = (env, fn) ->
chunk, err = loadstring fix5p1 rawload fn
if not chunk
truss.error "Error parsing #{fn}: #{err}"
setfenv chunk, env
chunk! or env
load_idl = (buildpath) ->
env = truss.extend_table {}, truss.clean_subenv
path = buildpath .. BGFX_PATH
print "Loading IDL from [#{path}]"
idl = exec_in env, "#{path}/scripts/idl.lua"
exec_in idl, "#{path}/scripts/bgfx.idl"
is_api_func = (line) ->
parts = sutil.split " ", line
if parts[1] != "BGFX_C_API" then return nil
api_key = (parts[2] != "const" and parts[3]) or parts[4] or line
api_key = (sutil.split "%(", api_key)[1]
(table.concat [p for p in *parts[2,]], " "), api_key
get_functions = (buildpath) ->
-- generating function signatures from the IDL is too much of a pain
-- instead just read them from the C-api header
path = "#{buildpath}#{BGFX_PATH}/include/bgfx/c99/bgfx.h"
api_funcs = {}
for line in *(sutil.split_lines rawload path)
api_line, api_order_key = is_api_func line
if api_line then api_funcs[api_order_key] = api_line
key_sorted_concat api_funcs, "\n"
gen_enum = (e) ->
format_val = if e.underscore
(v) -> upper_snake v
else
(v) -> v\upper!
name = "bgfx_#{lower_snake e.name}"
conflatten {
"typedef enum #{name} {",
(table.concat [" #{name\upper!}_#{format_val v.name}" for v in *e.enum], ",\n") .. ",",
" #{name\upper!}_COUNT",
"} #{name}_t;"
}
gen_enums = (idl) ->
enums = {t.name, gen_enum t for t in *idl.types when t.enum}
key_sorted_concat enums, "\n\n"
gen_handle = (handle) ->
name = "bgfx_#{lower_snake handle.name}"
"typedef struct #{name} { uint16_t idx; } #{name}_t;"
gen_handles = (idl) ->
handles = {t.name, gen_handle t for t in *idl.types when t.handle}
key_sorted_concat handles, "\n"
is_pointer = (s) -> ((s\sub -1) == "*") and (s\sub 1, -2)
is_const = (s) -> ((s\sub 1, 5) == "const") and (s\sub 7)
is_enum = (s) ->
parts = sutil.split "::", s
if #parts == 2 and (parts[2]\sub 1, 4) == "Enum"
parts[1]
else
false
is_array = (s) ->
array_start = s\find "%["
if not array_start then return nil, nil
return (s\sub 1, array_start-1), (s\sub array_start+1, -2)
FIXED_TYPES = {
"float": "float"
"double": "double"
"char": "char"
"bool": "bool"
"CallbackI": "bgfx_callback_interface_t"
"bx::AllocatorI": "bgfx_allocator_interface_t"
"void": "void"
}
for itype in *{8, 16, 32, 64}
for qualifier in *{"uint", "int"}
tname = "#{qualifier}#{itype}_t"
FIXED_TYPES[tname] = tname
format_count = (count) ->
parts = sutil.split "::", count
if #parts == 2 -- assume ::Count
"BGFX_#{upper_snake parts[1]}_COUNT"
else
count
namespaced_structs = {}
format_type = (t, parent) ->
subtype, count = is_array t
if subtype
(format_type subtype, parent), (format_count count)
else
pointer_type = is_pointer t
if pointer_type
t = pointer_type
const_type = is_const t
if const_type
t = const_type
res = ""
if FIXED_TYPES[t]
res = FIXED_TYPES[t]
else
res = lower_snake ((is_enum t) or t)
if parent and namespaced_structs["#{parent}_#{res}"]
res = "#{parent}_#{res}"
res = "bgfx_" .. res .. "_t"
if pointer_type
res = res .. "*"
if const_type
res = "const " .. res
res
format_field = (f, parent) ->
argtype, argcount = format_type f.fulltype, parent
name = f.name
if argcount
name = "#{name}[#{argcount}]"
" #{argtype} #{name};"
gen_struct = (struct) ->
name = lower_snake struct.name
if struct.namespace
name = "#{lower_snake struct.namespace}_#{name}"
namespaced_structs[name] = true
if #struct.struct == 0
return name, "typedef struct bgfx_#{name}_s bgfx_#{name}_t;"
name, conflatten {
"typedef struct bgfx_#{name}_s {",
[format_field f, name for f in *struct.struct]
"} bgfx_#{name}_t;"
}
gen_structs = (idl) ->
structs = {}
for t in *idl.types
if not t.struct then continue
name, struct = gen_struct t
table.insert structs, struct
table.concat structs, "\n\n"
PREAMBLE = [[
/*
* BGFX Copyright 2011-2021 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
*
* This header is slightly modified to make it easier for Terra
* to digest; it is automatically generated from the 'real' BGFX
* headers and IDL by `dev/bgfxgen.moon`.
*/
#ifndef BGFX_C99_H_HEADER_GUARD
#define BGFX_C99_H_HEADER_GUARD
//#include <stdarg.h> // va_list
#include <stdbool.h> // bool
#include <stdint.h> // uint32_t
#include <stdlib.h> // size_t
#undef UINT32_MAX
#define UINT32_MAX 4294967295
#define BGFX_UINT32_MAX 4294967295
#define BGFX_INVALID_HANDLE 0xffff
typedef uint16_t bgfx_view_id_t;
typedef struct bgfx_interface_vtbl bgfx_interface_vtbl_t;
typedef struct bgfx_callback_interface bgfx_callback_interface_t;
typedef struct bgfx_callback_vtbl bgfx_callback_vtbl_t;
typedef struct bgfx_allocator_interface bgfx_allocator_interface_t;
typedef struct bgfx_allocator_vtbl bgfx_allocator_vtbl_t;
typedef void (*bgfx_release_fn_t)(void* _ptr, void* _userData);
]]
gen_header = (buildpath) ->
idl = load_idl buildpath
conflatten {
PREAMBLE,
"\n\n/* Enums: */\n",
gen_enums idl,
"\n\n/* Handle types: */\n",
gen_handles idl,
"\n\n/* Structs: */\n",
gen_structs idl,
"\n\n/* Functions: */\n",
get_functions buildpath,
"\n",
"#endif // BGFX_C99_H_HEADER_GUARD"
}
export init = ->
bpath = "../build"
print "Copying files"
copy_files bpath
print "Generating include/bgfx_truss.c99.h"
truss.save_string "include/bgfx_truss.c99.h", (gen_header bpath)
print "Generating scripts/gfx/bgfx_constants.t"
truss.save_string "scripts/gfx/bgfx_constants.t", get_constants!
print "Done."
truss.quit!
export update = ->
truss.quit! | 27.62987 | 94 | 0.649941 |
1a92c59d050b89daa73dc4dcc170c84bd3461151 | 2,376 | (DEBUG) ->
unless DEBUG
inspect = require "inspect"
return {
:inspect, log: (->), processor: {sign: process: (x)->(x)}
}
import inspect from require "debugkit.inspect"
import logger from require "debugkit.log"
import style from require "ansikit.style"
io.stdout\setvbuf "no"
typekitLgr = logger.default!
typekitLgr.name = "typekit"
typekitLgr.header = (T) => style "%{bold green}#{@name}%{blue}.%{white}#{T} %{yellow}$ "
typekitLgr.time = => ""
typekitLgr.exclude = {
-- parser.nameFor
"parser.nameFor"
"parser.nameFor #got"
-- parser.binarize
"parser.binarize #loop"
"parser.binarize #got"
"parser.binarize #sig"
"parser.binarize #ret"
"parser.binarize #name"
-- parser.rebinarize
"parser.rebinarize #ch"
-- parser.checkParenthesis
"parser.checkParenthesis #match"
"parser.checkParenthesis #over"
"parser.checkParenthesis #status"
"parser.checkParenthesis #ret"
"parser.checkParenthesis #got"
-- parser.checkList
"parser.checkList #match"
"parser.checkList #over"
"parser.checkList #status"
"parser.checkList #ret"
"parser.checkList #got"
-- parser.checkTable
"parser.checkTable #match"
"parser.checkTable #over"
"parser.checkTable #status"
"parser.checkTable #ret"
"parser.checkTable #got"
-- parser.compareSide
"parser.compareSide #got"
"parser.compareSide #types"
"parser.compareSide #ret"
"parser.compareSide #const"
-- parser.compareConstraints
"parser.compareConstraints #got"
-- type.resovleSynonym
"type.resolveSynonym #got"
-- type.typeof.resolve
"type.typeof.resolve #got"
"type.typeof.resolve #resolved"
-- sign
--"sign #got"
"sign #fn"
"sign #cache"
-- global
"global.initG"
"global.addReference #got"
}
log = typekitLgr!
processor = {
sign: process: (path) => -- item(@), path
i = path[#path]
--
return nil if i == "type"
return nil if i == "call"
return nil if i == "patterns"
return {@__type, @__kind, @__newindex} if i == inspect.METATABLE
return @
match: process: (path) => -- item(@), path
i = path[#path]
--
return nil if i == "__parent"
return nil if i == "parent"
return @
}
{ :inspect, :log, :processor } | 26.696629 | 91 | 0.612374 |
98cb2d656a9e4a8fcc78ec6ffa34ceaca59a494a | 4,026 | eventLoop = EventLoop!
activeHeight = settings['hover-zone-height']
ignoreRequestDisplay = =>
unless Mouse.inWindow
return false
if Mouse.dead
return false
return @containsPoint Mouse.x, Mouse.y
bottomZone = ActivityZone =>
@reset 0, Window.h - activeHeight, Window.w, activeHeight
hoverTimeZone = ActivityZone =>
@reset 0, Window.h - activeHeight, Window.w, activeHeight,
ignoreRequestDisplay
topZone = ActivityZone =>
@reset 0, 0, Window.w, activeHeight,
ignoreRequestDisplay
-- This is kind of ugly but I have gone insane and don't care any more.
-- Watch the rapidly declining quality of this codebase in realtime.
local chapters, progressBar, barCache, barBackground, elapsedTime, remainingTime, hoverTime
if settings['enable-bar']
-- this order is recorded and (ab)used by BarBase and
-- ProgressBarBackground
progressBar = ProgressBar!
barCache = ProgressBarCache!
barBackground = ProgressBarBackground!
bottomZone\addUIElement barBackground
-- this is not runtime reconfigurable, currently
if settings['bar-cache-position'] == 'overlay'
bottomZone\addUIElement progressBar
bottomZone\addUIElement barCache
else
bottomZone\addUIElement barCache
bottomZone\addUIElement progressBar
mp.add_key_binding "c", "toggle-inactive-bar", ->
BarBase\toggleInactiveVisibility!
if settings['enable-chapter-markers']
chapters = Chapters!
bottomZone\addUIElement chapters
if settings['enable-elapsed-time']
elapsedTime = TimeElapsed!
bottomZone\addUIElement elapsedTime
if settings['enable-remaining-time']
remainingTime = TimeRemaining!
bottomZone\addUIElement remainingTime
if settings['enable-hover-time']
hoverTime = HoverTime!
hoverTimeZone\addUIElement hoverTime
title = nil
if settings['enable-title']
title = Title!
bottomZone\addUIElement title
topZone\addUIElement title
if settings['enable-system-time']
systemTime = SystemTime!
bottomZone\addUIElement systemTime
topZone\addUIElement systemTime
-- The order of these is important, because the order that elements are added to
-- eventLoop matters, because that controls how they are layered (first element
-- on the bottom).
eventLoop\addZone hoverTimeZone
eventLoop\addZone bottomZone
eventLoop\addZone topZone
notFrameStepping = false
if settings['pause-indicator']
PauseIndicatorWrapper = ( event, paused ) ->
if notFrameStepping
PauseIndicator eventLoop, paused
elseif paused
notFrameStepping = true
mp.add_key_binding '.', 'step-forward',
->
notFrameStepping = false
mp.commandv 'frame_step',
{ repeatable: true }
mp.add_key_binding ',', 'step-backward',
->
notFrameStepping = false
mp.commandv 'frame_back_step',
{ repeatable: true }
mp.observe_property 'pause', 'bool', PauseIndicatorWrapper
streamMode = false
initDraw = ->
-- this forces sizing activityzones and ui elements
if chapters
chapters\createMarkers!
if title
title\_forceUpdatePlaylistInfo!
title\print!
notFrameStepping = true
-- duration is nil for streams of indeterminate length
duration = mp.get_property 'duration'
if not (streamMode or duration)
BarAccent.changeBarSize 0
if progressBar
bottomZone\removeUIElement progressBar
bottomZone\removeUIElement barCache
bottomZone\removeUIElement barBackground
if chapters
bottomZone\removeUIElement chapters
if hoverTime
hoverTimeZone\removeUIElement hoverTime
if remainingTime
bottomZone\removeUIElement remainingTime
streamMode = true
elseif streamMode and duration
BarAccent.changeBarSize settings['bar-height-active']
if progressBar
bottomZone\addUIElement barBackground
bottomZone\addUIElement barCache
bottomZone\addUIElement progressBar
if chapters
bottomZone\addUIElement chapters
if hoverTime
hoverTimeZone\addUIElement hoverTime
if remainingTime
bottomZone\addUIElement remainingTime
streamMode = false
mp.command 'script-message-to osc disable-osc'
eventLoop\generateUIFromZones!
eventLoop\resize!
eventLoop\redraw!
mp.register_event 'file-loaded', initDraw
| 27.575342 | 91 | 0.785395 |
b8a70df150bf6e5683722174d414cd09d6958d67 | 4,357 | fiber = require 'fiber'
http_client = require 'http.client'
json = require 'json'
table_insert = table.insert
UPDATE_TYPES = {
MESSAGE: 'message'
EDITED_MESSAGE: 'edited_message'
CHANNEL_POST: 'channel_post'
EDITED_CHANNEL_POST: 'edited_channel_post'
INLINE_QUERY: 'inline_query'
CHOSEN_INLINE_RESULT: 'chosen_inline_result'
CALLBACK_QUERY: 'callback_query'
SHIPPING_QUERY: 'shipping_query'
PRE_CHECKOUT_QUERY: 'pre_checkout_query'
POLL: 'poll'
}
UPDATE_TYPES_SET = {t, true for _, t in pairs UPDATE_TYPES}
class TelegramBot
url_template: 'https://api.telegram.org/bot%s/'
call_timeout: 10
poll_timeout: 30
new: (api_token, call_timeout, poll_timeout) =>
if call_timeout
@call_timeout = call_timeout
if poll_timeout
@poll_timeout = poll_timeout
@base_url = @url_template\format(api_token)
@client = http_client.new!
@_update_channel = fiber.channel!
-- generic API method calls
call: (method, body, content_type, timeout) =>
url = @base_url .. method
headers =
['user-agent']: 'taragram/0.0.0'
['content-type']: content_type
['accept']: 'application/json'
if not timeout
timeout = @call_timeout
resp = @client\request 'POST', url, body, {
timeout: timeout
headers: headers
}
if not resp
return nil, 'unknown http.client error'
ok, decoded = pcall json.decode, resp.body
if not ok
return nil, '[HTTP:%s] %s'\format(resp.status, resp.reason)
if not decoded.ok
return nil, '[API:%s] %s'\format(
decoded.error_code, decoded.description)
return decoded.result
call_json: (method, params, timeout) =>
body = json.encode params
return @call method, body, 'application/json', timeout
-- concrete API method calls
get_me: => @call 'getMe'
send_message: (chat_id, text, params) =>
params = @_prepare_params params
params.chat_id = tonumber chat_id
params.text = text
return @call_json 'sendMessage', params
answer_callback_query: (callback_query_id, params) =>
params = @_prepare_params params
params.callback_query_id = callback_query_id
return @call_json 'answerCallbackQuery', params
-- polling methods
start_polling: (fiber_name, allowed_updates, timeout) =>
if @_polling_fiber
return nil, 'already polling'
if not allowed_updates
allowed_updates = {}
if not timeout
timeout = @poll_timeout
fb = fiber.create @_poll, @, allowed_updates, timeout
fb\name fiber_name
@_polling_fiber = fb
return @_update_channel
stop_polling: =>
fb = @_polling_fiber
if not fb
return nil, 'polling is not started'
fb\cancel!
@_polling_fiber = nil
return true
_poll: (allowed_updates, timeout) =>
offset = nil
while true
fiber.testcancel!
updates, offset = @_poll_once allowed_updates, offset, timeout
if updates
@_update_channel\put upd for upd in *updates
_poll_once: (allowed_updates, offset, timeout) =>
updates, err = @call_json 'getUpdates', {
offset: offset
limit: 100
timeout: timeout
allowed_updates: allowed_updates
}, timeout + 5
if not updates
return nil, offset, err
if #updates == 0
return nil, offset
extracted_updates = {}
for update in *updates
local update_type, object
for key, value in pairs update
if key ~= 'update_id' and UPDATE_TYPES_SET[key]
update_type = key
object = value
break
assert object, 'cannot find any object in Update'
table_insert extracted_updates, {type: update_type, :object}
offset = updates[#updates].update_id + 1
return extracted_updates, offset
_prepare_params: (params) =>
if not params
return {}
return {k, v for k, v in pairs params}
:UPDATE_TYPES, :TelegramBot
| 30.048276 | 74 | 0.599725 |
32a4a086679215f5d482851f2bb75f7374db04c2 | 11,047 | require "busted"
require "tests.mock_love"
import LP from require "LunoPunk.LP"
import Scene from require "LunoPunk.Scene"
import Entity from require "LunoPunk.Entity"
import Graphic from require "LunoPunk.Graphic"
import Mask from require "LunoPunk.Mask"
import instance from require "LunoPunk.utils.moonscript"
import Rectangle from require "LunoPunk.geometry.Rectangle"
entity_sanity_check = ->
e = Entity!
assert.are.equal 0, e\x!
assert.are.equal 0, e\y!
e
describe "Entity", ->
e = nil
before_each ->
e = entity_sanity_check!
it "construct", ->
assert.are.equal true, e.active
assert.are.equal false, e.autoClear
assert.are.equal 0, e\x!
assert.are.equal 0, e\y!
assert.are.equal 0, e.originX
assert.are.equal 0, e.originY
assert.are.equal 0, e.width
assert.are.equal 0, e.height
assert.are.equal true, e.visible
assert.are.equal true, e.collidable
assert.are.equal false, e.followCamera
-- Follow Camera coverage
e.followCamera = true
assert.are.equal 0, e\x!
assert.are.equal 0, e\y!
LP.camera.x += 1
assert.are.equal 1, e\x!
assert.are.equal 0, e\y!
LP.camera.y -= 1
assert.are.equal -1, e\y!
e.followCamera = false
assert.are.equal 0, e\x!
assert.are.equal 0, e\y!
e = Entity 10, 15
assert.are.equal 10, e\x!
assert.are.equal 15, e\y!
assert.are.equal 0, e.originX
assert.are.equal 0, e.originY
assert.are.equal 0, e.width
assert.are.equal 0, e.height
g = Graphic!
g.x, g.y = 25, 30
e = Entity 10, 15, g
assert.are.equal g, e\graphic!
assert.are.equal 10, e\x!
assert.are.equal 15, e\y!
assert.are.equal 0, e.originX
assert.are.equal 0, e.originY
assert.are.equal 0, e.width
assert.are.equal 0, e.height
m = Mask!
e = Entity 10, 15, g, m
assert.are.equal m, e\mask!
assert.are.equal 10, e\x!
assert.are.equal 15, e\y!
assert.are.equal 0, e.originX
assert.are.equal 0, e.originY
assert.are.equal 0, e.width
assert.are.equal 0, e.height
it "accessors", ->
assert.are.equal 0, e\halfWidth!
e.width = 10
assert.are.equal 5, e\halfWidth!
assert.are.equal 0, e\halfHeight!
e.height = 20
assert.are.equal 10, e\halfHeight!
assert.are.equal 5, e\centerX!
assert.are.equal 10, e\centerY!
e.originX = 10
assert.are.equal -5, e\centerX!
e.originY = 10
assert.are.equal 0, e\centerY!
e\x 5
assert.are.equal 0, e\centerX!
e\y 10
assert.are.equal 10, e\centerY!
assert.are.equal -5, e\left!
assert.are.equal 5, e\right!
assert.are.equal 0, e\top!
assert.are.equal 20, e\bottom!
-- No scene
assert.is.False e\onCamera!
l = 5
assert.is.Nil e\scene!
assert.are.equal 10, e\layer!
assert.are.equal l, e\layer l
assert.are.equal 10, e\layer 10
e\layer l
assert.are.equal LP.BASELAYER!, e\layer false
t = "Entity"
assert.are.equal '', e\type!
assert.are.equal t, e\type t
assert.are.equal t, e\type!
assert.are.equal t, e\type nil
assert.are.equal '', e\type ''
m = Mask!
assert.is.Nil e\mask!
assert.are.equal m, e\mask m
assert.are.equal m, e\mask!
assert.are.equal e, m.parent
assert.are.equal m, e\mask nil
assert.is.Nil e\mask false
assert.is.Nil m.parent
assert.is.Nil e\mask!
g = Graphic!
assert.is.Nil e\graphic!
assert.are.equal g, e\graphic g
assert.are.equal g, e\graphic!
assert.is.Nil e\graphic false
s = Scene!
assert.is.Nil e\scene!
assert.is.Nil e\world!
assert.are.equal s, e\scene s
assert.are.equal s, e\scene!
assert.are.equal s, e\world!
assert.is.Nil e\scene false
assert.are.equal s, e\world s
e\scene false
-- Come back to some that branch if scene is set
e\scene s
assert.are.equal t, e\type t
-- Hits a branch if e\type! is not ""
assert.are.equal t, e\type t
assert.are.equal l, e\layer l
-- Hits a branch if e\layer! is not nil
assert.are.equal l, e\layer l
pending "Entity\\onCamera after scene is set"
it "collidable", ->
e = with Entity 5, 5
.width = 10
.height = 10
\type "Entity"
-- Collider
c = with Entity 5, 5
.width = 10
.height = 10
\type "Entity"
-- No Scene
assert.is.Nil e\collide "Entity", 10, 10
LP.scene = Scene!
LP.scene\add e
LP.scene\add c
LP.scene\updateLists!
-- Not collidable
e.collidable = false
assert.is.Nil e\collide "Entity", 10, 10
-- A collision
e.collidable = true
assert.are.equal c, e\collide "Entity", 10, 10
assert.are.equal e, c\collide "Entity", 10, 10
-- Bounds
assert.are.equal c, e\collide "Entity", 5 - c.width, 5
assert.are.equal c, e\collide "Entity", 5, 5 - c.height
assert.are.equal e, c\collide "Entity", 5, 5
assert.are.equal c, e\collide "Entity", 15, 15
assert.are.equal e, c\collide "Entity", 15, 15
-- Not a collision
assert.is.Nil e\collide "Entity", 4 - c.width, 5
assert.is.Nil e\collide "Entity", 5, 4 - c.height
assert.is.Nil c\collide "Entity", 4 - e.width, 5
assert.is.Nil c\collide "Entity", 5, 4 - e.height
assert.is.Nil e\collide "Entity", 16, 15
assert.is.Nil e\collide "Entity", 15, 16
assert.is.Nil c\collide "Entity", 16, 15
assert.is.Nil c\collide "Entity", 15, 16
-- Mask collision
m = Mask!
e\mask Mask!
c\mask Mask!
assert.are.equal c, e\collide "Entity", 10, 10
assert.are.equal e, c\collide "Entity", 10, 10
-- Not a collision
assert.is.Nil e\collide "Entity", 30, 30
assert.is.Nil e\collide "Entity", 16, 16
assert.are.equal c, e\collide "Entity", 15, 15
it "setHitbox/setHitboxTo", ->
e.width, e.height = 5, 5
c = (w, h, x, y) ->
assert.are.equal w, e.width
assert.are.equal h, e.height
assert.are.equal x, e.originX
assert.are.equal y, e.originY
-- Default
c 5, 5, 0, 0
e\setHitbox 5, 5
c 5, 5, 0, 0
e\setHitbox 10, 10, 2, 2
c 10, 10, 2, 2
r = Rectangle 2, 2, 5, 5
e\setHitboxTo r
c 5, 5, -2, -2
r = { width: 10, height: 10, originX: 0, originY: 0}
e\setHitboxTo r
c 10, 10, 0, 0
it "centerOrigin/setOrigin", ->
e.width, e.height = 10, 10
assert.are.equal 0, e.originX
assert.are.equal 0, e.originY
e\centerOrigin!
assert.are.equal 5, e.originX
assert.are.equal 5, e.originY
e\setOrigin 0, 0
assert.are.equal 0, e.originX
assert.are.equal 0, e.originY
it "distanceFrom", ->
e2 = with Entity 20, 0
.width = 10
.height = 10
e.width, e.height = 10, 10
assert.are.equal 20, e\distanceFrom e2
assert.are.equal 20, e2\distanceFrom e
e2\moveTo 0, 20
assert.are.equal 20, e\distanceFrom e2
assert.are.equal 20, e2\distanceFrom e
e2\moveTo 0, 0
assert.are.equal 0, e\distanceFrom e2
assert.are.equal 0, e2\distanceFrom e
assert.are.equal 0, e\distanceFrom e2, true
assert.are.equal 0, e2\distanceFrom e, true
e2\moveTo 20, 0
assert.are.equal 10, e\distanceFrom e2, true
assert.are.equal 10, e2\distanceFrom e, true
e2\moveTo 0, 20
assert.are.equal 10, e\distanceFrom e2, true
assert.are.equal 10, e2\distanceFrom e, true
it "distanceToPoint", ->
e.width, e.height = 10, 10
assert.are.equal 20, e\distanceToPoint 20, 0
assert.are.equal 20, e\distanceToPoint 0, 20
assert.are.equal 0, e\distanceToPoint 0, 0
assert.are.equal 10, e\distanceToPoint 20, 0, true
assert.are.equal 10, e\distanceToPoint 0, 20, true
assert.are.equal 0, e\distanceToPoint 0, 0, true
assert.are.equal 10, e\distanceToPoint -10, 0
assert.are.equal 10, e\distanceToPoint 0, -10
assert.are.equal 10, e\distanceToPoint -10, 0, true
assert.are.equal 10, e\distanceToPoint 0, -10, true
it "distanceToRect", ->
e.width, e.height = 10, 10
assert.are.equal 10, e\distanceToRect 20, 0, 10, 10
assert.are.equal 10, e\distanceToRect 0, 20, 10, 10
assert.are.equal 0, e\distanceToRect 0, 0, 10, 10
assert.are.equal 10, e\distanceToRect -20, 0, 10, 10
assert.are.equal 10, e\distanceToRect 0, -20, 10, 10
assert.are.equal 10, e\distanceToRect -20, 0, 10, 10
assert.are.equal 10, e\distanceToRect 0, -20, 10, 10
it "toString", ->
assert.are.equal e\toString!, "Entity"
assert.are.equal tostring(e), "Entity"
class Ball extends Entity
b = Ball!
assert.are.equal b\toString!, "Ball"
-- The metatable for __tostring is on the parent, not the child
assert.are_not.equal tostring(b), "Ball"
it "moveBy", ->
e\moveBy 1, 0
assert.are.equal 1, e\x!
assert.are.equal 0, e\y!
e\moveBy 0, 1
assert.are.equal 1, e\x!
assert.are.equal 1, e\y!
e\moveBy 1, 1
assert.are.equal 2, e\x!
assert.are.equal 2, e\y!
e\moveBy -1, -1
assert.are.equal 1, e\x!
assert.are.equal 1, e\y!
e\moveBy 0, 0
assert.are.equal 1, e\x!
assert.are.equal 1, e\y!
pending "Entity\\moveBy solidType and sweep"
it "moveTo", ->
e\moveTo 5, 0
assert.are.equal 5, e\x!
assert.are.equal 0, e\y!
e\moveTo 0, 5
assert.are.equal 0, e\x!
assert.are.equal 5, e\y!
e\moveTo 0, 0
assert.are.equal 0, e\x!
assert.are.equal 0, e\y!
pending "Entity\\moveTo solidType and sweep"
it "moveTowards", ->
e\moveTowards 5, 0, 2
assert.are.equal 2, e\x!
assert.are.equal 0, e\y!
e\moveTowards 5, 0, 2
assert.are.equal 4, e\x!
assert.are.equal 0, e\y!
e\moveTowards 5, 0, 2
assert.are.equal 5, e\x!
assert.are.equal 0, e\y!
e\moveTowards 5, 0, 2
assert.are.equal 5, e\x!
assert.are.equal 0, e\y!
e\moveTowards 5, 5, 2
assert.are.equal 5, e\x!
assert.are.equal 2, e\y!
e\moveTowards 5, 5, 2
assert.are.equal 5, e\x!
assert.are.equal 4, e\y!
e\moveTowards 5, 5, 2
assert.are.equal 5, e\x!
assert.are.equal 5, e\y!
e\moveTowards 7, 7, 1
assert.are.equal 6, e\x!
assert.are.equal 6, e\y!
pending "Entity\\moveTowards solidType and sweep"
it "moveAtAngle", ->
e\moveAtAngle 0, 1
assert.are.equal 1, e\x!
assert.are.equal 0, e\y!
e\moveAtAngle 90, 1
assert.are.equal 1, e\x!
assert.are.equal 1, e\y!
e\moveAtAngle 30, 2
assert.are.equal 3, e\x!
assert.are.equal 2, e\y!
e\moveAtAngle -90, 1
assert.are.equal 3, e\x!
assert.are.equal 1, e\y!
e\moveAtAngle 180, 1
assert.are.equal 2, e\x!
assert.are.equal 1, e\y!
pending "Entity\\moveAtAngle solidType and sweep"
it "clamp hitbox", ->
e = with Entity 0, 0
.width = 25
.height = 25
-- Horizontal clamp
e\clampHorizontal 0, 25
assert.are.equal 0, e\x!
e\clampHorizontal 0, 20
assert.are.equal -5, e\x!
e\clampHorizontal 0, 25
assert.are.equal 0, e\x!
e\clampHorizontal 5, 30
assert.are.equal 5, e\x!
e\clampHorizontal 5, 20
assert.are.equal -5, e\x!
e\x 0
-- Vertical clamp
e\clampVertical 0, 25
assert.are.equal 0, e\y!
e\clampVertical 0, 20
assert.are.equal -5, e\y!
e\clampVertical 0, 25
assert.are.equal 0, e\y!
e\clampVertical 5, 30
assert.are.equal 5, e\y!
e\clampVertical 5, 20
assert.are.equal -5, e\y!
it "centerGraphicInRect", ->
g = Graphic!
e = with Entity!
.width = 10
.height = 10
\graphic g
assert.are_not.equal e\halfWidth!, e\graphic!.x
assert.are_not.equal e\halfHeight!, e\graphic!.y
e\centerGraphicInRect!
assert.are.equal e\halfWidth!, e\graphic!.x
assert.are.equal e\halfHeight!, e\graphic!.y
| 23.504255 | 65 | 0.661899 |
1ba89ea9345443710c04a5cd0ac4138416c1b293 | 1,233 | Dorothy!
-- [signals]
-- "TextChanged",(textField)->
-- [params]
-- x, y, limit, fontSize
Class
__partial: (args)=>
CCTextFieldTTF "","Arial",args.fontSize
__init: (args)=>
{:x,:y,:fontSize,:limit,:placeHolder} = args
@anchor = oVec2 0.5,0
@position = oVec2 x,y
@_placeHolder = placeHolder or ""
@placeHolder = @_placeHolder
@colorPlaceHolder = ccColor3 0x00ffff
@cursor = with oLine {oVec2.zero,oVec2(0,fontSize)},ccColor4 0xff00ffff
.visible = false
.positionX = @width
@addChild @cursor
blink = CCRepeatForever CCSequence {
CCShow!
CCDelay 0.5
CCHide!
CCDelay 0.5
}
@slot "InputAttach", ->
@placeHolder = ""
with @cursor
.visible = true
.positionX = @width
\perform blink
true
@slot "InputDetach", ->
@placeHolder = @_placeHolder
with @cursor
.visible = false
\stopAllActions!
if @text ~= ""
@emit "TextChanged",@
true
@slot "InputInserting",(addText)->
string.len(@text) < limit or addText == "\n"
inputed = ->
with @cursor
.positionX = @width
\perform blink
@texture.antiAlias = false
@slot "InputInserted",inputed
@slot "InputDeleted",inputed
| 21.258621 | 74 | 0.607461 |
fb885eeafc1b9e08ac3008b7a7a421aced868982 | 398 | Dungeon = require "dungeon"
inspect = require "inspect"
dungeon = Dungeon!
love.load = ->
love.update = (dt) ->
love.window.setTitle math.floor collectgarbage 'count'
love.draw = ->
dungeon\drawGrid!
-- dungeon\drawMST!
dungeon\drawTerrain!
love.keypressed = (key) ->
if key == "r"
love.event.quit "restart"
elseif key == "escape"
love.event.quit! | 19.9 | 58 | 0.623116 |
18e42b91f95cbf1bfe03bf266d834a7eee25ea22 | 2,050 |
you_cool = false
if cool
if you_cool
one
else if eatdic
yeah
else
two
three
else
no
if cool then no
if cool then no else yes
if cool then wow cool else
noso cool
if working
if cool then if cool then okay else what else nah
if yeah then no day elseif cool me then okay ya else u way
if yeah then no dad else if cool you then okay bah else p way
if (->)() then what ever
if nil then flip me else
it be,rad
if things great then no way elseif okay sure
what here
if things then no chance
elseif okay
what now
if things
yes man
elseif okay person then hi there else hmm sure
if lets go
print "greetings"
elseif "just us"
print "will smith" else show 5555555
--
if something = 10
print something
else
print "else"
hello = if something = 10
print something
else
print "else"
hello = 5 + if something = 10
print something
---
z = false
if false
one
elseif x = true
two
elseif z = true
three
else
four
out = if false
one
elseif x = true
two
elseif z = true
three
else
four
kzy = ->
if something = true
1
elseif another = false
2
---
unless true
print "cool!"
unless true and false
print "cool!"
unless false then print "cool!"
unless false then print "cool!" else print "no way!"
unless nil
print "hello"
else
print "world"
--
x = unless true
print "cool!"
x = unless true and false
print "cool!"
y = unless false then print "cool!"
y = unless false then print "cool!" else print "no way!"
z = unless nil
print "hello"
else
print "world"
print unless true
print "cool!"
print unless true and false
print "cool!"
print unless false then print "cool!"
print unless false then print "cool!" else print "no way!"
print unless nil
print "hello"
else
print "world"
--
print "hello" unless value
dddd = {1,2,3} unless value
--
do
j = 100
unless j = hi!
error "not j!"
----------------
a = 12
a,c,b = "cool" if something
---
j = if 1
if 2
3
else 6
m = if 1
if 2
3
else 6
nil
| 10.732984 | 61 | 0.648293 |
dba44d046557e75b108f97c75988b583e84da189 | 3,039 |
import with_dev from require "spec.helpers"
describe "moonscript.transform.destructure", ->
local extract_assign_names
with_dev ->
{ :extract_assign_names } = require "moonscript.transform.destructure"
it "extracts names from table destructure", ->
des = {
"table"
{
{{"key_literal", "hi"}, {"ref", "hi"}}
{{"key_literal", "world"}, {"ref", "world"}}
}
}
assert.same {
{
{"ref", "hi"} -- target
{
{"dot", "hi"}
} -- chain suffix
}
{
{"ref", "world"}
{
{"dot", "world"}
}
}
}, extract_assign_names des
it "extracts names from array destructure", ->
des = {
"table"
{
{{"ref", "hi"}}
}
}
assert.same {
{
{"ref", "hi"}
{
{"index", {"number", 1}}
}
}
}, extract_assign_names des
describe "moonscript.transform.statements", ->
local last_stm, transform_last_stm, Run
with_dev ->
{ :last_stm, :transform_last_stm, :Run } = require "moonscript.transform.statements"
describe "last_stm", ->
it "gets last statement from empty list", ->
assert.same nil, (last_stm {})
it "gets last statement", ->
stms = {
{"ref", "butt_world"}
{"ref", "hello_world"}
}
stm, idx, t = last_stm stms
assert stms[2] == stm
assert.same 2, idx
assert stms == t
it "gets last statement ignoring run", ->
stms = {
{"ref", "butt_world"}
{"ref", "hello_world"}
Run => print "hi"
}
stm, idx, t = last_stm stms
assert stms[2] == stm
assert.same 2, idx
assert stms == t
it "gets last from within group", ->
stms = {
{"ref", "butt_world"}
{"group", {
{"ref", "hello_world"}
{"ref", "cool_world"}
}}
}
last = stms[2][2][2]
stm, idx, t = last_stm stms
assert stm == last, "should get last"
assert.same 2, idx
assert t == stms[2][2], "should get correct table"
describe "transform_last_stm", ->
it "transforms empty stms", ->
before = {}
after = transform_last_stm before, (n) -> {"wrapped", n}
assert.same before, after
assert before != after
it "transforms stms", ->
before = {
{"ref", "butt_world"}
{"ref", "hello_world"}
}
transformer = (n) -> n
after = transform_last_stm before, transformer
assert.same {
{"ref", "butt_world"}
{"transform", {"ref", "hello_world"}, transformer}
}, after
it "transforms empty stms ignoring runs", ->
before = {
{"ref", "butt_world"}
{"ref", "hello_world"}
Run => print "hi"
}
transformer = (n) -> n
after = transform_last_stm before, transformer
assert.same {
{"ref", "butt_world"}
{"transform", {"ref", "hello_world"}, transformer}
before[3]
}, after
| 21.553191 | 88 | 0.507404 |
ca560456dd994c47549e6fd823377ade6dc7380b | 289 | howl.mode.register
name: 'myrddin'
extensions: {'myr'}
aliases: {'myr', 'mc'}
create: -> bundle_load 'mode'
parent: 'curly_mode'
unload = -> howl.mode.unregister 'myrddin'
{
info:
author: 'Ryan Gonzalez'
description: 'A Myrddin bundle'
license: 'MIT'
:unload
}
| 17 | 42 | 0.633218 |
71c48fe5f2211ddecfcfcf322f73430d2d220df0 | 459 | describe 'Globals', ->
it 'callable <foo> returns true if foo can be invoked as a function', ->
assert.is_true callable -> true
t = setmetatable {}, __call: -> true
assert.is_true callable t
it 'typeof(v) is like type(), but handles regexes and moonscript classes', ->
assert.equal 'regex', typeof r'foo'
class Bar
assert.equal 'Bar', typeof Bar!
it 'r is a short alias for regex', ->
assert.equal r, require 'howl.regex'
| 30.6 | 79 | 0.657952 |
24f82dd02c9f281ae35c0276f45e4a56be7a14d5 | 1,363 | import sin, floor from math
title = {}
title.y = 16
title.text = "Unknown\n Depths"
local color
move = ->
flux.to(title, 0.48, {y: 32})\ease("cubicin")\oncomplete(->
flux.to(title, 0.48, {y: 16})\ease("cubicout")\oncomplete(move)
)
move!
text = (s, font, y) ->
x = gameWidth / 2 - font\getWidth(s) / 2
love.graphics.setFont font
love.graphics.print(s, x, y)
title.enter = (previous, playMusic = true) =>
if playMusic
sounds.titleMusic\play!
color = {0,0,0,0}
title.update = (dt) =>
flux.update dt
title.draw = () =>
-- draw the level
push\start!
text @text, fontFantasy, floor(@y)
y = 74
text "ENTER TO START", fontRetro, screenHeight - y
text "H FOR HELP", fontRetro, screenHeight - y + 12
text "F FOR FULLSCREEN", fontRetro, screenHeight - y + 24
text "ESC TO EXIT", fontRetro, screenHeight - y + 36
text "© 2020", fontRetro, screenHeight - 16
love.graphics.setColor color
love.graphics.rectangle "fill", 0, 0, gameWidth, screenHeight
push\finish!
title.keypressed = (key) =>
switch key
when "return"
flux.to(color, 0.5, {0,0,0,1})\oncomplete(->
color = {0,0,0,0}
manager\push states.gameplay
)
when "h"
manager\push states.help
when "f"
push\switchFullscreen(windowedWidth, windowedHeight)
when "escape" love.event.quit!
return title | 23.5 | 67 | 0.635363 |
66fd1506bbdc9cc4e7c1eb8d9ec2cefec1d66ac9 | 561 | c.position =
x: 0
y: 0
c.size =
w: 0
h: 0
c.color = { 0, 0, 0 }
c.direction = {1}
c.head = {}
c.shade = { 0, 0, 0 }
c.physics =
dx: 0
dy: 0
frc_x: 0.5
frc_y: 0.3
dir: 0
speed: 8
grounded: false
gravity:
power: 10
mod: 1
wall:
dir: 0
stick: 0
jump:
desire: 0
force: 5
doubled: false
max_speed: 20
dash:
power: 5
timer: 0
cooldown: 3
c.player = {}
c.rotation = {0}
c.slime =
dir: {}
visible: false
color: { 1, 1, 1 }
c.hurts = {}
c.sprite =
img: nil
c.speed = {0}
c.door = {}
| 10.788462 | 21 | 0.500891 |
1dcf119679bf4bf0c1fe32c9322cc4a073d3ad3e | 913 | import Widget from require "lapis.html"
i18n = require "i18n"
class MTAResourceManageDetails extends Widget
@include "widgets.utils"
name: "Details"
content: =>
div class: "card", ->
div class: "card-header", i18n "resources.manage.details.change_description"
div class: "card-block", -> form method: "POST", action: @url_for("resources.manage.update_description", resource_slug: @resource.slug), ->
fieldset class: "form-group", ->
label for: "resDescription", ->
text "#{i18n 'resources.manage.details.description'} "
small class: "text-muted", i18n "resources.manage.details.description_info"
textarea class: "form-control", id: "resDescription", name: "resDescription", rows: 3, required: true, @resource.description
@write_csrf_input!
button class: "btn btn-secondary", type: "submit", " #{i18n 'resources.manage.details.description_button'}" | 48.052632 | 143 | 0.698795 |
2276a1dc27ebe4821eb76b8798ffddec96a35e2d | 989 | -- Blob example: save and load data to/from file
-- run with luajit <path to moon> file.moon
package.moonpath = "#{package.moonpath};../?.moon"
BlobReader, BlobWriter = require('BlobReader'), require('BlobWriter')
projectInfo =
name: 'moonblob',
author: '[email protected]',
url: 'https://github.com/megagrump/moonblob',
license: 'MIT',
magicnumber: 0xbaadc0de,
tests: { 'test/test.moon' }
-- serialize the table
tableBlob = BlobWriter!
tableBlob\write(projectInfo)
-- save the table
file = assert(io.open('table.dat', 'wb'))
file\write(tableBlob\tostring!)
file\close()
-- load the table
file = assert(io.open('table.dat', 'rb'))
filedata = file\read('*all')
file\close()
--deserialize table
blob = BlobReader(filedata)
projectTable = blob\read()
-- display loaded table
show = (what) ->
for k, v in pairs(what)
if type(v) == 'table'
print(k .. ":")
show(v)
else
print(string.format("%s = %s", k, v))
show(projectTable)
| 24.725 | 69 | 0.659252 |
7326dd2cae5bcd1ba7831bb79fc2181a36753dba | 369 | <template>
<h1>{{content}}</h1>
</template>
<style scoped>
h1 {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
font-weight: 200;
font-size: 100px;
color: #414141;
}
</style>
<script>
exports = {
props: ["content"]
}
</script>
| 21.705882 | 163 | 0.609756 |
66a6702a61d4210f7e89aab40518b7104cef36db | 1,395 | state = require 'lqc.fsm.state'
make_state = (name, precondition, next_state, postcondition) ->
->
state name,
precondition: precondition
next_state: next_state,
postcondition: postcondition
describe 'state helper object (moonscript integration', ->
it 'is necessary to provide a name, next_state, pre- and postcondition', ->
name = 'state_name'
next_state = ->
precondition = ->
postcondition = ->
assert.equal(false, pcall(make_state(nil, nil, nil, nil)))
assert.equal(false, pcall(make_state(name, nil, nil, nil)))
assert.equal(false, pcall(make_state(name, precondition, nil, nil)))
assert.equal(false, pcall(make_state(name, precondition, next_state, nil)))
assert.equal(true, pcall(make_state(name, precondition, next_state, postcondition)))
assert.equal(false, pcall(-> state name nil))
it 'returns a table containing precondition, next_state and postcondition', ->
state_name = 'name of the state'
precondition = ->
next_state = ->
postcondition = ->
a_state = state 'name of the state'
precondition: precondition
next_state: next_state
postcondition: postcondition
assert.equal(state_name, a_state.name)
assert.equal(precondition, a_state.precondition)
assert.equal(next_state, a_state.next_state)
assert.equal(postcondition, a_state.postcondition)
| 32.44186 | 88 | 0.701075 |
f783f69db1b4d7bbded1b1e832f4b462938a05de | 1,331 | -------------------------------------------------------------------------------
-- Provides high-resolution timing functionality.
-------------------------------------------------------------------------------
-- @module yae.timer
import java from yae
TimeUtils = java.require "com.badlogic.gdx.utils.TimeUtils"
Thread = java.require "java.lang.Thread"
Gdx = java.require "com.badlogic.gdx.Gdx"
---
-- Returns the time between the last two frames.
-- @treturn number The time passed (in seconds).
-- @usage
-- dt = yae.timer.getDelta!
getDelta = ->
Gdx.graphics\getDeltaTime! / 1000
---
-- Returns the current frames per second.
-- @treturn number The current FPS.
-- @usage
-- fps = yae.timer.getFPS!
getFPS = ->
Gdx.graphics\getFramesPerSecond!
---
-- Returns the value of a timer with an unspecified starting time. This
-- function should only be used to calculate differences between points
-- in time, as the starting time of the timer is unknown.
-- @treturn number The time in seconds.
-- @usage
-- time = yae.timer.getTime!
getTime = ->
TimeUtils\millis! / 1000
---
-- Pauses the current thread for the specified amount of time.
-- @tparam number seconds Seconds to sleep for.
-- @usage
-- yae.timer.sleep seconds
sleep = (seconds) ->
Thread\sleep seconds * 1000
{
:getDelta
:getFPS
:getTime
:sleep
}
| 26.098039 | 79 | 0.625845 |
6ca95152f52ea0ffb5f2fa1dab364040661f5faa | 951 | Anim8 = require "lib.anim8"
{graphics: lg} = love
Sprite = setmetatable {}, __index: (sprite) =>
img = lg.newImage "assets/graphics/#{sprite}.png"
@[sprite] = img
img
Animation = {}
Grid = {}
for name, anim in pairs {
soul: {w: 10, h: 13, "1-2", 1, 1, 1, 3, 1},
swipe: {w: 6, h: 19, s: 0.02, "1-13", loop: "pauseAtEnd", 1},
player_walk: {w: 13, h: 16, sprite: "player", s: 0.1, "4-7", 1},
player_idle: {w: 13, h: 16, sprite: "player", "3-1", 1, "1-3", 1, 3, 1, 3, 1},
person: {w: 10, h: 14, sprite: "enemy", s: 0.2, "1-2", 1, 1, 1, 3, 1}
}
anim.sprite or= name
Grid[anim.sprite] = Anim8.newGrid anim.w, anim.h, Sprite[anim.sprite]\getDimensions! unless Grid[anim.sprite]
Animation[name] = Anim8.newAnimation Grid[anim.sprite](unpack anim), anim.s or 0.3, anim.loop
{
:Sprite,
Animation: setmetatable {}, __index: (index) =>
rawget(Animation, index)\clone! -- clone animations
}
| 32.793103 | 111 | 0.57939 |
c76d9fb113daa267a9756eb13ccbfc2c66aee8ae | 832 | System = require "lib.concord.system"
Position = require "src.components.Position"
Mover = require "src.components.Mover"
Input = require "src.components.Input"
filter = {
Mover,
Position,
Input
}
MovementInput = System filter
MovementInput.update = (deltaTime) =>
for _, entity in ipairs self.pool.objects
mover = entity\get Mover
position = entity\get Position
input = entity\get Input
-- Vertical
if love.keyboard.isDown input.buttons.up
mover.velocity.y = -mover.speed
elseif love.keyboard.isDown input.buttons.down
mover.velocity.y = mover.speed
else
mover.velocity.y = 0
-- Horizontal
if love.keyboard.isDown input.buttons.left
mover.velocity.x = -mover.speed
elseif love.keyboard.isDown input.buttons.right
mover.velocity.x = mover.speed
else
mover.velocity.x = 0
MovementInput | 24.470588 | 49 | 0.737981 |
b2ba5ac1e75160e62933f8c9d39e474114ece751 | 19,175 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
Gtk = require 'ljglibs.gtk'
import bindings, config, dispatch from howl
import PropertyObject from howl.util.moon
import ActionBuffer, BufferPopup, markup, style from howl.ui
{:TextWidget, :NotificationWidget, :IndicatorBar, :StyledText, :ContentBox} = howl.ui
append = table.insert
-- used to generate a unique id for every new activity
id_counter = 0
class CommandLine extends PropertyObject
new: (@window) =>
super!
@bin = Gtk.Box Gtk.ORIENTATION_HORIZONTAL
@box = nil
@command_widget = nil
@notification_widget = nil
@header = nil
@indic_title = nil
@indic_info = nil
@showing = false
@spillover = nil
@running = {}
@aborted = {}
@next_run_queue = {}
@_command_history = {}
@sync_history!
@property current: get: => @running[#@running]
@property stack_depth: get: => #@running
_init_activity_from_factory: (activity_frame) =>
activity = activity_frame.activity_spec.factory!
if not activity
error "activity '#{activity_frame.name}' factory returned nil"
activity_frame.activity = activity
parked_handle = dispatch.park 'activity'
activity_frame.parked_handle = parked_handle
finish = (...) ->
results = table.pack ...
activity_frame.results = results
@_finish(activity_frame.activity_id, results)
dispatch.launch -> dispatch.resume parked_handle
true -- finish() is often the last function in a key handler
activity_frame.runner = ->
table.pack activity\run(finish, unpack activity_frame.args)
-- check that run didn't call finish
if @current and @current.activity_id == activity_frame.activity_id
@current.state = 'running'
@show!
@close_popup!
bindings.cancel_capture!
if @spillover and not @spillover.is_empty
-- allow editor to resize for correct focusing behavior
howl.timer.asap ->
@write @spillover if not @spillover.is_empty
@spillover = nil
dispatch.wait parked_handle
_init_activity_from_handler: (activity_frame) =>
if not callable activity_frame.activity_spec.handler
error "activity '#{activity_frame.name}' handler is not callable"
activity = { handler: activity_frame.activity_spec.handler }
activity_frame.activity = activity
activity_frame.runner = ->
@current.state = 'running'
results = table.pack activity.handler(unpack activity_frame.args)
if @current and @current.activity_id == activity_frame.activity_id
activity_frame.results = results
@_finish(activity_frame.activity_id, results)
run: (activity_spec, ...) =>
if not activity_spec.name or not (activity_spec.handler or activity_spec.factory)
error 'activity_spec requires "name" and one of "handler" or "factory" fields'
id_counter += 1
activity_id = id_counter
activity_frame = {
name: activity_spec.name
:activity_id
:activity_spec
args: table.pack ...
state: 'starting'
results: {}
}
if activity_spec.factory
@_init_activity_from_factory activity_frame
else
@_init_activity_from_handler activity_frame
append @running, activity_frame
@_initialize! if not @box
with @current
.command_line_left_stop = @command_widget.text.ulen + 1
.command_line_widgets = { }
.command_line_keymaps = { }
.command_line_help = { keys: { } }
.command_line_prompt_len = 0
if @stack_depth == 1
@current.evade_history = activity_spec.evade_history
@history_recorded = false
else
previous = @running[@stack_depth - 1]
@current.evade_history = previous.evade_history or activity_spec.evade_history
bindings.capture -> false
ok, err = pcall activity_frame.runner
bindings.cancel_capture!
unless ok
if @current and activity_id == @current.activity_id
@_finish(activity_id)
log.error err
return
unpack activity_frame.results
run_after_finish: (f) =>
if not (@stack_depth > 0)
error 'Cannot run_after_finish - no running activity'
append @next_run_queue, f
switch_to: (new_command) =>
captured_text = @text
howl.timer.asap ->
@abort_all!
howl.command.run new_command .. ' ' .. captured_text
_process_run_after_finish: =>
while true
f = table.remove @next_run_queue, 1
break unless f
f!
_is_active: (activity_id) =>
for activity in *@running
if activity.activity_id == activity_id
return true
return false
_finish: (activity_id, results={}) =>
if @aborted[activity_id]
@aborted[activity_id] = nil
return
if not @current
error 'Cannot finish - no running activities'
if activity_id != @current.activity_id
if @_is_active activity_id
while @current.activity_id != activity_id
@_abort_current!
else
error "Cannot finish - invalid activity_id #{activity_id}"
@current.state = 'stopping'
if #results > 0 and not @current.evade_history and not @history_recorded
@record_history!
@clear!
@prompt = nil
for name, _ in pairs @_widgets
@remove_widget name
if @current.saved_command_line
@command_widget\insert @current.saved_command_line, 1
@current.saved_command_line = nil
if @current.saved_widgets
for widget in *@_all_widgets
if @current.saved_widgets[widget]
widget\show!
@running[#@running] = nil
if @stack_depth > 0
@title = @title
@close_popup!
else
@hide!
@pop_spillover!
@_process_run_after_finish!
_abort_current: =>
activity_id = @current.activity_id
handle = @current.parked_handle
@_finish activity_id
@aborted[activity_id] = true
if handle
dispatch.launch -> dispatch.resume handle
if @current and activity_id == @current.activity_id
-- hard clear, polite attempt didn't work
@running[#@running] = nil
abort_all: =>
while @current
@_abort_current!
_cursor_to_end: =>
@command_widget.cursor\eof!
disable_auto_record_history: =>
@current.evade_history = true
record_history: =>
@history_recorded = true
command_line = @_capture_command_line!
for frame in *@running
if frame.saved_command_line
command_line = frame.saved_command_line .. command_line
current_history = @get_history @running[1].name
last_cmd = current_history[1]
unless last_cmd == command_line or command_line\find '\n' or command_line\find '\r'
name = @running[1].name
append @_command_history, 1, {:name, cmd: command_line, timestamp: howl.sys.time!}
@sync_history!
sync_history: =>
return unless howl.app.settings
saved_history = howl.app.settings\load_system 'command_line_history'
saved_history or= {}
history = {}
for item in *@_command_history
history[item.timestamp] = item
for item in *saved_history
continue if history[item.timestamp]
item.cmd = StyledText item.cmd.text, item.cmd.styles
history[item.timestamp] = item
merged_history = [item for _, item in pairs history]
table.sort merged_history, (a, b) -> a.timestamp > b.timestamp
deduped_history = {}
commands = {}
limit = config.command_history_limit
count = 0
for item in *merged_history
continue if commands[item.cmd.text]
append deduped_history, item
commands[item.cmd.text] = true
count += 1
break if count >= limit
howl.app.settings\save_system 'command_line_history', deduped_history
@_command_history = deduped_history
_capture_command_line: (end_pos) =>
buf = @command_widget.buffer
chunk = buf\chunk 1, (end_pos or #buf)
return StyledText chunk.text, chunk.styles
get_history: (activity_name) =>
return [item.cmd for item in *@_command_history when activity_name == item.name]
to_gobject: => @bin
_initialize: =>
@box = Gtk.Box Gtk.ORIENTATION_VERTICAL
@command_widget = TextWidget
line_wrap: 'char'
on_keypress: (event) ->
result = true
if not @handle_keypress(event)
result = false
@post_keypress!
return result
on_changed: ->
@on_update!
on_focus_lost: ->
@close_popup!
if @showing and howl.activities.nr_visible == 0
@command_widget\focus!
@command_widget.visible_rows = 1
@box\pack_end @command_widget\to_gobject!, false, 0, 0
@notification_widget = NotificationWidget!
@box\pack_end @notification_widget\to_gobject!, false, 0, 0
@header = IndicatorBar 'header'
@indic_title = @header\add 'left', 'title'
@indic_info = @header\add 'right', 'info'
@box.margin_left = 2
@box.margin_top = 2
c_box = ContentBox 'command_line', @box, {
header: @header\to_gobject!
}
@bin\add c_box\to_gobject!
_update_info: =>
@_info_icon or= howl.ui.icon.get('font-awesome-info')
@_keyboard_icon or= howl.ui.icon.get('font-awesome-keyboard-o')
h_texts, h_keys = @_get_help!
text = ''
if #h_texts > 0
if #h_texts > 1 or h_texts[1].text\contains('\n')
text = @_info_icon.text
if #h_keys > 0
text ..= " #{@_keyboard_icon.text}"
unless text.is_empty
text ..= ': f1'
@indic_info.label = text
@property width_cols:
get: => @command_widget.width_cols
@property _activity:
get: => @current and @current.activity
@property _widgets:
get: => @current and @current.command_line_widgets
@property _help:
get: => @current and @current.command_line_help
@property _keymaps:
get: => @current and @current.command_line_keymaps
@property _all_widgets:
get: =>
widgets = {}
for frame in *@running
for _, widget in pairs frame.command_line_widgets
append widgets, widget
return widgets
@property _left_stop:
get: => @current and @current.command_line_left_stop
@property _prompt_end:
get: => @current and @_left_stop + @current.command_line_prompt_len
@property _updating:
get: => @current and @current.command_line_updating
set: (value) =>
return unless @current
@current.command_line_updating = value
@property title:
get: => @current and @current.command_line_title
set: (text) =>
if not @current
error 'Cannot set title - no running activity', 2
@current.command_line_title = text
if text == nil or text.is_empty
@indic_title.label = ''
@header\to_gobject!\hide!
else
@header\to_gobject!\show!
@indic_title.label = tostring text
@_update_info!
@property prompt:
get: => @current and @command_widget.text\usub @_left_stop, @_prompt_end - 1
set: (prompt='') =>
if not @current
error 'Cannot set prompt - no running activity', 2
if @_left_stop <= @_prompt_end
@command_widget\delete @_left_stop, @_prompt_end - 1
@current.command_line_prompt = prompt
@current.command_line_prompt_len = prompt.ulen
if prompt
@command_widget\insert prompt, @_left_stop, 'prompt'
@\_cursor_to_end!
@property text:
get: => @current and @command_widget.text\usub @_prompt_end
set: (text) =>
if not @current
error 'Cannot set text - no running activity', 2
@clear!
@write text
show_help: =>
popup = BufferPopup @_build_help_buffer!
@show_popup popup
close_popup: =>
if @popup
@popup\destroy!
@popup = nil
return true
show_popup: (popup, options = {}) =>
@close_popup!
popup\show howl.app.window\to_gobject!, x:1, y:1
popup\center!
@popup = popup
notify: (text, notification_style = 'info') =>
if #text == 0
@clear_notification!
return
if @notification_widget
@notification_widget\notify notification_style, text
@notification_widget\show!
else
io.stderr\write text
clear_notification: =>
@notification_widget\hide! if @notification_widget
clear: =>
@command_widget\delete @_prompt_end, @command_widget.text.ulen
@\_cursor_to_end!
clear_all: =>
@current.saved_command_line = @_capture_command_line @_left_stop - 1
@command_widget\delete 1, @_left_stop - 1
@current.command_line_left_stop = 1
@current.saved_widgets = {}
for widget in *@_all_widgets
if widget.showing
widget\hide!
@current.saved_widgets[widget] = true
write: (text) =>
@command_widget\append text
@\_cursor_to_end!
@\on_update!
write_spillover: (text) =>
-- spillover is saved text written to whichever activity is invoked next
if @spillover
@spillover = @spillover .. text
else
@spillover = text
pop_spillover: =>
spillover = @spillover
@spillover = nil
return spillover or ''
post_keypress: =>
@enforce_left_pos!
on_update: =>
-- only call on_update() after run() ends and before finish() begins
return if not @current or @current.state != 'running'
if @_activity and @_activity.on_update and not @_updating
-- avoid recursive calls
@_updating = true
ok, err = pcall ->
@_activity\on_update @text
@_updating = false
if not ok
error err
enforce_left_pos: =>
-- don't allow cursor to go left into prompt
return if not @current
left_pos = @_prompt_end or 1
if @command_widget.cursor.pos < left_pos
@command_widget.cursor.pos = left_pos
handle_keypress: (event) =>
-- keymaps checked in order:
-- @preemptive_keymap - keys that cannot be remapped by activities
-- widget.keymap for widget in @_widgets
-- @_activity.keymap
-- command_line_keymaps for every running activity, newest to oldest
-- @default_keymap
@clear_notification!
@window.status\clear!
@close_popup! unless event.key_name == 'escape'
return true if bindings.dispatch event, 'commandline', { @preemptive_keymap}, self
if @_widgets
for _, widget in pairs @_widgets
if widget.keymap
return true if bindings.dispatch event, 'commandline', { widget.keymap }, widget
activity = @_activity
if activity and activity.keymap
return true if bindings.dispatch event, 'commandline', { activity.keymap }, activity
for i = @stack_depth, 1, -1
frame = @running[i]
for keymap in *frame.command_line_keymaps
return true if bindings.dispatch event, 'commandline', { keymap }, frame.activity
return true if bindings.dispatch event, 'commandline', { @default_keymap }, self
return false
preemptive_keymap:
ctrl_shift_backspace: => @abort_all!
escape: =>
return false unless @close_popup!
default_keymap:
binding_for:
["cursor-home"]: => @command_widget.cursor.pos = @_prompt_end
["cursor-line-end"]: => @command_widget.cursor.pos = @_prompt_end + @text.ulen
["cursor-left"]: => @command_widget.cursor\left!
["cursor-right"]: => @command_widget.cursor\right!
["editor-select-all"]: => @command_widget.selection\select @_prompt_end, @command_widget.text.ulen
["editor-delete-back"]: =>
if @command_widget.cursor.pos <= @_prompt_end
-- backspace attempted into prompt
if @_activity and @_activity.handle_back
@_activity\handle_back!
return true
else
return true
range_start = @command_widget.selection\range!
return if range_start and range_start < @_prompt_end
@command_widget\delete_back!
@on_update!
["editor-paste"]: =>
import clipboard from howl
if clipboard.current
@write clipboard.current.text
f1: => @show_help!
add_widget: (name, widget, pos='bottom') =>
error('No widget provided', 2) if not widget
@remove_widget name
local pack
if pos == 'bottom'
pack = @box\pack_end
elseif pos == 'top'
pack = @box\pack_start
else
error "Invalid pos #{pos}"
pack widget\to_gobject!, false, 0, 0
@_widgets[name] = widget
widget\show!
remove_widget: (name) =>
widget = @_widgets[name]
return unless widget
widget\to_gobject!\destroy!
@_widgets[name] = nil
get_widget: (name) => @_widgets[name]
add_keymap: (keymap) => append @current.command_line_keymaps, 1, keymap
add_help: (help_defs) =>
if #help_defs == 0
help_defs = {help_defs}
for def in *help_defs
if def.key or def.key_for
@_help.keys[def.key or def.key_for] = def
elseif def.text or def.heading
@_help.text = def
show: =>
return if @showing
@last_focused = @window.focus if not @last_focused
@window\remember_focus!
@_initialize! if not @box
@window.status\hide!
@bin\show_all!
@notification_widget\hide!
with @command_widget
\show!
\focus!
@title = @current and @current.command_line_title
@showing = true
hide: =>
if @showing
@showing = false
@bin\hide!
@window.status\show!
@last_focused\grab_focus! if @last_focused
@last_focused = nil
refresh: =>
for frame in *@running
frame.activity\refresh! if frame.activity.refresh
_get_help: =>
help_keys = {}
help_texts = {}
for frame in *@running
for _, def in pairs(frame.command_line_help.keys)
append(help_keys, def)
if frame.command_line_help.text
append help_texts, frame.command_line_help.text
if @_activity.help
help = @_activity.help
help = help(@_activity) if type(help) == 'function'
for def in *help
if def.key or def.key_for
append(help_keys, def)
elseif def.text
append help_texts, def
help_texts, help_keys
_build_help_buffer: =>
buffer = ActionBuffer!
buffer.text = ''
help_texts, help_keys = @_get_help!
for def in *help_texts
if def.heading
buffer\append markup.howl "<h1>#{def.heading}</>\n\n"
if def.text
buffer\append def.text
buffer\append '\n'
buffer\append '\n' if #help_keys > 0
if #help_keys > 0
buffer\append markup.howl "<h1>Keys</>\n"
keys = {}
for def in *help_keys
key = def.key
if def.key_for
resolved = howl.bindings.keystrokes_for def.key_for, 'editor'
key = resolved[1]
if key
append keys, {markup.howl("<keystroke>#{key}</>"), def.action}
buffer\append howl.ui.StyledText.for_table keys
buffer
style.define_default 'prompt', 'keyword'
style.define_default 'keystroke', 'special'
config.define
name: 'command_history_limit'
description: 'The number of commands persisted in command line history'
scope: 'global'
type_of: 'number'
default: 100
return CommandLine
| 27.51076 | 104 | 0.652621 |
a704e5625ee75dc59246fc425c3c51f233caf97d | 1,371 |
for x=1,10
print "yeah"
for x=1,#something
print "yeah"
for y=100,60,-3
print "count down", y
for a=1,10 do print "okay"
for a=1,10
for b = 2,43
print a,b
for i in iter
for j in yeah
x = 343 + i + j
print i, j
for x in *something
print x
for k,v in pairs hello do print k,v
for x in y, z
print x
for x in y, z, k
print x
x = ->
for x in y
y
hello = {1,2,3,4,5}
x = for y in *hello
if y % 2 == 0
y
x = ->
for x in *hello
y
t = for i=10,20 do i * 2
hmm = 0
y = for j = 3,30, 8
hmm += 1
j * hmm
->
for k=10,40
"okay"
->
return for k=10,40
"okay"
while true do print "name"
while 5 + 5
print "okay world"
working man
while also do
i work too
"okay"
i = 0
x = while i < 10
i += 1
-- values that can'e be coerced
x = for thing in *3
y = "hello"
x = for x=1,2
y = "hello"
-- continue
while true
continue if false
print "yes"
break if true
print "no"
for x=1,10
continue if x > 3 and x < 7
print x
list = for x=1,10
continue if x > 3 and x < 7
x
for a in *{1,2,3,4,5,6}
continue if a == 1
continue if a == 3
print a
for x=1,10
continue if x % 2 == 0
for y = 2,12
continue if y % 3 == 0
while true
continue if false
break
while true
continue if false
return 22
--
do
xxx = {1,2,3,4}
for thing in *xxx
print thing
| 10.231343 | 35 | 0.553611 |
d1b66deb1120061c27f6ca6ec8fc3fe839fb9dc8 | 15,276 |
lapis = require "lapis"
import mock_action, mock_request, assert_request from require "lapis.spec.request"
mock_app = (...) ->
mock_action lapis.Application, ...
describe "find_action", ->
action1 = ->
action2 = ->
it "finds action", ->
class SomeApp extends lapis.Application
[hello: "/cool-dad"]: action1
[world: "/another-dad"]: action2
assert.same action1, (SomeApp\find_action "hello")
assert.same action2, (SomeApp\find_action "world")
assert.same nil, (SomeApp\find_action "nothing")
it "finds require'd action", ->
package.loaded["actions.hello"] = action1
package.loaded["actions.admin.cool"] = action2
class SomeApp extends lapis.Application
[hello: "/cool-dad"]: true
[world: "/uncool-dad"]: "admin.cool"
assert.same action1, (SomeApp\find_action "hello")
assert.same action2, (SomeApp\find_action "world")
describe "dispatch", ->
describe "lazy loaded actions", ->
import mock_request from require "lapis.spec.request"
class BaseApp extends lapis.Application
[test_route: "/hello/:var"]: true
[another: "/good-stuff"]: "hello_world"
[regular: "/hmm"]: ->
"/yo": true
before_each ->
package.loaded["actions.test_route"] = spy.new ->
package.loaded["actions.hello_world"] = spy.new ->
it "dispatches action by route name", ->
mock_request BaseApp, "/hello/5"
assert.spy(package.loaded["actions.test_route"]).was.called!
assert.spy(package.loaded["actions.hello_world"]).was_not.called!
it "dispatches action by string name", ->
mock_request BaseApp, "/good-stuff"
assert.spy(package.loaded["actions.test_route"]).was_not.called!
assert.spy(package.loaded["actions.hello_world"]).was.called!
it "doesn't call other actions for unrelated route", ->
mock_request BaseApp, "/hmm"
assert.spy(package.loaded["actions.test_route"]).was_not.called!
assert.spy(package.loaded["actions.hello_world"]).was_not.called!
mock_request BaseApp, "/hmm"
it "failes to load `true` action with no route name", ->
assert.has_error ->
mock_request BaseApp, "/yo"
describe "inheritance", ->
local result
before_each ->
result = nil
class BaseApp extends lapis.Application
"/yeah": => result = "base yeah"
[test_route: "/hello/:var"]: => result = "base test"
class ChildApp extends BaseApp
"/yeah": => result = "child yeah"
"/thing": => result = "child thing"
it "should find route in base app", ->
status, buffer, headers = mock_request ChildApp, "/hello/world", {}
assert.same 200, status
assert.same "base test", result
it "should generate url from route in base", ->
url = mock_action ChildApp, =>
@url_for "test_route", var: "foobar"
assert.same url, "/hello/foobar"
it "should override route in base class", ->
status, buffer, headers = mock_request ChildApp, "/yeah", {}
assert.same 200, status
assert.same "child yeah", result
describe "@include", ->
local result
before_each ->
result = nil
it "should include another app", ->
class SubApp extends lapis.Application
"/hello": => result = "hello"
class App extends lapis.Application
@include SubApp
"/world": => result = "world"
status, buffer, headers = mock_request App, "/hello", {}
assert.same 200, status
assert.same "hello", result
status, buffer, headers = mock_request App, "/world", {}
assert.same 200, status
assert.same "world", result
it "should merge url table", ->
class SubApp extends lapis.Application
[hello: "/hello"]: => result = "hello"
class App extends lapis.Application
@include SubApp
[world: "/world"]: => result = "world"
app = App!
req = App.Request App!, {}, {}
assert.same "/hello", req\url_for "hello"
assert.same "/world", req\url_for "world"
it "should set sub app prefix path", ->
class SubApp extends lapis.Application
[hello: "/hello"]: => result = "hello"
class App extends lapis.Application
@include SubApp, path: "/sub"
[world: "/world"]: => result = "world"
app = App!
req = App.Request App!, {}, {}
assert.same "/sub/hello", req\url_for "hello"
assert.same "/world", req\url_for "world"
it "should set sub app url name prefix", ->
class SubApp extends lapis.Application
[hello: "/hello"]: => result = "hello"
class App extends lapis.Application
@include SubApp, name: "sub_"
[world: "/world"]: => result = "world"
app = App!
req = App.Request App!, {}, {}
assert.has_error -> req\url_for "hello"
assert.same "/hello", req\url_for "sub_hello"
assert.same "/world", req\url_for "world"
it "should set include options from target app", ->
class SubApp extends lapis.Application
@path: "/sub"
@name: "sub_"
[hello: "/hello"]: => result = "hello"
class App extends lapis.Application
@include SubApp
[world: "/world"]: => result = "world"
app = App!
req = App.Request App!, {}, {}
assert.same "/sub/hello", req\url_for "sub_hello"
assert.same "/world", req\url_for "world"
it "included application supports require'd action", ->
s = {} -- use table address for unique identifier for action result
package.loaded["actions.hello"] = -> "action1 #{s}"
package.loaded["actions.admin.cool"] = -> "action2 #{s}"
class SubApp extends lapis.Application
[hello: "/cool-dad"]: true
[world: "/uncool-dad"]: "admin.cool"
class SomeApp extends lapis.Application
layout: false
@include SubApp
"/some-dad": => "hi"
status, buffer, headers = mock_request SomeApp, "/cool-dad", {}
assert.same {
status: 200
buffer: "action1 #{tostring s}"
}, { :status, :buffer }
status, buffer, headers = mock_request SomeApp, "/uncool-dad", {}
assert.same {
status: 200
buffer: "action2 #{tostring s}"
}, { :status, :buffer }
it "included application supports require'd action and include name", ->
s = {}
package.loaded["actions.subapp.hello"] = -> "subapp action1 #{s}"
package.loaded["actions.subapp.admin.cool"] = -> "subapp action2 #{s}"
class SubApp extends lapis.Application
name: "subapp."
[hello: "/cool-dad"]: true
[world: "/uncool-dad"]: "admin.cool"
class SomeApp extends lapis.Application
layout: false
@include SubApp
"/some-dad": => "hi"
status, buffer, headers = mock_request SomeApp, "/cool-dad", {}
assert.same {
status: 200
buffer: "subapp action1 #{tostring s}"
}, { :status, :buffer }
status, buffer, headers = mock_request SomeApp, "/uncool-dad", {}
assert.same {
status: 200
buffer: "subapp action2 #{tostring s}"
}, { :status, :buffer }
it "included application supports require'd action with before filter", ->
s = {}
package.loaded["actions.one"] = => "action1 #{s} #{@something}"
package.loaded["actions.admin.two"] = => "action2 #{s} #{@something}"
class SubApp extends lapis.Application
@before_filter (r) =>
@something = "Before filter has run!"
[one: "/cool-dad"]: true
[two: "/uncool-dad"]: "admin.two"
class SomeApp extends lapis.Application
layout: false
@include SubApp
"/some-dad": => "hi"
status, buffer, headers = mock_request SomeApp, "/cool-dad", {}
assert.same {
status: 200
buffer: "action1 #{s} Before filter has run!"
}, { :status, :buffer }
status, buffer, headers = mock_request SomeApp, "/uncool-dad", {}
assert.same {
status: 200
buffer: "action2 #{s} Before filter has run!"
}, { :status, :buffer }
status, buffer, headers = mock_request SomeApp, "/some-dad", {}
assert.same {
status: 200
buffer: "hi"
}, { :status, :buffer }
describe "default route", ->
it "hits default route", ->
local res
class App extends lapis.Application
"/": =>
default_route: =>
res = "bingo!"
status, body = mock_request App, "/hello", {}
assert.same 200, status
assert.same "bingo!", res
describe "default layout", ->
after_each ->
package.loaded["views.test_layout"] = nil
it "uses widget as layout", ->
import Widget from require "lapis.html"
class TestApp extends lapis.Application
layout: class Layout extends Widget
content: =>
h1 "hello world"
@content_for "inner"
div class: "footer"
"/": => "yeah"
status, body = assert_request TestApp, "/"
assert.same [[<h1>hello world</h1>yeah<div class="footer"></div>]], body
it "uses module name as layout", ->
import Widget from require "lapis.html"
class Layout extends Widget
content: =>
div class: "content", ->
@content_for "inner"
package.loaded["views.test_layout"] = Layout
class TestApp extends lapis.Application
layout: "test_layout"
"/": => "yeah"
status, body = assert_request TestApp, "/"
assert.same [[<div class="content">yeah</div>]], body
describe "error capturing", ->
import capture_errors, capture_errors_json, assert_error,
yield_error from require "lapis.application"
it "should capture error", ->
result = "no"
errors = nil
class ErrorApp extends lapis.Application
"/error_route": capture_errors {
on_error: =>
errors = @errors
=>
yield_error "something bad happened!"
result = "yes"
}
assert_request ErrorApp, "/error_route"
assert.same "no", result
assert.same {"something bad happened!"}, errors
it "should capture error as json", ->
result = "no"
class ErrorApp extends lapis.Application
"/error_route": capture_errors_json =>
yield_error "something bad happened!"
result = "yes"
status, body, headers = assert_request ErrorApp, "/error_route"
assert.same "no", result
assert.same [[{"errors":["something bad happened!"]}]], body
assert.same "application/json", headers["Content-Type"]
describe "instancing", ->
it "should match a route", ->
local res
app = lapis.Application!
app\match "/", => res = "root"
app\match "/user/:id", => res = @params.id
app\build_router!
assert_request app, "/"
assert.same "root", res
assert_request app, "/user/124"
assert.same "124", res
it "should should respond to verb", ->
local res
app = lapis.Application!
app\match "/one", ->
app\get "/hello", => res = "get"
app\post "/hello", => res = "post"
app\match "two", ->
app\build_router!
assert_request app, "/hello"
assert.same "get", res
assert_request app, "/hello", post: {}
assert.same "post", res
it "should hit default route", ->
local res
app = lapis.Application!
app\match "/", -> res = "/"
app.default_route = -> res = "default_route"
app\build_router!
assert_request app, "/hello"
assert.same "default_route", res
it "should strip trailing / to find route", ->
local res
app = lapis.Application!
app\match "/hello", -> res = "/hello"
app\match "/world/", -> res = "/world/"
app\build_router!
-- exact match, no default action
assert_request app, "/world/"
assert.same "/world/", res
status, _, headers = assert_request app, "/hello/"
assert.same 301, status
assert.same "http://localhost/hello", headers.location
it "should include another app", ->
do return pending "implement include for instances"
local res
sub_app = lapis.Application!
sub_app\get "/hello", => res = "hello"
app = lapis.Application!
app\get "/cool", => res = "cool"
app\include sub_app
it "should preserve order of route", ->
app = lapis.Application!
routes = for i=1,20
with r = "/route#{i}"
app\get r, =>
app\build_router!
assert.same routes, [tuple[1] for tuple in *app.router.routes]
describe "errors", ->
class ErrorApp extends lapis.Application
"/": =>
error "I am an error!"
it "renders default error page", ->
status, body, h = mock_request ErrorApp, "/", allow_error: true
assert.same 500, status
assert.truthy (body\match "I am an error")
-- only set on test env
assert.truthy h["X-Lapis-Error"]
it "raises error in spec by default", ->
assert.has_error ->
mock_request ErrorApp, "/"
it "renders custom error page", ->
class CustomErrorApp extends lapis.Application
handle_error: (err, msg) =>
assert.truthy @original_request
"hello world", layout: false, status: 444
"/": =>
error "I am an error!"
status, body, h = mock_request CustomErrorApp, "/", allow_error: true
assert.same 444, status
assert.same "hello world", body
-- should still be set
assert.truthy h["X-Lapis-Error"]
describe "custom request", ->
it "renders with custom request (overriding supuport)", ->
class R extends lapis.Application.Request
@support: {
load_session: =>
@session = {"cool"}
write_session: =>
}
local the_session
class A extends lapis.Application
Request: R
"/": =>
the_session = @session
"ok"
mock_request A, "/"
assert.same {"cool"}, the_session
-- should be requrest spec?
describe "inline html", ->
class HtmlApp extends lapis.Application
layout: false
"/": =>
@html -> div "hello world"
it "should render html", ->
status, body = assert_request HtmlApp, "/"
assert.same "<div>hello world</div>", body
-- this should be in request spec...
describe "request:build_url", ->
it "should build url", ->
assert.same "http://localhost", mock_app "/hello", {}, =>
@build_url!
it "should build url with path", ->
assert.same "http://localhost/hello_dog", mock_app "/hello", {}, =>
@build_url "hello_dog"
it "should build url with host and port", ->
assert.same "http://leaf:2000/hello",
mock_app "/hello", { host: "leaf", port: 2000 }, =>
@build_url @req.parsed_url.path
it "doesn't include default port for scheme http", ->
assert.same "http://leaf/whoa",
mock_app "/hello", { host: "leaf", port: 80 }, =>
@build_url "whoa"
it "doesn't include default port for scheme https", ->
assert.same "https://leaf/whoa",
mock_app "/hello", { host: "leaf", scheme: "https", port: 443 }, =>
@build_url "whoa"
it "should build url with overridden query", ->
assert.same "http://localhost/please?yes=no",
mock_app "/hello", {}, =>
@build_url "please?okay=world", { query: "yes=no" }
it "should build url with overridden port and host", ->
assert.same "http://yes:4545/cat?sure=dad",
mock_app "/hello", { host: "leaf", port: 2000 }, =>
@build_url "cat?sure=dad", host: "yes", port: 4545
it "should return arg if already build url", ->
assert.same "http://leafo.net",
mock_app "/hello", { host: "leaf", port: 2000 }, =>
@build_url "http://leafo.net"
| 27.376344 | 82 | 0.617046 |
700e98631bfd2453631df713a737265508dc83fd | 288 | #!/usr/bin/env moon
-- vim: ts=2 sw=2 et :
-- Data header utils
is={}
is.weighted= (s)-> if s\find"-" then -1 else 1
is.klass = (s)-> s\find"!"
is.skip = (s)-> s\find"?"
is.num = (s)-> s\match"^[A-Z]"
is.y = (s)-> s\find"+" or s\find"-" or is.klass s
-- Returns...
:is
| 19.2 | 55 | 0.496528 |
768fca3fd18c4227b6b50d800501ab7947455894 | 6,690 | Dorothy!
ScrollAreaView = require "View.Control.Basic.ScrollArea"
-- [signals]
-- "ScrollTouchBegan",->
-- "ScrollTouchEnded",->
-- "ScrollStart",->
-- "ScrollEnd",->
-- "Scrolled",(delta)->
-- [params]
-- x,y,width,height,
-- paddingX,paddingY,
-- viewWidth,viewHeight,
-- touchPriority
Class ScrollAreaView,
__init: (args)=>
{:width,:height,:touchPriority} = args
touchPriority = touchPriority or CCMenu.DefaultHandlerPriority
winHeight = CCDirector.winSize.height
viewWidth = math.max args.viewWidth or width,width
viewHeight = math.max args.viewHeight or height,height
moveY = viewHeight - height
moveX = viewWidth - width
deltaX,deltaY = 0,0
paddingX = args.paddingX or 200
paddingY = args.paddingY or 200
posX,posY = 0,0
timePassed = 0
S = oVec2.zero
V = oVec2.zero
deltaMoveLength = 0
updateReset = (deltaTime)->
local x,y
timePassed += deltaTime
t = math.min timePassed*4,1
with oEase
if posX < -moveX
tmp = deltaX
deltaX = \func .OutQuad,t,posX,-moveX-posX
x = deltaX - tmp
elseif posX > 0
tmp = deltaX
deltaX = \func .OutQuad,t,posX,0-posX
x = deltaX - tmp
if posY < 0
tmp = deltaY
deltaY = \func .OutQuad,t,posY,0-posY
y = deltaY - tmp
elseif posY > moveY
tmp = deltaY
deltaY = \func .OutQuad,t,posY,moveY-posY
y = deltaY - tmp
x or= 0
y or= 0
@emit "Scrolled",oVec2(x,y)
if t == 1
@unschedule!
@emit "ScrollEnd"
isReseting = ->
not @dragging and (deltaX > 0 or deltaX < -moveX or deltaY > moveY or deltaY < 0)
startReset = ->
posX = deltaX
posY = deltaY
timePassed = 0
@schedule updateReset
setOffset = (delta, touching)->
dPosX = delta.x
dPosY = delta.y
newPosX = deltaX + dPosX
newPosY = deltaY + dPosY
newPosX = math.min newPosX, paddingX
newPosX = math.max newPosX, -moveX-paddingX
newPosY = math.max newPosY, -paddingY
newPosY = math.min newPosY, moveY+paddingY
dPosX = newPosX - deltaX
dPosY = newPosY - deltaY
if touching
lenY = if newPosY < 0
(0-newPosY)/paddingY
elseif newPosY > moveY
(newPosY-moveY)/paddingY
else 0
lenX = if newPosX > 0
(newPosX-0)/paddingX
elseif newPosX < -moveX
(-moveX-newPosX)/paddingX
else 0
if lenY > 0
v = lenY*3
dPosY = dPosY / math.max v*v,1
if lenX > 0
v = lenX*3
dPosX = dPosX / math.max v*v,1
deltaX += dPosX
deltaY += dPosY
@emit "Scrolled",oVec2(dPosX,dPosY)
startReset! if not touching and
(newPosY < -paddingY*0.5 or
newPosY > moveY+paddingY*0.5 or
newPosX > paddingX*0.5 or
newPosX < -moveX-paddingX*0.5)
accel = winHeight*2
updateSpeed = (dt)->
V = S / dt
if V.length > accel
V\normalize!
V = V * accel
S = oVec2.zero
updatePos = (dt)->
dir = oVec2 V.x,V.y
dir\normalize!
A = dir * -accel
incX = V.x > 0
incY = V.y > 0
V = V + A * dt * 0.5
decX = V.x < 0
decY = V.y < 0
if incX == decX and incY == decY
if isReseting!
startReset!
else
@unschedule!
@emit "ScrollEnd"
else
dS = V * dt
setOffset dS,false
@touchEnabled = true
@touchPriority = touchPriority
@slot "TouchBegan",(touch)->
return false unless touch.id == 0
pos = @convertToNodeSpace touch.location
rect = CCRect oVec2(-@width*0.5,-@height*0.5),CCSize(@width,@height)
return false unless rect\containsPoint pos
deltaMoveLength = 0
S = oVec2.zero
V = oVec2.zero
@schedule updateSpeed
@emit "ScrollTouchBegan"
true
touchEnded = ->
@dragging = false
if isReseting!
startReset!
elseif V ~= oVec2.zero and deltaMoveLength > 10
@schedule updatePos
else
@emit "ScrollEnd"
@emit "ScrollTouchEnded"
@slot "TouchEnded",touchEnded
@slot "TouchCancelled",touchEnded
@slot "TouchMoved",(touch)->
lastMoveLength = deltaMoveLength
S = touch.delta
deltaMoveLength += S.length
if deltaMoveLength > 10
setOffset S,true
if lastMoveLength <= 10
@dragging = true
@emit "ScrollStart"
@scroll = (delta)=>
if delta
deltaX += delta.x
deltaY += delta.y
@emit "Scrolled",oVec2(delta.x,delta.y)
startReset! if isReseting!
@scrollTo = (offset)=>
delta = offset - oVec2 deltaX,deltaY
deltaX = offset.x
deltaY = offset.y
@emit "Scrolled",delta
@updateViewSize = (wView,hView)=>
{:width,:height} = @
viewWidth = math.max wView,width
viewHeight = math.max hView,height
moveY = viewHeight - height
moveX = viewWidth - width
@scroll oVec2.zero
@reset = (wView,hView,padX,padY)=>
@updateViewSize wView,hView
paddingX = padX
paddingY = padY
deltaX,deltaY = 0,0
posX,posY = 0,0
timePassed = 0
S = oVec2.zero
V = oVec2.zero
deltaMoveLength = 0
@updatePadding = (padX,padY)=>
paddingX = padX
paddingY = padY
@scroll oVec2.zero
@getPadding = -> oVec2 paddingX,paddingY
@getViewSize = -> CCSize viewWidth,viewHeight
@getTotalDelta = -> oVec2 deltaX,deltaY
offset:property => @getTotalDelta!,
(offset)=> @scroll offset-@getTotalDelta!
viewSize:property => @getViewSize!,
(size)=> @updateViewSize size.width,size.height
padding:property => @getPadding!,
(padding)=> @updatePadding padding.x,padding.y
setupMenuScroll:(menu)=>
@slot "Scrolled",(delta)->
menu\moveAndCullItems delta -- reduce draw calls
menuEnabled = true
@slot "ScrollStart",->
menuEnabled = menu.enabled
menu.enabled = false
@slot "ScrollTouchEnded",->
menu.enabled = menuEnabled if not menu.enabled
adjustScrollSize:(menu,padding=10,alignMode="auto")=> -- alignMode:auto,vertical,horizontal
offset = @offset
@scrollTo oVec2.zero
@viewSize = switch alignMode
when "auto"
menu\alignItems padding
when "vertical"
menu\alignItemsVertically padding
when "horizontal"
menu\alignItemsHorizontally padding
@scrollTo offset
@scroll!
scrollToPosY:(posY,time=0.3)=>
height = @height
offset = @offset
viewHeight = @viewSize.height
deltaY = height/2-posY
startY = offset.y
endY = startY+deltaY
if viewHeight <= height
endY = 0
else
endY = math.max endY,0
endY = math.min endY,viewHeight-height
@schedule once ->
changeY = endY-startY
cycle time,(progress)->
offset.y = oEase\func oEase.OutQuad,progress,startY,changeY
@scrollTo offset
offset.y = endY
@scrollTo offset
| 24.777778 | 93 | 0.623169 |
77ead03a69f729fef9368c8613e1bcc440250817 | 132 | Component = require "lib.concord.component"
BoundingBox = Component (entity) ->
-- TODO: Allow the user to place different
return | 33 | 43 | 0.75 |
d44f5b4d4b1ea1a6631ad920e8b5a7f7d09d5b2a | 12,531 |
lapis = require "lapis"
import mock_action, mock_request, assert_request from require "lapis.spec.request"
mock_app = (...) ->
mock_action lapis.Application, ...
describe "find_action", ->
action1 = ->
action2 = ->
it "finds action", ->
class SomeApp extends lapis.Application
[hello: "/cool-dad"]: action1
[world: "/another-dad"]: action2
assert.same action1, (SomeApp\find_action "hello")
assert.same action2, (SomeApp\find_action "world")
assert.same nil, (SomeApp\find_action "nothing")
it "finds require'd action", ->
package.loaded["actions.hello"] = action1
package.loaded["actions.admin.cool"] = action2
class SomeApp extends lapis.Application
[hello: "/cool-dad"]: true
[world: "/uncool-dad"]: "admin.cool"
assert.same action1, (SomeApp\find_action "hello")
assert.same action2, (SomeApp\find_action "world")
describe "dispatch", ->
describe "lazy loaded actions", ->
import mock_request from require "lapis.spec.request"
class BaseApp extends lapis.Application
[test_route: "/hello/:var"]: true
[another: "/good-stuff"]: "hello_world"
[regular: "/hmm"]: ->
"/yo": true
before_each ->
package.loaded["actions.test_route"] = spy.new ->
package.loaded["actions.hello_world"] = spy.new ->
it "dispatches action by route name", ->
mock_request BaseApp, "/hello/5"
assert.spy(package.loaded["actions.test_route"]).was.called!
assert.spy(package.loaded["actions.hello_world"]).was_not.called!
it "dispatches action by string name", ->
mock_request BaseApp, "/good-stuff"
assert.spy(package.loaded["actions.test_route"]).was_not.called!
assert.spy(package.loaded["actions.hello_world"]).was.called!
it "doesn't call other actions for unrelated route", ->
mock_request BaseApp, "/hmm"
assert.spy(package.loaded["actions.test_route"]).was_not.called!
assert.spy(package.loaded["actions.hello_world"]).was_not.called!
mock_request BaseApp, "/hmm"
it "failes to load `true` action with no route name", ->
assert.has_error ->
mock_request BaseApp, "/yo"
describe "inheritance", ->
local result
before_each ->
result = nil
class BaseApp extends lapis.Application
"/yeah": => result = "base yeah"
[test_route: "/hello/:var"]: => result = "base test"
class ChildApp extends BaseApp
"/yeah": => result = "child yeah"
"/thing": => result = "child thing"
it "should find route in base app", ->
status, buffer, headers = mock_request ChildApp, "/hello/world", {}
assert.same 200, status
assert.same "base test", result
it "should generate url from route in base", ->
url = mock_action ChildApp, =>
@url_for "test_route", var: "foobar"
assert.same url, "/hello/foobar"
it "should override route in base class", ->
status, buffer, headers = mock_request ChildApp, "/yeah", {}
assert.same 200, status
assert.same "child yeah", result
describe "@include", ->
local result
before_each ->
result = nil
it "should include another app", ->
class SubApp extends lapis.Application
"/hello": => result = "hello"
class App extends lapis.Application
@include SubApp
"/world": => result = "world"
status, buffer, headers = mock_request App, "/hello", {}
assert.same 200, status
assert.same "hello", result
status, buffer, headers = mock_request App, "/world", {}
assert.same 200, status
assert.same "world", result
it "should merge url table", ->
class SubApp extends lapis.Application
[hello: "/hello"]: => result = "hello"
class App extends lapis.Application
@include SubApp
[world: "/world"]: => result = "world"
app = App!
req = App.Request App!, {}, {}
assert.same "/hello", req\url_for "hello"
assert.same "/world", req\url_for "world"
it "should set sub app prefix path", ->
class SubApp extends lapis.Application
[hello: "/hello"]: => result = "hello"
class App extends lapis.Application
@include SubApp, path: "/sub"
[world: "/world"]: => result = "world"
app = App!
req = App.Request App!, {}, {}
assert.same "/sub/hello", req\url_for "hello"
assert.same "/world", req\url_for "world"
it "should set sub app url name prefix", ->
class SubApp extends lapis.Application
[hello: "/hello"]: => result = "hello"
class App extends lapis.Application
@include SubApp, name: "sub_"
[world: "/world"]: => result = "world"
app = App!
req = App.Request App!, {}, {}
assert.has_error -> req\url_for "hello"
assert.same "/hello", req\url_for "sub_hello"
assert.same "/world", req\url_for "world"
it "should set include options from target app", ->
class SubApp extends lapis.Application
@path: "/sub"
@name: "sub_"
[hello: "/hello"]: => result = "hello"
class App extends lapis.Application
@include SubApp
[world: "/world"]: => result = "world"
app = App!
req = App.Request App!, {}, {}
assert.same "/sub/hello", req\url_for "sub_hello"
assert.same "/world", req\url_for "world"
describe "default route", ->
it "hits default route", ->
local res
class App extends lapis.Application
"/": =>
default_route: =>
res = "bingo!"
status, body = mock_request App, "/hello", {}
assert.same 200, status
assert.same "bingo!", res
describe "default layout", ->
after_each ->
package.loaded["views.test_layout"] = nil
it "uses widget as layout", ->
import Widget from require "lapis.html"
class TestApp extends lapis.Application
layout: class Layout extends Widget
content: =>
h1 "hello world"
@content_for "inner"
div class: "footer"
"/": => "yeah"
status, body = assert_request TestApp, "/"
assert.same [[<h1>hello world</h1>yeah<div class="footer"></div>]], body
it "uses module name as layout", ->
import Widget from require "lapis.html"
class Layout extends Widget
content: =>
div class: "content", ->
@content_for "inner"
package.loaded["views.test_layout"] = Layout
class TestApp extends lapis.Application
layout: "test_layout"
"/": => "yeah"
status, body = assert_request TestApp, "/"
assert.same [[<div class="content">yeah</div>]], body
describe "error capturing", ->
import capture_errors, capture_errors_json, assert_error,
yield_error from require "lapis.application"
it "should capture error", ->
result = "no"
errors = nil
class ErrorApp extends lapis.Application
"/error_route": capture_errors {
on_error: =>
errors = @errors
=>
yield_error "something bad happened!"
result = "yes"
}
assert_request ErrorApp, "/error_route"
assert.same "no", result
assert.same {"something bad happened!"}, errors
it "should capture error as json", ->
result = "no"
class ErrorApp extends lapis.Application
"/error_route": capture_errors_json =>
yield_error "something bad happened!"
result = "yes"
status, body, headers = assert_request ErrorApp, "/error_route"
assert.same "no", result
assert.same [[{"errors":["something bad happened!"]}]], body
assert.same "application/json", headers["Content-Type"]
describe "instancing", ->
it "should match a route", ->
local res
app = lapis.Application!
app\match "/", => res = "root"
app\match "/user/:id", => res = @params.id
app\build_router!
assert_request app, "/"
assert.same "root", res
assert_request app, "/user/124"
assert.same "124", res
it "should should respond to verb", ->
local res
app = lapis.Application!
app\match "/one", ->
app\get "/hello", => res = "get"
app\post "/hello", => res = "post"
app\match "two", ->
app\build_router!
assert_request app, "/hello"
assert.same "get", res
assert_request app, "/hello", post: {}
assert.same "post", res
it "should hit default route", ->
local res
app = lapis.Application!
app\match "/", -> res = "/"
app.default_route = -> res = "default_route"
app\build_router!
assert_request app, "/hello"
assert.same "default_route", res
it "should strip trailing / to find route", ->
local res
app = lapis.Application!
app\match "/hello", -> res = "/hello"
app\match "/world/", -> res = "/world/"
app\build_router!
-- exact match, no default action
assert_request app, "/world/"
assert.same "/world/", res
status, _, headers = assert_request app, "/hello/"
assert.same 301, status
assert.same "http://localhost/hello", headers.location
it "should include another app", ->
do return pending "implement include for instances"
local res
sub_app = lapis.Application!
sub_app\get "/hello", => res = "hello"
app = lapis.Application!
app\get "/cool", => res = "cool"
app\include sub_app
it "should preserve order of route", ->
app = lapis.Application!
routes = for i=1,20
with r = "/route#{i}"
app\get r, =>
app\build_router!
assert.same routes, [tuple[1] for tuple in *app.router.routes]
describe "errors", ->
class ErrorApp extends lapis.Application
"/": =>
error "I am an error!"
it "renders default error page", ->
status, body, h = mock_request ErrorApp, "/", allow_error: true
assert.same 500, status
assert.truthy (body\match "I am an error")
-- only set on test env
assert.truthy h["X-Lapis-Error"]
it "raises error in spec by default", ->
assert.has_error ->
mock_request ErrorApp, "/"
it "renders custom error page", ->
class CustomErrorApp extends lapis.Application
handle_error: (err, msg) =>
assert.truthy @original_request
"hello world", layout: false, status: 444
"/": =>
error "I am an error!"
status, body, h = mock_request CustomErrorApp, "/", allow_error: true
assert.same 444, status
assert.same "hello world", body
-- should still be set
assert.truthy h["X-Lapis-Error"]
describe "custom request", ->
it "renders with custom request (overriding supuport)", ->
class R extends lapis.Application.Request
@support: {
load_session: =>
@session = {"cool"}
write_session: =>
}
local the_session
class A extends lapis.Application
Request: R
"/": =>
the_session = @session
"ok"
mock_request A, "/"
assert.same {"cool"}, the_session
-- should be requrest spec?
describe "inline html", ->
class HtmlApp extends lapis.Application
layout: false
"/": =>
@html -> div "hello world"
it "should render html", ->
status, body = assert_request HtmlApp, "/"
assert.same "<div>hello world</div>", body
-- this should be in request spec...
describe "request:build_url", ->
it "should build url", ->
assert.same "http://localhost", mock_app "/hello", {}, =>
@build_url!
it "should build url with path", ->
assert.same "http://localhost/hello_dog", mock_app "/hello", {}, =>
@build_url "hello_dog"
it "should build url with host and port", ->
assert.same "http://leaf:2000/hello",
mock_app "/hello", { host: "leaf", port: 2000 }, =>
@build_url @req.parsed_url.path
it "doesn't include default port for scheme http", ->
assert.same "http://leaf/whoa",
mock_app "/hello", { host: "leaf", port: 80 }, =>
@build_url "whoa"
it "doesn't include default port for scheme https", ->
assert.same "https://leaf/whoa",
mock_app "/hello", { host: "leaf", scheme: "https", port: 443 }, =>
@build_url "whoa"
it "should build url with overridden query", ->
assert.same "http://localhost/please?yes=no",
mock_app "/hello", {}, =>
@build_url "please?okay=world", { query: "yes=no" }
it "should build url with overridden port and host", ->
assert.same "http://yes:4545/cat?sure=dad",
mock_app "/hello", { host: "leaf", port: 2000 }, =>
@build_url "cat?sure=dad", host: "yes", port: 4545
it "should return arg if already build url", ->
assert.same "http://leafo.net",
mock_app "/hello", { host: "leaf", port: 2000 }, =>
@build_url "http://leafo.net"
| 27.480263 | 82 | 0.621419 |
510e923c3bcf05bd44a0c77c49057b4107aff565 | 1,778 | export class GridCollider extends Collider
new: (@width, @height, @columns = 10, @rows = 10) =>
error("Grid width and height cannot be 0") if @width == 0 or @height == 0
super!
@cell_width = math.floor @width / @columns
@cell_height = math.floor @height / @rows
@initialize!
initialize: =>
@source_list = {}
@grid = {}
@grid[i] = {} for i = 0, @columns * @rows - 1
reset: =>
@source_list[k] = nil for k in pairs @source_list
bucket[k] = nil for bucket in *@grid for k in pairs bucket
build: (source, target) =>
error("Cannot use spacial hashing on tilemaps") if source.__type == "tilemap" or target.__type == "tilemap"
@add_all source, @source_list
@add_to_bucket target
add_to_bucket: (entity) =>
if entity.__type == "group"
@add_to_bucket object for object in *entity.members when object.active and object.exists
else
for x = math.max(0, math.floor(entity.x / @cell_width)), math.min(@columns - 1, math.floor((entity.x + entity.width) / @cell_width))
for y = math.max(0, math.floor(entity.y / @cell_height)), math.min(@rows - 1, math.floor((entity.y + entity.height) / @cell_height))
table.insert @grid[y * @columns + x], entity
overlap: => @overlap_with_callback @overlap_against_bucket_callback
collide: => @overlap_with_callback @collide_against_bucket_callback
overlap_with_callback: (overlap_function) =>
overlap_found = false
for entity in *@source_list
for x = math.max(0, math.floor(entity.x / @cell_width)), math.min(@columns - 1, math.floor((entity.x + entity.width) / @cell_width))
for y = math.max(0, math.floor(entity.y / @cell_height)), math.min(@rows - 1, math.floor((entity.y + entity.height) / @cell_height))
overlap_found = true if overlap_function entity, @grid[y * @columns + x] | 43.365854 | 136 | 0.685039 |
ef2c0531b060f1b19f9806c069c2a6a88e810ade | 7,567 | -- Copyright 2012-2018 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import dispatch, interact from howl
import style, markup from howl.ui
append = table.insert
style.define_default 'command_name', 'keyword'
commands = {}
accessible_names = {}
resolve_command = (name) ->
-- return a command definition for a command name or an alias
def = commands[name]
def = commands[def.alias_for] if def and def.alias_for -- alias
def
accessible_name = (name) ->
name\lower!\gsub '[%s%p]+', '_'
parse_cmd = (text) ->
cmd_name, rest = text\match '^%s*([^%s]+)%s+(.*)$'
return resolve_command(cmd_name), cmd_name, rest if cmd_name
register = (cmd_def) ->
for field in *{'name', 'description'}
error 'Missing field for command: "' .. field .. '"' if not cmd_def[field]
if not cmd_def.handler
error 'Command "handler" required for ' .. cmd_def.name
cmd_def = moon.copy cmd_def
commands[cmd_def.name] = cmd_def
sane_name = accessible_name cmd_def.name
accessible_names[sane_name] = cmd_def if sane_name != cmd_def.name
unregister = (name) ->
cmd = commands[name]
return if not cmd
commands[name] = nil
aliases = {}
for cmd_name, def in pairs commands
append aliases, cmd_name if def.alias_for == name
commands[alias] = nil for alias in *aliases
sane_name = accessible_name name
accessible_names[sane_name] = nil if sane_name != name
alias = (target, name, opts = {}) ->
error 'Target ' .. target .. ' does not exist' if not commands[target]
def = moon.copy opts
def.alias_for = target
commands[name] = def
get = (name) -> commands[name]
names = -> [name for name in pairs commands]
command_bindings = ->
c_bindings = {}
for map in *howl.bindings.keymaps
for m in *{ map, map['editor'] or {} }
c_bindings[cmd] = binding for binding, cmd in pairs m when type(cmd) == 'string'
c_bindings
get_command_items = ->
cmd_names = names!
bindings = command_bindings!
table.sort cmd_names
items = {}
for name in *cmd_names
def = commands[name]
desc = def.description
if def.alias_for
desc = "(Alias for #{def.alias_for})"
desc = "[deprecated] #{desc}" if def.deprecated
binding = bindings[name] or ''
append items, { name, binding, desc, cmd_text: name }
return items
history = {} -- array of {styled_text:, text:} objects
record_history = (cmd_name, input_text) ->
local styled_text, text
if input_text and not input_text.is_empty
styled_text = markup.howl("<command_name>:#{cmd_name}</> #{input_text}")
text = "#{cmd_name} #{input_text}"
else
styled_text = markup.howl("<command_name>:#{cmd_name}</>")
text = cmd_name
item = {:styled_text, :text}
-- don't duplicate repeated commands
history = [h_item for h_item in *history when h_item.text != item.text]
append history, 1, item
-- prune
if #history > 1000
history = [history[i] for i=1,1000]
get_input_text = (cmd, input) ->
-- convert the input object to input_text - a text representation of input used in the history
-- this is done either via cmd.get_input_text function if present
-- or using some simple heuristics
if cmd.get_input_text
return cmd.get_input_text input
if typeof(input) == 'File'
return input.short_path
if type(input) == 'table' and input.input_text
return input.input_text
return tostring input
get_command_history = -> [{item.styled_text, text: item.text} for item in *history]
ensure_command_can_run = (cmd) ->
unless howl.app.window
error "Cannot run command '#{cmd}', application not initialized. Try using the 'app-ready' signal.", 3
launch_cmd = (cmd, args) ->
dispatch.launch ->
ok, err = pcall -> cmd.handler table.unpack args
if not ok
log.error err
run = (cmd_text=nil) ->
-- run a command string, either immediately, or after asking for input if necessary
capture_history = true
ensure_command_can_run cmd_text
cmd_text or= ''
cmd, cmd_name, rest = parse_cmd cmd_text
unless cmd
cmd, cmd_name, rest = resolve_command(cmd_text), cmd_text, ''
if cmd
-- don't capture history for automatically selected commands that are run immediately
capture_history = false
-- if we couldn't resolve a command,
-- or we resolved a command that doesn't take input, but we have extra command text
-- then require command selection
if not cmd or (not rest.is_empty and not cmd.input)
cmd, cmd_name, rest = howl.interact.select_command text: cmd_text, prompt: ':'
return unless cmd
rest or= ''
help = howl.ui.HelpContext!
help\add_section heading: "Command '#{cmd.name}'", text: cmd.description
-- the command definition may or may not have an input function
if cmd.input
-- invoke the input function to get input data and then invoke the handler
inputs = table.pack cmd.input
prompt: ':'..cmd_name..' '
text: rest
:help
return if inputs[1] == nil -- input was cancelled
-- record history
input_text = get_input_text cmd, inputs[1]
if input_text
record_history cmd_name, input_text
-- invoke handler
cmd.handler table.unpack inputs
else
-- no input function, invoke the handler directly
if capture_history
record_history cmd_name, ''
cmd.handler!
class CommandConsole
new: =>
@commands = get_command_items!
-- compute column styles (including min_width) used for completion list
name_width = 0
shortcut_width = 0
for item in *@commands
name_width = math.max(name_width, item[1].ulen)
shortcut_width = math.max(shortcut_width, item[2].ulen)
@completion_columns = {{style: 'string', min_width: name_width}, {style: 'keyword', min_width: shortcut_width}, {style: 'comment'}}
display_prompt: => ":"
display_title: => "Command"
complete: (text) =>
word, spaces = text\match '^(%S+)(%s*)'
if not spaces or spaces.is_empty
return name: 'command', completions: @commands, match_text: word, columns: @completion_columns
select: (text, item, completion_opts) =>
@run item.cmd_text
parse: (text) =>
_, spaces = text\match '^(%S+)(%s*)'
if spaces and not spaces.is_empty
@run text
run: (text) =>
cmd_name, space, rest = text\match '^(%S+)(%s?)(.*)'
cmd = resolve_command cmd_name
if cmd
if not space.is_empty and not cmd.input
msg = "Command '#{cmd_name}' accepts no input - press <enter> to run.", 0
return text: cmd_name, error: msg
return result: {:cmd_name, :rest, :cmd}
else
error "No such command: #{cmd_name}"
get_history: => get_command_history!
interact.register
name: 'select_command'
description: 'Selection list for all commands'
handler: (opts={}) ->
help = howl.ui.HelpContext!
with help
\add_section
heading: "Command 'run'"
text: 'Run a command'
\add_section
heading: 'Usage'
text: 'Type a command name and press <keystroke>enter</> to run.'
\add_keys
tab: 'Show command list'
up: 'Show command history'
result = howl.app.window.command_panel\run howl.ui.ConsoleView(CommandConsole!), text: opts.text, :help
return unless result
result.cmd, result.cmd_name, result.rest
return setmetatable {:register, :unregister, :alias, :run, :names, :get, :record_history}, {
__index: (key) =>
command = commands[key] or accessible_names[key]
return unless command
ensure_command_can_run command.name
(...) -> launch_cmd command, table.pack ...
}
| 29.791339 | 135 | 0.675961 |
34c1bcf0bd0acd3f9d67a404ecbcff38c4923621 | 7,603 | export script_name = "Text in Clip"
export script_description = "Causes the characters in your text to go through the coordinates of your clip!"
export script_author = "Zeref"
export script_version = "2.0.0"
-- LIB
zf = require "ZF.main"
setConfig = (shape, width, offset = 0, mode = 1) ->
shap = zf.shape shape, false
slen = shap\length!
size = slen - width
offx = switch mode
when 1, "Left" then offset
when 2, "Center" then size / 2 + offset
when 3, "Right" then size - offset
animated = mode == "Animated - Left to Right" or mode == "Animated - Right to Left"
offset = (animated and offset <= 0) and 1 or offset
return {:shap, :slen, :size, :offx, :animated, :offset}
getTextInClipValues = (t, shape, tag, char) ->
angle, {:x, :y} = 0, char
if 0 <= t and t <= 1
tan, pnt = shape\getNormal t
angle = zf.math\round deg(atan2(-tan.y, tan.x)) - 90
pnt\round 3
{:x, :y} = pnt
__tags = zf.tags\replaceCoords tag.tags, {x, y}
__tags = zf.tags\insertTags __tags, "\\frz#{angle}"
__tags = zf.tags\removeTags __tags, "clip", "iclip"
return __tags .. char.text_stripped
interface = ->
items = {"Left", "Center", "Right", "Around", "Animated - Left to Right", "Animated - Right to Left"}
hints = {
items: "Position of the text relative to the text",
offset: "The offset value of the position of the text \nrelative to the clip. \nIn case of animations, the value is a natural \nnumber that equals the frame step."
}
{
{class: "label", label: "Modes:", x: 0, y: 0}
{class: "dropdown", name: "mds", :items, hint: hints.items, x: 0, y: 1, value: items[1]}
{class: "checkbox", name: "ens", label: "Enable shape?", x: 0, y: 2, value: false}
{class: "label", label: "\nOffset:", x: 0, y: 3}
{class: "intedit", name: "off", hint: hints.offset, x: 0, y: 4, value: 0}
{class: "checkbox", name: "remove", label: "Remove selected layers?", x: 0, y: 5, value: true}
}
main = (subs, selected, active, button, elements) ->
new_selection, i = {}, {0, 0, selected[#selected], zf.util\getFirstLine subs}
gui = zf.config\loadGui interface!, script_name
while true
button, elements = aegisub.dialog.display gui, {"Ok", "Reset", "Cancel"}, close: "Cancel"
gui = switch button
when "Reset" then interface!
when "Cancel" then return
else break
zf.config\saveGui elements, script_name
for sel in *selected
dialogue_index = sel + i[1] - i[2] - i[4] + 1
aegisub.progress.set 100 * sel / i[3]
aegisub.progress.task "Processing line: #{dialogue_index}"
-- gets the current line
l, remove = subs[sel + i[1]], elements.remove
-- skips execution if execution is not possible
unless zf.util\runMacro l
zf.util\warning "The line is commented out or it is an empty line with possible blanks.", dialogue_index
remove = false
continue
-- gets the first tag and the text stripped
rawTag, rawTxt = zf.tags\getRawText l.text
-- checks if the \clip tag exists
unless zf.tags\getTagInTags(rawTag, "clip") or zf.tags\getTagInTags(rawTag, "iclip")
zf.util\warning "The line does not have the \"\\clip\" or \"\\iclip\" tag, they are necessary for the macro to work.", dialogue_index
remove = false
continue
clip = zf.util\clip2Draw rawTag
-- copies the current line
line = zf.table(l)\copy!
line.text = line.text\gsub("\\N", " ")\gsub "\\move%b()", ""
line.comment = false
-- calls the TEXT class to get the necessary values
callText = zf.text subs, line
{:coords} = callText
{px, py} = coords.pos
shape = zf.util\isShape rawTxt
if shape and not elements.ens
zf.util\warning "The line has a shape, you must activate the \"Enable Shape?\" checkbox to enable the use of shapes.", dialogue_index
remove = false
continue
elseif not shape and elements.ens
shape = callText\toShape nil, px, py
rawTag = zf.tags\clear rawTag, "To Text"
rawTag = zf.tags\insertTag rawTag, "\\p1"
with elements
fbf = zf.fbf line
-- if it's text
unless .ens
tags = callText\tags2Lines!
left = line.left - (tags.width - line.width) / 2
{:shap, :slen, :size, :offx, :animated, :offset} = setConfig clip, tags.width, .off, .mds
zf.util\deleteLine l, subs, sel, remove, i
for ti, tag in ipairs tags
chars = callText\chars tag
charn = chars.n
for ci, char in ipairs chars
cx = char.x
if animated
for s, e, d, j, n in fbf\iter offset
break if aegisub.progress.is_cancelled!
u = (j - 1) / (n - 1)
u = .mds == "Animated - Right to Left" and 1 - u or u
t = (u * size + cx - left) / slen
tag.start_time = s
tag.end_time = e
tag.text = getTextInClipValues t, shap, tag, char
zf.util\insertLine tag, subs, sel, new_selection, i
continue
elseif .mds == "Around"
u = (ci - 1) / (charn - 1)
t = (u * size + cx - left) / slen
tag.text = getTextInClipValues t, shap, tag, char
else
t = (offx + cx - left) / slen
tag.text = getTextInClipValues t, shap, tag, char
zf.util\insertLine tag, subs, sel, new_selection, i
else
rawTag = zf.tags\removeTags rawTag, "clip", "iclip"
rawTag = zf.tags\insertTags rawTag, "\\an7", "\\pos(0,0)"
shaper = zf.shape shape
{:shap, :slen, :size, :offx, :animated, :offset} = setConfig clip, shaper.w, .off, .mds
zf.util\deleteLine l, subs, sel, remove, i
if animated
for s, e, d, j, n in fbf\iter offset
break if aegisub.progress.is_cancelled!
u = (j - 1) / (n - 1)
u = .mds == "Animated - Right to Left" and 1 - u or u
line.start_time = s
line.end_time = e
line.text = rawTag .. zf.shape(shape)\inClip(line.styleref.align, shap, nil, nil, u * size)\build!
zf.util\insertLine line, subs, sel, new_selection, i
continue
elseif .mds == "Around"
line.text = rawTag .. shaper\inClip(line.styleref.align, shap, .mds, shaper.w)\build!
else
line.text = rawTag .. shaper\inClip(line.styleref.align, shap, .mds, nil, offset)\build!
zf.util\insertLine line, subs, sel, new_selection, i
remove = elements.remove
aegisub.set_undo_point script_name
if #new_selection > 0
return new_selection, new_selection[1]
aegisub.register_macro script_name, script_description, main | 50.350993 | 171 | 0.531501 |
0fe0af27a20cdc9686b979e71132af49540dadd5 | 1,292 |
utils = require("utils")
import proxyCall, protectedCall, namespace, getFullName from utils
class Module
new: (parent) =>
@submodules = {}
@parent = parent
start: (...) =>
proxyCall(@submodules,"start",...)
update: (...) =>
proxyCall(@submodules,"update",...)
addObject: (...) =>
proxyCall(@submodules,"addObject",...)
createObject: (...) =>
proxyCall(@submodules,"createObject",...)
deleteObject: (...) =>
proxyCall(@submodules,"deleteObject",...)
addPlayer: (...) =>
proxyCall(@submodules,"addPlayer",...)
createPlayer: (...) =>
proxyCall(@submodules,"createPlayer",...)
deletePlayer: (...) =>
proxyCall(@submodules,"deletePlayer",...)
save: (...) =>
return proxyCall(@submodules,"save",...)
load: (...) =>
data = ...
for i, v in pairs(@submodules)
protectedCall(v,"load",unpack(data[i]))
gameKey: (...) =>
proxyCall(@submodules,"gameKey", ...)
receive: (...) =>
proxyCall(@submodules,"receive", ...)
command: (...) =>
proxyCall(@submodules,"command", ...)
useModule: (cls, ...) =>
inst = cls(@, ...)
@submodules[getFullName(cls)] = inst
return inst
namespace("core", Module)
return Module
| 19.876923 | 67 | 0.54257 |
0e1852af02b416960429ec31de8bf41d1de855b0 | 1,776 | import cwd from process
import join from require "path"
-- ::ALLOWED_FRAGMENT_TYPES -> table
-- Represents which fragment types are parseable for the LunarBook
-- export
export ALLOWED_FRAGMENT_TYPES = {fragmentType, true for fragmentType in *{
".html"
".md"
}}
-- ::BOOK_HOME -> table
-- Represents the LunarBook related paths for the current book
-- export
export BOOK_HOME = with {}
-- BOOK_HOME::home -> string
-- Represents the home directory of the book
--
.home = cwd()
-- BOOK_HOME::data -> string
-- Represents the configuration directory for the book
--
.data = join(.home, ".lunarbook")
-- BOOK_HOME::assets -> string
-- Represents the directory for the user-shipped assets of the book
--
.assets = join(.data, "assets")
-- BOOK_HOME::theme -> string
-- Represents the directory for the local theme of the book
--
.theme = join(.data, "theme")
-- BOOK_HOME::plugins -> table
-- Represents the directory for the local LunarBook plugins
--
.plugins = join(.data, "plugins")
-- BOOK_HOME::configuration -> string
-- Represents the local configuration file of the book
--
.configuration = join(.data, "configuration.mprop")
-- ::BUILD_DIRS -> table
-- Represents the LunarBook build directories
-- export
export BUILD_DIRS = with {}
-- ::BUILD_DIRS::scheme -> string
--
--
.scheme = "build://"
-- BUILD_DIRS::assets -> string
--
--
.assets = .scheme.."assets"
-- BUILD_DIRS::fragments -> string
--
--
.fragments = .assets.."/fragments"
-- BUILD_DIRS::scripts -> string
--
--
.scripts = .assets.."/scripts"
-- BUILD_DIRS::styles -> string
--
--
.styles = .assets.."/styles"
| 24 | 74 | 0.621059 |
33e7989713860325ce3623939445cf4878599149 | 1,378 |
import render_html from require "lapis.html"
import label_wrap, float_wrap from require "luminary.util"
import sort, concat from table
format_query = (q) ->
render_html ->
span style: "font-family: Monaco, Menlo, Consolas, 'Courier New', monospace;", ->
span style: "color:magenta;font-weight:bold;", ->
text "SQL: "
span style: "color:navy;", ->
raw q
class DatabasePanel extends require "luminary.panels.base"
@title = "Database"
-- Nifty way to set the subtitle before rendering content
include_helper: (req, ...) =>
super req, ...
@subtitle = if req._luminary and req._luminary.queries
"#{#req._luminary.queries} queries"
else
"Error"
content: =>
-- luminary.capture_queries! must be called early in the app's request handling for queries to be captured
h1 ->
text "Queries"
if @_luminary
if @_luminary.queries
n=0
for i,q in ipairs @_luminary.queries
@_luminary.queries[i] = format_query q
n+=1
if n>0
@table_contents @_luminary.queries
else
pre ->
text "No queries captured"
else
pre ->
text "Query capture error!"
else
pre ->
"Unable to capture queries. Did you add `luminary.capture_queries!` to your @before_filter? Check your configuration."
| 28.122449 | 126 | 0.623367 |
b295ee5723ab7366d0e8e1d50904f01276970a99 | 964 | ----------------------------------------------------------------
-- Variable naming for ROBLOX objects.
--
-- @classmod VariableNamer
-- @author Richard Voelker
-- @license MIT
----------------------------------------------------------------
-- {{ TBSHTEMPLATE:BEGIN }}
class VariableNamer
new: =>
@_nameCount = {}
----------------------------------------------------------------
-- Get the next name for a ROBLOX object variable. The name is
-- in the following form: var(Object ClassName)(Unique ID).
--
-- @tparam VariableNamer self
-- @tparam string className The ClassName of the ROBLOX object.
-- @treturn string The name for the object variable.
----------------------------------------------------------------
NameObjectVariable: (className) =>
if @_nameCount[className]
@_nameCount[className] += 1
else
@_nameCount[className] = 1
return "obj#{className}#{@_nameCount[className]}"
-- {{ TBSHTEMPLATE:END }}
return VariableNamer
| 30.125 | 65 | 0.514523 |
82109846fa4ee409bede9bf028ef837397d15b93 | 3,304 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
Gtk = require 'ljglibs.gtk'
Window = Gtk.Window
import PropertyObject from howl.aux.moon
import theme from howl.ui
class Popup extends PropertyObject
comfort_zone: 10
new: (child, properties = {}) =>
error('Missing argument #1: child', 3) if not child
properties.default_height = 150 if not properties.default_height
properties.default_width = 150 if not properties.default_width
@window = Window Window.POPUP, properties
box = Gtk.Box Gtk.ORIENTATION_VERTICAL, {
{ expand: true, child }
}
@window\add box
theme.register_background_widget @window, 'popup'
@showing = false
super!
show: (widget, options = position: 'center') =>
error('Missing argument #1: widget', 2) if not widget
@window.transient_for = widget.toplevel
@window\realize!
@widget = widget
@showing = true
if options.x
@window.window_position = Gtk.WIN_POS_NONE
@move_to options.x, options.y
else
@center!
@window\show_all!
close: =>
@window\hide!
@showing = false
@widget = nil
move_to: (x, y) =>
error('Attempt to move a closed popup', 2) if not @showing
w_x, w_y = @widget.toplevel.window\get_position!
t_x, t_y = @widget\translate_coordinates(@widget.toplevel, x, y)
x = w_x + t_x
y = w_y + t_y
@x, @y = x, y
@window\move x, y
@resize @window.allocated_width, @window.allocated_height
resize: (width, height) =>
if not @showing
@window.default_width = width
@window.default_height = height
return
screen = @widget.screen
if @x + width > (screen.width - @comfort_zone)
width = screen.width - @x - @comfort_zone
if @y + height > (screen.height - @comfort_zone)
height = screen.height - @y - @comfort_zone
@width, @height = width, height
@window\set_size_request width, height
@window\resize width, height
center: =>
error('Attempt to center a closed popup', 2) if not @showing
height = @height
width = @width
-- now, if we were to center ourselves on the widgets toplevel,
-- with our current width and height..
screen = @widget.screen
toplevel = @widget.toplevel
w_x, w_y = toplevel.window\get_position!
w_width, w_height = toplevel.allocated_width, toplevel.allocated_height
win_h_center = w_x + (w_width / 2)
win_v_center = w_y + (w_height / 2)
x = win_h_center - (width / 2)
y = win_v_center - (height / 2)
-- are we outside of the comfort zone horizontally?
if x < @comfort_zone or x + width > (screen.width - @comfort_zone)
-- pull in the stomach
min_outside_h = math.min(w_x, screen.width - (w_x + w_width))
width = (w_width + min_outside_h) - @comfort_zone
x = win_h_center - (width / 2)
-- are we outside of the comfort zone vertically?
if y < @comfort_zone or y + heigth > (screen.height - @comfort_zone)
-- hunch down
min_outside_v = math.min(w_y, screen.height - (w_y + w_height))
height = (w_height + min_outside_v) - @comfort_zone
y = win_v_center - (height / 2)
-- now it's all good
@resize width, height
@window\move x, y
return Popup
| 29.765766 | 79 | 0.654358 |
79e4c531eb46dcb361d4319b18d9b629ba3cb20d | 11,306 | -- Auto-generated with ./create_everything.sh on 2014-04-04 23:27:36
-- We tell Moonscript to export classes globally. Thus, we prevent collisions
-- based on namespace since we don't know what is going to be used.
--
-- This provides two options for getting the class, calling require again and
-- assigning it to a local variable. Alternatively, the namespaced version can
-- be used.
import mixin_table from require "moon"
export LunoPunk
LunoPunk = LunoPunk or {}
LunoPunk.math = LunoPunk.math or {}
LunoPunk.debug = LunoPunk.debug or {}
LunoPunk.masks = LunoPunk.masks or {}
LunoPunk.tweens = LunoPunk.tweens or {}
LunoPunk.tweens.misc = LunoPunk.tweens.misc or {}
LunoPunk.tweens.sound = LunoPunk.tweens.sound or {}
LunoPunk.tweens.motion = LunoPunk.tweens.motion or {}
LunoPunk.graphics = LunoPunk.graphics or {}
LunoPunk.graphics.prototype = LunoPunk.graphics.prototype or {}
LunoPunk.graphics.atlas = LunoPunk.graphics.atlas or {}
LunoPunk.utils = LunoPunk.utils or {}
LunoPunk.utils.mixins = LunoPunk.utils.mixins or {}
LunoPunk.geometry = LunoPunk.geometry or {}
import extract_love_version, set_love_title from require "LunoPunk.Config"
extract_love_version love._version
set_love_title!
-- Now load each file to the correctly namespaced table
mixin_table LunoPunk.debug, if t = assert(require "LunoPunk.debug.Console") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.debug, if t = assert(require "LunoPunk.debug.LayerList") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.geometry, if t = assert(require "LunoPunk.geometry.Matrix") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.geometry, if t = assert(require "LunoPunk.geometry.Point") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.geometry, if t = assert(require "LunoPunk.geometry.Rectangle") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics.atlas, if t = assert(require "LunoPunk.graphics.atlas.AtlasData") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics.atlas, if t = assert(require "LunoPunk.graphics.atlas.AtlasRegion") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics.atlas, if t = assert(require "LunoPunk.graphics.atlas.Atlas") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics.atlas, if t = assert(require "LunoPunk.graphics.atlas.TextureAtlas") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics.atlas, if t = assert(require "LunoPunk.graphics.atlas.TileAtlas") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.Animation") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.Backdrop") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.Canvas") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.Emitter") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.Graphiclist") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.Image") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.Particle") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.ParticleType") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.PreRotation") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.Spritemap") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.Stamp") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.Text") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.TiledImage") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.TiledSpritemap") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics, if t = assert(require "LunoPunk.graphics.Tilemap") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics.prototype, if t = assert(require "LunoPunk.graphics.prototype.Circle") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.graphics.prototype, if t = assert(require "LunoPunk.graphics.prototype.Rect") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.Config") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.Engine") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.Entity") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.Graphic") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.LP") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.Mask") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.RenderMode") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.Scene") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.Screen") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.Sfx") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.Tweener") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.Tween") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk, if t = assert(require "LunoPunk.World") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.masks, if t = assert(require "LunoPunk.masks.Circle") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.masks, if t = assert(require "LunoPunk.masks.Grid") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.masks, if t = assert(require "LunoPunk.masks.Hitbox") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.masks, if t = assert(require "LunoPunk.masks.Imagemask") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.masks, if t = assert(require "LunoPunk.masks.Masklist") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.masks, if t = assert(require "LunoPunk.masks.Pixelmask") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.masks, if t = assert(require "LunoPunk.masks.Polygon") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.masks, if t = assert(require "LunoPunk.masks.SlopedGrid") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.math, if t = assert(require "LunoPunk.math.Projection") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.math, if t = assert(require "LunoPunk.math.Vector") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens, if t = assert(require "LunoPunk.tweens.TweenEvent") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.misc, if t = assert(require "LunoPunk.tweens.misc.Alarm") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.misc, if t = assert(require "LunoPunk.tweens.misc.AngleTween") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.misc, if t = assert(require "LunoPunk.tweens.misc.ColorTween") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.misc, if t = assert(require "LunoPunk.tweens.misc.MultiVarTween") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.misc, if t = assert(require "LunoPunk.tweens.misc.NumTween") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.misc, if t = assert(require "LunoPunk.tweens.misc.VarTween") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.motion, if t = assert(require "LunoPunk.tweens.motion.CircularMotion") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.motion, if t = assert(require "LunoPunk.tweens.motion.CubicMotion") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.motion, if t = assert(require "LunoPunk.tweens.motion.LinearMotion") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.motion, if t = assert(require "LunoPunk.tweens.motion.LinearPath") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.motion, if t = assert(require "LunoPunk.tweens.motion.Motion") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.motion, if t = assert(require "LunoPunk.tweens.motion.QuadMotion") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.motion, if t = assert(require "LunoPunk.tweens.motion.QuadPath") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.sound, if t = assert(require "LunoPunk.tweens.sound.Fader") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.tweens.sound, if t = assert(require "LunoPunk.tweens.sound.SfxFader") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.Color") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.Data") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.Draw") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.Ease") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.EventListener") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.Event") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.Input") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.Joystick") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.Key") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.List") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.Math") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.moonscript") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils, if t = assert(require "LunoPunk.utils.Touch") then t if type(t) == "table" else {} else {}
mixin_table LunoPunk.utils.mixins, if t = assert(require "LunoPunk.utils.mixins.clone") then t if type(t) == "table" else {} else {}
{ :LunoPunk }
| 98.313043 | 145 | 0.717849 |
9e3380dbae336a0132569e3d8e30f2d9aa53b3e6 | 429 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see README.md at the top-level directory of the bundle)
mode_reg =
name: 'mail-mode'
extensions: {'eml', 'mbox', 'mbx'}
create: -> bundle_load('mail_mode')!
howl.mode.register mode_reg
unload = -> howl.mode.unregister 'mail-mode'
return {
info:
author: 'Copyright 2015 The Howl Developers',
description: 'Mail mode',
license: 'MIT',
:unload
}
| 21.45 | 72 | 0.678322 |
0db6c7e0682071429c1f0eada0b050727d891519 | 1,513 | -- BlobReader example: parse binary data via Blob\unpack
-- This example shows how to use Blob\unpack to parse arbitrary binary files
-- run with luajit <path to moon> file.moon
package.moonpath = "#{package.moonpath};../?.moon"
BlobReader = require('BlobReader')
import format from string
file = assert(io.open('smile.png'))
blob = BlobReader(file\read('*all'))
file\close!
-- parse png header
magic1, magic2 = blob\unpack('>LL') -- PNG has big endian byte order
assert(magic1 == 0x89504e47, "Invalid PNG or damaged file")
assert(magic2 == 0x0d0a1a0a, "Invalid PNG or damaged file")
at_end = false
-- read chunks
while not at_end and blob\position! < blob\size! do
length, type = blob\unpack('Lc4')
switch type
when 'IHDR'
width, height, bpp = blob\unpack('LLBx4')
print("Image width: #{width} pixels")
print("Image height: #{height} pixels")
print("Bit depth: #{bpp} bpp")
when 'pHYs'
ppux, ppuy, units = blob\unpack('LLB')
print("#{ppux} pixels per unit, X axis")
print("#{ppuy} pixels per unit, Y axis")
print("Unit specifier: %s"\format(units == 1 and "meter" or "unknown"))
when 'iTXt'
data = blob\unpack("c#{length}")
sep = data\find('\0')
print(("%s: %s")\format(data\sub(1, sep - 1), data\sub(sep + 5)))
when 'IEND'
print("End of image marker")
at_end = true
else
print("Chunk type #{type}, data length #{length}")
blob\skip(length) -- skip chunk data
crc = blob\unpack('L')
print("Chunk CRC: 0x%x"\format(crc))
print(string.rep("-", 60))
| 32.191489 | 76 | 0.664243 |
317689ecfd6b97174e538e83524a510076bca461 | 489 | import Widget from require "lapis.html"
class extends Widget
content: =>
element "table", class: "pure-table", ->
for i in ipairs @messages
tr title: os.date("%c", tonumber(@messages[i].timestamp\sub(1, @messages[i].timestamp\find(".") - 1))), ->
if @show_channel
td @messages[i].channel_name
td @messages[i].user_name
td @messages[i].text
| 40.75 | 126 | 0.494888 |
3944a9c19de9b74a487ab465e6eac4d8b53e1102 | 1,053 |
import next, debug, string, setmetatable, rawget from _G
loadstring = loadstring or load
clone_function = if debug.upvaluejoin
(fn) ->
dumped = string.dump fn
cloned = loadstring(dumped)
i = 1
while true
name = debug.getupvalue(fn, i)
break unless name
debug.upvaluejoin(cloned, i, fn, i)
i += 1
cloned
else
(fn) ->
dumped = string.dump fn
cloned = loadstring(dumped)
i = 1
while true
name, val = debug.getupvalue(fn, i)
break unless name
debug.setupvalue(cloned, i, val)
i += 1
cloned
locks = setmetatable {}, {
__mode: "k"
__index: (name) =>
list = setmetatable {}, { __mode: "k" }
@[name] = list
list
}
locked_fn = (fn) ->
-- look for existing lock
list = locks[fn]
clone = next list
if clone
list[clone] = nil
clone
else
with c = clone_function fn
locks[c] = fn
release_fn = (fn) ->
list = locks[rawget locks, fn]
list[fn] = true
true
{ :clone_function, :locked_fn, :release_fn, _locks: locks }
| 17.847458 | 59 | 0.598291 |
ed3ddb52b7ba09f6711586f615038d7d5155f15b | 6,317 |
nginx = require "lapis.cmd.nginx"
describe "lapis.cmd.nginx", ->
it "should compile config", ->
tpl = [[
hello: ${{some_var}}]]
compiled = nginx.compile_config tpl, { some_var: "what's up" }
assert.same [[
env LAPIS_ENVIRONMENT;
hello: what's up]], compiled
it "should compile postgres connect string", ->
tpl = [[
pg-connect: ${{pg postgres}}]]
compiled = nginx.compile_config tpl, {
postgres: "postgres://pg_user:[email protected]/my_database"
}
assert.same [[
env LAPIS_ENVIRONMENT;
pg-connect: 127.0.0.1 dbname=my_database user=pg_user password=user_password]], compiled
it "should compile postgres connect table", ->
tpl = [[
pg-connect: ${{pg postgres}}]]
compiled = nginx.compile_config tpl, {
postgres: {
host: "example.com:1234"
user: "leafo"
password: "thepass"
database: "hello"
}
}
assert.same [[
env LAPIS_ENVIRONMENT;
pg-connect: example.com:1234 dbname=hello user=leafo password=thepass]], compiled
it "should read environment variable", ->
unless pcall -> require "posix"
pending "lposix is required for cmd.nginx specs"
return
posix = require "posix"
val = "hi there #{os.time!}"
posix.setenv "LAPIS_COOL", val
compiled = nginx.compile_config "thing: ${{cool}}"
assert.same "env LAPIS_ENVIRONMENT;\nthing: #{val}", compiled
it "should compile etlua config", ->
tpl = [[
hello: <%- some_var %>]]
compiled = nginx.compile_etlua_config tpl, { some_var: "what's up" }
assert.same [[
env LAPIS_ENVIRONMENT;
hello: what's up]], compiled
it "should read environment variable in etlua config", ->
unless pcall -> require "posix"
pending "lposix is required for cmd.nginx specs"
return
posix = require "posix"
val = "hi there #{os.time!}"
posix.setenv "LAPIS_COOL", val
compiled = nginx.compile_etlua_config "thing: <%- cool %>"
assert.same "env LAPIS_ENVIRONMENT;\nthing: #{val}", compiled
describe "lapis.cmd.actions", ->
import get_action, execute from require "lapis.cmd.actions"
it "gets built in action", ->
action = get_action "help"
assert.same "help", action.name
it "gets nil for invalid action", ->
action = get_action "wazzupf2323"
assert.same nil, action
it "gets action from module", ->
package.loaded["lapis.cmd.actions.cool"] = {
name: "cool"
->
}
action = get_action "cool"
assert.same "cool", action.name
it "executes help", ->
p = _G.print
_G.print = ->
execute {"help"}
_G.print = p
describe "lapis.cmd.actions.execute", ->
import join, shell_escape from require "lapis.cmd.path"
local cmd
local old_dir, new_dir, old_package_path
lfs = require "lfs"
before_each ->
cmd = require "lapis.cmd.actions"
-- replace the annotated path with silent one
cmd.actions.path = require "lapis.cmd.path"
old_dir = lfs.currentdir!
old_package_path = package.path
package.path ..= ";#{old_dir}/?.lua"
new_dir = join old_dir, "spec_tmp_app"
assert lfs.mkdir new_dir
assert lfs.chdir new_dir
after_each ->
package.path = old_package_path
assert lfs.chdir old_dir
os.execute "rm -r '#{shell_escape new_dir}'"
list_files = (dir, accum={}, prefix="") ->
for f in lfs.dir dir
continue if f\match "^%.*$"
relative_name = join prefix, f
if "directory" == lfs.attributes relative_name, "mode"
list_files join(dir, f), accum, relative_name
else
table.insert accum, relative_name
accum
assert_files = (files) ->
have_files = list_files lfs.currentdir!
table.sort files
table.sort have_files
assert.same files, have_files
describe "new", ->
it "default app", ->
cmd.execute { [0]: "lapis", "new" }
assert_files {
"app.moon", "mime.types", "models.moon", "nginx.conf"
}
it "cqueues app", ->
cmd.execute { [0]: "lapis", "new", "--cqueues" }
assert_files { "app.moon", "models.moon" }
it "etlua config", ->
cmd.execute { [0]: "lapis", "new", "--etlua-config" }
assert_files {
"app.moon", "mime.types", "models.moon", "nginx.conf.etlua"
}
it "command line flags can go anywhere", ->
cmd.execute { [0]: "lapis", "--etlua-config", "new" }
assert_files {
"app.moon", "mime.types", "models.moon", "nginx.conf.etlua"
}
it "lua default", ->
cmd.execute { [0]: "lapis", "new", "--lua" }
assert_files {
"app.lua", "mime.types", "models.lua", "nginx.conf"
}
it "has tup", ->
cmd.execute { [0]: "lapis", "new", "--tup" }
assert_files {
"app.moon", "mime.types", "models.moon", "nginx.conf", "Tupfile", "Tuprules.tup"
}
it "has git", ->
cmd.execute { [0]: "lapis", "new", "--git" }
assert_files {
"app.moon", "mime.types", "models.moon", "nginx.conf", ".gitignore"
}
describe "build", ->
it "buils app", ->
cmd.execute { [0]: "lapis", "new" }
cmd.execute { [0]: "lapis", "build" }
assert_files {
"app.moon", "mime.types", "models.moon", "nginx.conf", "nginx.conf.compiled"
}
describe "generate", ->
it "generates model", ->
cmd.execute { [0]: "lapis", "generate", "model", "things" }
assert_files { "models/things.moon" }
it "generates spec", ->
cmd.execute { [0]: "lapis", "generate", "spec", "models.things" }
assert_files { "spec/models/things_spec.moon" }
describe "lapis.cmd.util", ->
it "columnizes", ->
import columnize from require "lapis.cmd.util"
columnize {
{"hello", "here is some info"}
{"what is going on", "this is going to be a lot of text so it wraps around the end"}
{"this is something", "not so much here"}
{"else", "yeah yeah yeah not so much okay goodbye"}
}
it "parses flags", ->
import parse_flags from require "lapis.cmd.util"
flags, args = parse_flags { "hello", "--world", "-h=1", "yeah" }
assert.same {
h: "1"
world: true
}, flags
assert.same {
"hello"
"yeah"
}, args
flags, args = parse_flags { "new", "dad" }
assert.same {}, flags
assert.same {
"new"
"dad"
}, args
| 26.103306 | 90 | 0.600285 |
15142ace61bc4e3e16abeaef385a35e00239bde7 | 1,993 | ffi = require "ffi"
import BUFFER from require "ZF.img.buffer"
-- https://github.com/koreader/koreader-base/tree/master/ffi
class LIBJPG
new: (@filename = filename) => assert hasJPG, "libjpeg-turbo was not found"
read: =>
file = io.open @filename, "rb"
assert file, "Couldn't open JPG file"
@rawData = file\read "*a"
file\close!
setArguments: =>
@width = ffi.new "int[1]"
@height = ffi.new "int[1]"
@jpegSubsamp = ffi.new "int[1]"
@colorSpace = ffi.new "int[1]"
decode: (gray) =>
@read!
handle = JPG.tjInitDecompress!
assert handle, "no TurboJPEG API decompressor handle"
@setArguments!
JPG.tjDecompressHeader3 handle, ffi.cast("const unsigned char*", @rawData), #@rawData, @width, @height, @jpegSubsamp, @colorSpace
assert @width[0] > 0 and @height[0] > 0, "Image dimensions"
buffer = gray and BUFFER(@width[0], @height[0], 1) or BUFFER @width[0], @height[0], 4
format = gray and JPG.TJPF_GRAY or JPG.TJPF_RGB
err = JPG.tjDecompress2(handle, ffi.cast("unsigned char*", @rawData), #@rawData, ffi.cast("unsigned char*", buffer.data), @width[0], buffer.pitch, @height[0], format, 0) == -1
assert not err, "Decoding error"
JPG.tjDestroy handle
@rawData = buffer
@width = buffer\get_width!
@height = buffer\get_height!
@bit_depth = buffer\get_bpp!
@getPixel = (x, y) => buffer\get_pixel x, y
@getData = =>
@data = ffi.new "color_RGBA[?]", @width * @height
for y = 0, @height - 1
for x = 0, @width - 1
i = y * @width + x
with @getPixel(x, y)\get_color_32!
@data[i].r = .r
@data[i].g = .g
@data[i].b = .b
@data[i].a = .alpha
return @data
return @
{:LIBJPG} | 31.140625 | 183 | 0.531862 |
035bdfb86de9cad8f13edd8c85020505621873c1 | 1,986 | class Size extends Base
_readIndex: true
new: (arg0, arg1) =>
_type = typeof(arg0)
if _type is "number"
hasHeight = typeof(arg1) is "number"
@width = arg0
@height = (if hasHeight then arg1 else arg0)
@_read = (if hasHeight then 2 else 1) if @_read
else if arg0 is nil
@width = @height = 0
@_read = (if arg0 is null then 1 else 0) if @_read
else
if isArray(arg0)
@width = arg0[0]
@height = (if arg0.length > 1 then arg0[1] else arg0[0])
else if arg0.width?
@width = arg0.width
@height = arg0.height
else if arg0.x?
@width = arg0.x
@height = arg0.y
else
@width = @height = 0
@_read = 0 if @_read
@_read = 1 if @_read
set: (width, height) =>
@width = width
@height = height
equals: (size) =>
size is @ or size and (@width is size.width and @height is size.height or Array.isArray(size) and @width is size[0] and @height is size[1]) or false
clone: =>
Size(@width, @height)
add: (size) =>
size = Size\read(arg)
Size(@width + size.width, @height + size.height)
subtract: (size) =>
size = Size\read(arg)
Size(@width - size.width, @height - size.height)
multiply: (size) =>
size = Size\read(arg)
Size(@width * size.width, @height * size.height)
divide: (size) =>
size = Size\read(arg)
Size(@width / size.width, @height / size.height)
modulo: (size) =>
size = Size\read(arg)
Size(@width % size.width, @height % size.height)
negate: =>
Size(-@width, -@height)
isZero: =>
Numerical\isZero(@width) and Numerical\isZero(@height)
isNaN: =>
isNaN(@width) or isNaN(@height)
min: (size1, size2) =>
Size(math.min(size1.width, size2.width), math.min(size1.height, size2.height))
max: (size1, size2) =>
Size(math.max(size1.width, size2.width), math.max(size1.height, size2.height))
random: =>
Size(math.random(), math.random())
| 26.131579 | 152 | 0.58711 |
080597d5a48c74206a3ae67e95397adc16ec8972 | 2,451 |
--
-- 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.
net = DLib.net
net.pool('PPM2.RequestPonyData')
net.pool('PPM2.PlayerRespawn')
net.pool('PPM2.PlayerDeath')
net.pool('PPM2.PostPlayerDeath')
net.pool('PPM2.Require')
net.pool('PPM2.EditorStatus')
net.pool('PPM2.PonyDataRemove')
net.pool('PPM2.RagdollEdit')
net.pool('PPM2.RagdollEditFlex')
net.pool('PPM2.RagdollEditEmote')
net.pool('PPM2.EditorCamPos')
CreateConVar('ppm2_sv_draw_hands', '1', {FCVAR_NOTIFY, FCVAR_REPLICATED, FCVAR_ARCHIVE}, 'Should draw hooves as viewmodel')
CreateConVar('ppm2_sv_editor_dist', '0', {FCVAR_NOTIFY, FCVAR_REPLICATED, FCVAR_ARCHIVE}, 'Distance limit in PPM/2 Editor/2')
resource.AddWorkshop('933203381')
net.ReceiveAntispam('PPM2.EditorCamPos')
net.receive 'PPM2.EditorCamPos', (len = 0, ply = NULL) ->
return if not ply\IsValid()
return if ply.__ppm2_lcpt and ply.__ppm2_lcpt > RealTime()
ply.__ppm2_lcpt = RealTime() + 0.1
camPos, camAng = net.ReadVector(), net.ReadAngle()
filter = RecipientFilter()
filter\AddPVS(ply\GetPos())
filter\RemovePlayer(ply)
return if filter\GetCount() == 0
net.Start('PPM2.EditorCamPos', true)
net.WritePlayer(ply)
net.WriteVector(camPos)
net.WriteAngle(camAng)
net.Send(filter)
net.ReceiveAntispam('PPM2.EditorStatus')
net.Receive 'PPM2.EditorStatus', (len = 0, ply = NULL) ->
return if not IsValid(ply)
ply\SetNWBool('PPM2.InEditor', net.ReadBool())
| 38.296875 | 125 | 0.760098 |
642b66ff5f855371147d84c21fe3d41a140800e2 | 7,173 |
-- todo: splats in routes (*)
-- Cmt conditions on routes
-- pattern classes
-- :something[num] *[slug]
import insert from table
lpeg = require "lpeg"
import R, S, V, P from lpeg
import C, Cs, Ct, Cmt, Cg, Cb, Cc from lpeg
import encode_query_string from require "lapis.util"
reduce = (items, fn) ->
count = #items
error "reducing 0 item list" if count == 0
return items[1] if count == 1
left = fn items[1], items[2]
for i = 3, count
left = fn left, items[i]
left
route_precedence = (flags) ->
p = 0
if flags.var
p += 1
if flags.splat
p += 2
p
class RouteParser
new: =>
@grammar = @build_grammar!
-- returns an lpeg patternt that matches route, along with table of flags
parse: (route) =>
@grammar\match route
compile_exclude: (current_p, chunks, k=1) =>
local out
for {kind, value, val_params} in *chunks[k,]
switch kind
when "literal"
if out
out += value
else
out = value
break
when "optional"
p = route_precedence val_params
continue if current_p < p
if out
out += value
else
out = value
else
break
out
compile_chunks: (chunks, exclude=nil) =>
local patt
flags = {}
for i=#chunks,1,-1
chunk = chunks[i]
{kind, value, val_params} = chunk
flags[kind] = true
chunk_pattern = switch kind
when "splat"
inside = P 1
inside -= exclude if exclude
exclude = nil
Cg inside^1, "splat"
when "var"
char = val_params and @compile_character_class(val_params) or P 1
inside = char - "/"
inside -= exclude if exclude
exclude = nil
Cg inside^1, value
when "literal"
exclude = P value
P value
when "optional"
inner, inner_flags, inner_exclude = @compile_chunks value, exclude
for k,v in pairs inner_flags
flags[k] or= v
if inner_exclude
if exclude
exclude = inner_exclude + exclude
else
exclude = inner_exclude
inner^-1
else
error "unknown node: #{kind}"
patt = if patt
chunk_pattern * patt
else
chunk_pattern
patt, flags, exclude
-- convert character class, like %d to an lpeg pattern
compile_character_class: (chars) =>
@character_class_pattern or= Ct C("^")^-1 * C(
P"%" * S"adw" +
(C(1) * P"-" * C(1) / (a, b) -> "#{a}#{b}") +
1
)^1
negate = false
plain_chars = {}
patterns = for item in *@character_class_pattern\match chars
switch item
when "^"
negate = true
continue
when "%a"
R "az", "AZ"
when "%d"
R "09"
when "%w"
R "09", "az", "AZ"
else
if #item == 2
R item
else
table.insert plain_chars, item
continue
if next plain_chars
table.insert patterns, S table.concat plain_chars
local out
for p in *patterns
if out
out += p
else
out = p
if negate
out = 1 - out
out or P -1
build_grammar: =>
alpha = R("az", "AZ", "__")
alpha_num = alpha + R("09")
make_var = (str, char_class) -> { "var", str\sub(2), char_class }
make_splat = -> { "splat" }
make_lit = (str) -> { "literal", str }
make_optional = (children) -> { "optional", children }
splat = P"*"
var = P":" * alpha * alpha_num^0
var = C(var) * (P"[" * C((1 - P"]")^1) * P"]")^-1
@var = var
@splat = splat
chunk = var / make_var + splat / make_splat
chunk = (1 - chunk)^1 / make_lit + chunk
compile_chunks = @\compile_chunks
g = P {
"route"
optional_literal: (1 - P")" - V"chunk")^1 / make_lit
optional_route: Ct((V"chunk" + V"optional_literal")^1)
optional: P"(" * V"optional_route" * P")" / make_optional
literal: (1 - V"chunk")^1 / make_lit
chunk: var / make_var + splat / make_splat + V"optional"
route: Ct((V"chunk" + V"literal")^1)
}
g / @\compile_chunks / (p, f) -> Ct(p) * -1, f
class Router
new: =>
@routes = {}
@named_routes = {}
@parser = RouteParser!
add_route: (route, responder) =>
@p = nil
name = nil
if type(route) == "table"
name = next route
route = route[name]
-- keep existing route
unless @named_routes[name]
@named_routes[name] = route
insert @routes, { route, responder, name }
default_route: (route) =>
error "failed to find route: " .. route
build: =>
by_precedence = {}
for r in *@routes
pattern, flags = @build_route unpack r
p = route_precedence flags
by_precedence[p] or= {}
table.insert by_precedence[p], pattern
precedences = [k for k in pairs by_precedence]
table.sort precedences
@p = nil
for p in *precedences
for pattern in *by_precedence[p]
if @p
@p += pattern
else
@p = pattern
@p or= P -1
build_route: (path, responder, name) =>
pattern, flags = @parser\parse path
pattern = pattern / (params) ->
params, responder, path, name
pattern, flags
fill_path: (path, params={}, route_name) =>
local optional_stack
replace = (s) ->
param_name = s\sub 2
if val = params[param_name]
if "table" == type val
if get_key = val.url_key
val = get_key(val, route_name, param_name) or ""
else
obj_name = val.__class and val.__class.__name or type(val)
error "Don't know how to serialize object for url: #{obj_name}"
optional_stack.hits += 1 if optional_stack
val, true
else
optional_stack.misses += 1 if optional_stack
""
patt = Cs P {
"string"
replacement: @parser.var / replace +
@parser.splat / (-> replace ":splat") +
V"optional"
optional: Cmt("(", (_, k) ->
optional_stack = {
hits: 0
misses: 0
prev: optional_stack
}
true, ""
) * Cmt Cs((V"replacement" + 1 - ")")^0) * P")", (_, k, match) ->
result = optional_stack
optional_stack = optional_stack.prev
if result.hits > 0 and result.misses == 0
true, match
else
true, ""
string: (V"replacement" + 1)^0
}
patt\match path
url_for: (name, params, query) =>
return params unless name
path = assert @named_routes[name], "Missing route named #{name}"
path = @fill_path path, params, name
if query
if type(query) == "table"
query = encode_query_string query
if query != ""
path ..= "?" .. query
path
resolve: (route, ...) =>
@build! unless @p
params, responder, path, name = @p\match route
if params and responder
responder params, path, name, ...
else
@default_route route, params, path, name
{ :Router, :RouteParser }
| 22.843949 | 76 | 0.538269 |
a23acfb1f2936bb4b19b932bf653c631f29935f6 | 104 | lapis = require "lapis"
class extends lapis.Application
@include "api/v1"
"/": =>
"ayy lmao"
| 14.857143 | 31 | 0.615385 |
09231c33adb1b326c83d37368caf13e6d86e9c78 | 12,316 | LOADED_KEY = setmetatable {}, __tostring: => "::loaded_relations::"
assert_model = (primary_model, model_name) ->
with m = primary_model\get_relation_model model_name
error "failed to find model `#{model_name}` for relation" unless m
find_relation = (model, name) ->
return unless model
if rs = model.relations
for relation in *rs
if relation[1] == name
return relation
if p = model.__parent
find_relation p, name
preload_relation = (objects, name, ...) =>
preloader = @relation_preloaders[name]
unless preloader
error "Model #{@__name} doesn't have preloader for #{name}"
preloader @, objects, ...
true
preload_relations = (objects, name, ...) =>
preloader = @relation_preloaders[name]
unless preloader
error "Model #{@__name} doesn't have preloader for #{name}"
preloader @, objects
if ...
@preload_relations objects, ...
else
true
preload_homogeneous = (sub_relations, model, objects, front, ...) ->
import to_json from require "lapis.util"
return unless front
if type(front) == "table"
for key,val in pairs front
relation = type(key) == "string" and key or val
preload_relation model, objects, relation
if type(key) == "string"
r = find_relation model, key
unless r
error "missing relation: #{key}"
sub_relations or= {}
sub_relations[val] or= {}
loaded_objects = sub_relations[val]
if r.has_many or r.fetch and r.many
for obj in *objects
for fetched in *obj[key]
table.insert loaded_objects, fetched
else
for obj in *objects
table.insert loaded_objects, obj[key]
else
preload_relation model, objects, front
if ...
preload_homogeneous sub_relations, model, objects, ...
else
sub_relations
preload = (objects, ...) ->
-- group by type
by_type = {}
for object in *objects
cls = object.__class
unless cls
error "attempting to preload an object that doesn't have a class, are you sure it's a model?"
by_type[cls] or= {}
table.insert by_type[object.__class], object
local sub_relations
for model, model_objects in pairs by_type
sub_relations = preload_homogeneous sub_relations, model, model_objects, ...
if sub_relations
for sub_load, sub_objects in pairs sub_relations
preload sub_objects, sub_load
true
mark_loaded_relations = (items, name) ->
for item in *items
if loaded = item[LOADED_KEY]
loaded[name] = true
else
item[LOADED_KEY] = { [name]: true }
clear_loaded_relation = (item, name) ->
item[name] = nil
if loaded = item[LOADED_KEY]
loaded[name] = nil
true
relation_is_loaded = (item, name) ->
item[name] or item[LOADED_KEY] and item[LOADED_KEY][name]
get_relations_class = (model) ->
parent = model.__parent
unless parent
error "model does not have parent class"
if rawget parent, "_relations_class"
return parent
preloaders = {}
if inherited = parent.relation_preloaders
setmetatable preloaders, __index: inherited
relations_class = class extends model.__parent
@__name: "#{model.__name}Relations"
@_relations_class: true
@relation_preloaders: preloaders
@preload_relations: preload_relations
@preload_relation: preload_relation
clear_loaded_relation: clear_loaded_relation
model.__parent = relations_class
setmetatable model.__base, relations_class.__base
relations_class
fetch = (name, opts) =>
source = opts.fetch
assert type(source) == "function", "Expecting function for `fetch` relation"
get_method = opts.as or "get_#{name}"
@__base[get_method] = =>
existing = @[name]
loaded = @[LOADED_KEY]
return existing if existing != nil or loaded and loaded[name]
if loaded
loaded[name] = true
else
@[LOADED_KEY] = { [name]: true }
with obj = source @
@[name] = obj
if opts.preload
@relation_preloaders[name] = (objects, preload_opts) =>
mark_loaded_relations objects, name
opts.preload objects, preload_opts, @, name
belongs_to = (name, opts) =>
source = opts.belongs_to
assert type(source) == "string", "Expecting model name for `belongs_to` relation"
get_method = opts.as or "get_#{name}"
column_name = opts.key or "#{name}_id"
assert type(column_name) == "string",
"`belongs_to` relation doesn't support composite key, use `has_one` instead"
@__base[get_method] = =>
return nil unless @[column_name]
existing = @[name]
loaded = @[LOADED_KEY]
return existing if existing != nil or loaded and loaded[name]
if loaded
loaded[name] = true
else
@[LOADED_KEY] = { [name]: true }
model = assert_model @@, source
with obj = model\find @[column_name]
@[name] = obj
@relation_preloaders[name] = (objects, preload_opts) =>
model = assert_model @@, source
preload_opts or= {}
preload_opts.as = name
preload_opts.for_relation = name
model\include_in objects, column_name, preload_opts
has_one = (name, opts) =>
source = opts.has_one
model_name = @__name
assert type(source) == "string", "Expecting model name for `has_one` relation"
get_method = opts.as or "get_#{name}"
-- assert opts.local_key, "`has_one` relation `local_key` option deprecated for composite `key`"
@__base[get_method] = =>
existing = @[name]
loaded = @[LOADED_KEY]
return existing if existing != nil or loaded and loaded[name]
if loaded
loaded[name] = true
else
@[LOADED_KEY] = { [name]: true }
model = assert_model @@, source
clause = if type(opts.key) == "table"
out = {}
for k,v in pairs opts.key
key, local_key = if type(k) == "number"
v, v
else
k,v
out[key] = @[local_key] or @@db.NULL
out
else
local_key = opts.local_key
unless local_key
local_key, extra_key = @@primary_keys!
assert extra_key == nil, "Model #{model_name} has composite primary keys, you must specify column mapping directly with `key`"
{
[opts.key or "#{@@singular_name!}_id"]: @[local_key]
}
if where = opts.where
for k,v in pairs where
clause[k] = v
with obj = model\find clause
@[name] = obj
@relation_preloaders[name] = (objects, preload_opts) =>
model = assert_model @@, source
key = if type(opts.key) == "table"
opts.key
else
local_key = opts.local_key
unless local_key
local_key, extra_key = @@primary_keys!
assert extra_key == nil, "Model #{model_name} has composite primary keys, you must specify column mapping directly with `key`"
{
[opts.key or "#{@@singular_name!}_id"]: local_key
}
preload_opts or= {}
preload_opts.for_relation = name
preload_opts.as = name
preload_opts.where or= opts.where
model\include_in objects, key, preload_opts
has_many = (name, opts) =>
source = opts.has_many
assert type(source) == "string", "Expecting model name for `has_many` relation"
get_method = opts.as or "get_#{name}"
get_paginated_method = "#{get_method}_paginated"
build_query = (additional_opts) =>
foreign_key = opts.key or "#{@@singular_name!}_id"
clause = if type(foreign_key) == "table"
out = {}
for k,v in pairs foreign_key
key, local_key = if type(k) == "number"
v, v
else
k,v
out[key] = @[local_key] or @@db.NULL
out
else
{
[foreign_key]: @[opts.local_key or @@primary_keys!]
}
if where = opts.where
for k,v in pairs where
clause[k] = v
if additional_opts and additional_opts.where
for k,v in pairs additional_opts.where
clause[k] = v
clause = "where #{@@db.encode_clause clause}"
if order = additional_opts and additional_opts.order or opts.order
clause ..= " order by #{order}"
clause
@__base[get_method] = =>
existing = @[name]
loaded = @[LOADED_KEY]
return existing if existing != nil or loaded and loaded[name]
if loaded
loaded[name] = true
else
@[LOADED_KEY] = { [name]: true }
model = assert_model @@, source
with res = model\select build_query(@)
@[name] = res
unless opts.pager == false
@__base[get_paginated_method] = (fetch_opts) =>
model = assert_model @@, source
query_opts = if fetch_opts and (fetch_opts.where or fetch_opts.order)
-- ordered paginator can take order
order = unless fetch_opts.ordered
fetch_opts.order
{
where: fetch_opts.where
:order
}
model\paginated build_query(@, query_opts), fetch_opts
@relation_preloaders[name] = (objects, preload_opts) =>
model = assert_model @@, source
foreign_key = opts.key or "#{@@singular_name!}_id"
composite_key = type(foreign_key) == "table"
local_key = unless composite_key
opts.local_key or @@primary_keys!
preload_opts or= {}
unless composite_key
preload_opts.flip = true
preload_opts.many = true
preload_opts.for_relation = name
preload_opts.as = name
preload_opts.local_key = local_key
preload_opts.order or= opts.order
preload_opts.where or= opts.where
model\include_in objects, foreign_key, preload_opts
polymorphic_belongs_to = (name, opts) =>
import enum from require "lapis.db.model"
types = opts.polymorphic_belongs_to
assert type(types) == "table", "missing types"
type_col = "#{name}_type"
id_col = "#{name}_id"
enum_name = "#{name}_types"
model_for_type_method = "model_for_#{name}_type"
type_for_object_method = "#{name}_type_for_object"
type_for_model_method = "#{name}_type_for_model"
get_method = "get_#{name}"
@[enum_name] = enum { assert(v[1], "missing type name"), k for k,v in pairs types}
@relation_preloaders[name] = (objs, preload_opts) =>
fields = preload_opts and preload_opts.fields
for {type_name, model_name} in *types
model = assert_model @@, model_name
filtered = [o for o in *objs when o[type_col] == @@[enum_name][type_name]]
model\include_in filtered, id_col, {
for_relation: name
as: name
fields: fields and fields[type_name]
}
objs
-- TODO: deprecate this for the new `preload_relations` method
@["preload_#{name}s"] = @relation_preloaders[name]
@[model_for_type_method] = (t) =>
type_name = @[enum_name]\to_name t
for {t_name, t_model_name} in *types
if t_name == type_name
return assert_model @@, t_model_name
error "failed to model for type: #{type_name}"
@[type_for_object_method] = (o) =>
@[type_for_model_method] @, assert o.__class, "invalid object, missing class"
@[type_for_model_method] = (m) =>
assert m.__name, "missing class name for model"
model_name = m.__name
for i, {_, t_model_name} in ipairs types
if model_name == t_model_name
return i
error "failed to find type for model: #{model_name}"
@__base[get_method] = =>
existing = @[name]
loaded = @[LOADED_KEY]
return existing if existing != nil or loaded and loaded[name]
if loaded
loaded[name] = true
else
@[LOADED_KEY] = { [name]: true }
if t = @[type_col]
model = @@[model_for_type_method] @@, t
with obj = model\find @[id_col]
@[name] = obj
relation_builders = {
:fetch, :belongs_to, :has_one, :has_many, :polymorphic_belongs_to,
}
-- add_relations, Things, {
-- {"user", has_one: "Users"}
-- {"posts", has_many: "Posts", pager: true, order: "id ASC"}
-- }
add_relations = (relations) =>
cls = get_relations_class @
for relation in *relations
name = assert relation[1], "missing relation name"
built = false
for k in pairs relation
if builder = relation_builders[k]
builder cls, name, relation
built = true
break
continue if built
import flatten_params from require "lapis.logging"
error "don't know how to create relation `#{flatten_params relation}`"
{
:relation_builders, :find_relation, :clear_loaded_relation, :LOADED_KEY
:add_relations, :get_relations_class, :mark_loaded_relations, :relation_is_loaded
:preload
}
| 26.429185 | 134 | 0.649562 |
f14ea317c453b0055cb02b94b2ae7198d4c0cc40 | 1,141 | stringx = require "pl.stringx"
etlua = require "etlua"
fin = io.open "modes_temp2.go", "r"
export Replies
Replies = {}
export Errors
Errors = {}
line = ""
while line
line = fin\read "*l"
break unless line
if stringx.startswith line, "Rpl"
table.insert Replies, {stringx.split(line, " ")[4]\sub(2,4), stringx.split(line, " ")[1]}
else
table.insert Errors, {stringx.split(line, " ")[4]\sub(2,4), stringx.split(line, " ")[1]}
template = assert etlua.compile [[ // Generated by generate_check.moon on <%- os.date() %>
// DO NOT EDIT BY HAND
package numeric
/*
IsError checks the Response and returns true if it is an error and false if it is not.
*/
func (r Response) IsError() bool {
switch r {
case <% for i, item in pairs(replies) do %> "<%= item[1] -%>" <% if i ~= #replies then %>,<% end %> <% end %>:
return false
case <% for i, item in pairs(errors) do %> "<%= item[1] -%>" <% if i ~= #errors then %>,<% end %> <% end %>:
return true
default:
return false
}
}]]
fout = io.open "replies_iserror.go", "w"
fout\write template {
replies: Replies
errors: Errors
}
fout\close!
| 23.285714 | 114 | 0.611744 |
05891341caa1fb408d7bbe2ff29df8e54b24cb31 | 422 | M = {}
__ = ...
name1 = "module"
name2 = "import"
TK = require("PackageToolkit")
M.run = (msg="") ->
print TK.ui.dashed_line 80, '-'
print string.format "test %s.%s()", name1, name2
print msg
m = TK[name1][name2] __, "m/m2"
result = m.hello()
solution = "hello from m1"
print "Result: ", result
assert result == solution
print "VERIFIED!"
print TK.ui.dashed_line 80, '-'
return M
| 22.210526 | 52 | 0.582938 |
cc55c7a11d4f8e21d7736351baa3e9236d2ce21f | 1,440 | utility = require('shared.utility')
Page = require('settings.pages.page')
Settings = require('settings.types')
class Custom extends Page
new: () =>
super()
@title = LOCALIZATION\get('platform_name_custom', 'Custom')
@settings = {
Settings.Action({
title: LOCALIZATION\get('button_label_starting_bangs', 'Starting bangs')
tooltip: LOCALIZATION\get('setting_custom_starting_bangs_description', 'These Rainmeter bangs are executed just before any Custom game launches.')
label: LOCALIZATION\get('button_label_edit', 'Edit')
perform:() =>
path = 'cache\\bangs.txt'
bangs = COMPONENTS.SETTINGS\getCustomStartingBangs()
io.writeFile(path, table.concat(bangs, '\n'))
utility.runCommand(('""%s""')\format(io.joinPaths(STATE.PATHS.RESOURCES, path)), '', 'OnEditedCustomStartingBangs')
})
Settings.Action({
title: LOCALIZATION\get('button_label_stopping_bangs', 'Stopping bangs')
tooltip: LOCALIZATION\get('setting_custom_stopping_bangs_description', 'These Rainmeter bangs are executed just after any Custom game terminates.')
label: LOCALIZATION\get('button_label_edit', 'Edit')
perform:() =>
path = 'cache\\bangs.txt'
bangs = COMPONENTS.SETTINGS\getCustomStoppingBangs()
io.writeFile(path, table.concat(bangs, '\n'))
utility.runCommand(('""%s""')\format(io.joinPaths(STATE.PATHS.RESOURCES, path)), '', 'OnEditedCustomStoppingBangs')
})
}
return Custom
| 43.636364 | 151 | 0.715278 |
13c8892857539e9f9e017b3a52460a9118298f8d | 10,820 |
--
-- 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.
PPM2.ALLOW_TO_MODIFY_SCALE = CreateConVar('ppm2_sv_allow_resize', '1', {FCVAR_NOTIFY, FCVAR_REPLICATED}, 'Allow to resize ponies. Disables resizing completely (visual; mechanical)')
player_manager.AddValidModel('pony', 'models/ppm/player_default_base_new.mdl')
list.Set('PlayerOptionsModel', 'pony', 'models/ppm/player_default_base_new.mdl')
player_manager.AddValidModel('ponynj', 'models/ppm/player_default_base_new_nj.mdl')
list.Set('PlayerOptionsModel', 'ponynj', 'models/ppm/player_default_base_new_nj.mdl')
player_manager.AddValidModel('ponynj_old', 'models/ppm/player_default_base_nj.mdl')
list.Set('PlayerOptionsModel', 'ponynj_old', 'models/ppm/player_default_base_nj.mdl')
player_manager.AddValidModel('pony_old', 'models/ppm/player_default_base.mdl')
list.Set('PlayerOptionsModel', 'pony_old', 'models/ppm/player_default_base.mdl')
player_manager.AddValidModel('pony_cppm', 'models/cppm/player_default_base.mdl')
list.Set('PlayerOptionsModel', 'pony_cppm', 'models/cppm/player_default_base.mdl')
player_manager.AddValidModel('ponynj_cppm', 'models/cppm/player_default_base_nj.mdl')
list.Set('PlayerOptionsModel', 'ponynj_cppm', 'models/cppm/player_default_base_nj.mdl')
player_manager.AddValidHands(model, 'models/ppm/c_arms_pony.mdl', 0, '') for model in *{'pony', 'pony_cppm', 'ponynj', 'ponynj_cppm', 'pony_old'}
PPM2.MIN_WEIGHT = 0.7
PPM2.MAX_WEIGHT = 1.5
PPM2.MIN_SCALE = 0.5
PPM2.MAX_SCALE = 1.3
PPM2.PONY_HEIGHT_MODIFIER = 0.64
PPM2.PONY_HEIGHT_MODIFIER_DUCK = 1.12
PPM2.PONY_HEIGHT_MODIFIER_DUCK_HULL = 1
PPM2.MIN_NECK = 0.6
PPM2.MAX_NECK = 1.4
PPM2.MIN_LEGS = 0.6
PPM2.MAX_LEGS = 1.75
PPM2.MIN_SPINE = 0.8
PPM2.MAX_SPINE = 2
PPM2.PONY_JUMP_MODIFIER = 1.4
PPM2.PLAYER_VOFFSET = 64 * PPM2.PONY_HEIGHT_MODIFIER
PPM2.PLAYER_VOFFSET_DUCK = 28 * PPM2.PONY_HEIGHT_MODIFIER_DUCK
PPM2.PLAYER_VIEW_OFFSET = Vector(0, 0, PPM2.PLAYER_VOFFSET)
PPM2.PLAYER_VIEW_OFFSET_DUCK = Vector(0, 0, PPM2.PLAYER_VOFFSET_DUCK)
PPM2.PLAYER_VIEW_OFFSET_ORIGINAL = Vector(0, 0, 64)
PPM2.PLAYER_VIEW_OFFSET_DUCK_ORIGINAL = Vector(0, 0, 28)
PPM2.MIN_TAIL_SIZE = 0.6
PPM2.MAX_TAIL_SIZE = 1.7 -- i luv big tails
PPM2.MIN_IRIS = 0.4
PPM2.MAX_IRIS = 1.3
PPM2.MIN_HOLE = 0.1
PPM2.MAX_HOLE = .95
PPM2.MIN_HOLE_SHIFT = -0.5
PPM2.MAX_HOLE_SHIFT = 0.5
PPM2.MIN_PUPIL_SIZE = 0.2
PPM2.MAX_PUPIL_SIZE = 1
PPM2.MIN_EYE_ROTATION = -180
PPM2.MAX_EYE_ROTATION = 180
PPM2.HAND_BODYGROUP_ID = 0
PPM2.HAND_BODYGROUP_MAGIC = 0
PPM2.HAND_BODYGROUP_HOOVES = 1
PPM2.AvaliableTails = {
'MAILCALL'
'FLOOFEH'
'ADVENTUROUS'
'SHOWBOAT'
'ASSERTIVE'
'BOLD'
'STUMPY'
'SPEEDSTER'
'EDGY'
'RADICAL'
'BOOKWORM'
'BUMPKIN'
'POOFEH'
'CURLY'
'NONE'
}
PPM2.AvailableClothesHead = {
'EMPTY', 'APPLEJACK_HAT', 'BRAEBURN_HAT', 'TRIXIE_HAT', 'HEADPHONES'
}
PPM2.AvailableClothesNeck = {
'EMPTY', 'SCARF', 'TRIXIE_CAPE', 'TIE', 'BOWTIE'
}
PPM2.AvailableClothesBody = {
'EMPTY', 'VEST', 'SHIRT', 'HOODIE', 'WONDERBOLTS_BADGE'
}
PPM2.AvailableClothesEye = {
'EMPTY', 'GOGGLES_ROUND_FEMALE', 'GOGGLES_ROUND_MALE', 'SHADES_FEMALE', 'SHADES_MALE'
'MONOCLE_FEMALE', 'MONOCLE_MALE', 'EYEPATH_FEMALE', 'EYEPATH_MALE'
}
PPM2.MAX_CLOTHES_COLORS = 6
PPM2.MAX_CLOTHES_URLS = 4
PPM2.AvailableHorns = {
'EMPTY', 'CUSTOM', 'CLASSIC_SHARP', 'CLASSIC', 'BROKEN', 'LONG'
'LONG_CURLED', 'POISON_JOKE', 'CHANGELING'
'CHANGELING_QUEEN', 'KIRIN'
}
PPM2.AvaliableUpperManes = {
'MAILCALL', 'FLOOFEH', 'ADVENTUROUS', 'SHOWBOAT', 'ASSERTIVE'
'BOLD', 'STUMPY', 'SPEEDSTER', 'RADICAL', 'SPIKED'
'BOOKWORM', 'BUMPKIN', 'POOFEH', 'CURLY', 'INSTRUCTOR', 'NONE'
}
PPM2.AvaliableLowerManes = {
'MAILCALL', 'FLOOFEH', 'ADVENTUROUS', 'SHOWBOAT'
'ASSERTIVE', 'BOLD', 'STUMPY', 'HIPPIE', 'SPEEDSTER'
'BOOKWORM', 'BUMPKIN', 'CURLY', 'NONE'
}
PPM2.EyelashTypes = {
'Default', 'Double', 'Coy', 'Full', 'Mess', 'None'
}
PPM2.BodyDetails = {
'None', 'Leg gradient', 'Lines', 'Stripes', 'Head stripes'
'Freckles', 'Hooves big', 'Hooves small', 'Head layer'
'Hooves big rnd', 'Hooves small rnd', 'Spots 1', 'Robotic'
'DASH-E', 'Eye Scar', 'Eye Wound', 'Scars', 'MGS Socks'
'Sharp Hooves', 'Sharp Hooves 2', 'Muzzle', 'Eye Scar Left'
'Eye Scar Right'
'Albedo Printed Plate Skin'
'Paintable Printed Plate Skin'
'Albedo Printed Plate Strip'
'Paintable Printed Plate Strip'
'Cow Details'
'Deer Details'
'Extended Deer Details'
'Demonic'
'Ear Inner Detail'
'Zebra Details'
}
PPM2.BodyDetailsEnum = {
'NONE', 'GRADIENT', 'LINES', 'STRIPES', 'HSTRIPES'
'FRECKLES', 'HOOF_BIG', 'HOOF_SMALL', 'LAYER'
'HOOF_BIG_ROUND', 'HOOF_SMALL_ROUND', 'SPOTS', 'ROBOTIC'
'DASH_E', 'EYE_SCAR', 'EYE_WOUND', 'SCARS', 'MGS_SOCKS'
'SHARP_HOOVES', 'SHARP_HOOVES_2', 'MUZZLE', 'EYE_SCAR_LEFT'
'EYE_SCAR_RIGHT'
'ALBEDO_ANDROID'
'PAINT_ANDROID'
'ALBEDO_ANDROID_STRIP'
'PAINT_ANDROID_STRIP'
'COW'
'DEER'
'DEER_EXTENDED'
'DEMONIC'
'EAR_INNER'
'ZEBRA_DETAILS'
}
PPM2.SocksTypes = {
'DEFAULT'
'GEOMETRIC1'
'GEOMETRIC2'
'GEOMETRIC3'
'GEOMETRIC4'
'GEOMETRIC5'
'GEOMETRIC6'
'GEOMETRIC7'
'GEOMETRIC8'
'DARK1'
'FLOWERS10'
'FLOWERS11'
'FLOWERS12'
'FLOWERS13'
'FLOWERS14'
'FLOWERS15'
'FLOWERS16'
'FLOWERS17'
'FLOWERS18'
'FLOWERS19'
'FLOWERS2'
'FLOWERS20'
'FLOWERS3'
'FLOWERS4'
'FLOWERS5'
'FLOWERS6'
'FLOWERS7'
'FLOWERS8'
'FLOWERS9'
'GREY1'
'GREY2'
'GREY3'
'HEARTS1'
'HEARTS2'
'SNOW1'
'WALLPAPER1'
'WALLPAPER2'
'WALLPAPER3'
}
PPM2.AvaliableLightwarps = {
'SFM_PONY'
'AIRBRUSH'
'HARD_LIGHT'
'PURPLE_SKY'
'SPAWN'
'TF2'
'TF2_CINEMATIC'
'TF2_CLASSIC'
'WELL_OILED'
}
PPM2.MAX_LIGHTWARP = #PPM2.AvaliableLightwarps - 1
PPM2.AvaliableLightwarpsPaths = ['models/ppm2/lightwarps/' .. mat\lower() for _, mat in ipairs PPM2.AvaliableLightwarps]
PPM2.DefaultCutiemarks = {
'8ball', 'dice', 'magichat',
'magichat02', 'record', 'microphone',
'bits', 'checkered', 'lumps',
'mirror', 'camera', 'magnifier',
'padlock', 'binaryfile', 'floppydisk',
'cube', 'bulb', 'battery',
'deskfan', 'flames', 'alarm',
'myon', 'beer', 'berryglass',
'roadsign', 'greentree', 'seasons',
'palette', 'palette02', 'palette03',
'lightningstone', 'partiallycloudy', 'thunderstorm',
'storm', 'stoppedwatch', 'twistedclock',
'surfboard', 'surfboard02', 'star',
'ussr', 'vault', 'anarchy',
'suit', 'deathscythe', 'shoop',
'smiley', 'dawsome', 'weegee'
'applej', 'applem', 'bon_bon', 'carrots', 'celestia', 'cloudy', 'custom01', 'custom02', 'derpy', 'firezap',
'fluttershy', 'fruits', 'island', 'lyra', 'mine', 'note', 'octavia', 'pankk', 'pinkie_pie', 'rainbow_dash',
'rarity', 'rosen', 'sflowers', 'storm', 'time', 'time2', 'trixie', 'twilight', 'waters', 'weer', 'zecora'
}
PPM2.AvaliableUpperManesNew = {
'MAILCALL', 'FLOOFEH', 'ADVENTUROUS', 'SHOWBOAT', 'ASSERTIVE'
'BOLD', 'STUMPY', 'SPEEDSTER', 'RADICAL', 'SPIKED'
'BOOKWORM', 'BUMPKIN', 'POOFEH', 'CURLY', 'INSTRUCTOR'
'TIMID', 'FILLY', 'MECHANIC', 'MOON', 'CLOUD'
'DRUNK', 'EMO'
'NONE'
}
PPM2.AvaliableLowerManesNew = {
'MAILCALL', 'FLOOFEH', 'ADVENTUROUS', 'SHOWBOAT'
'ASSERTIVE', 'BOLD', 'STUMPY', 'HIPPIE', 'SPEEDSTER'
'BOOKWORM', 'BUMPKIN', 'CURLY'
'TIMID', 'MOON', 'BUN', 'CLOUD', 'EMO'
'NONE'
}
PPM2.AvaliableTailsNew = {
'MAILCALL', 'FLOOFEH', 'ADVENTUROUS', 'SHOWBOAT'
'ASSERTIVE', 'BOLD', 'STUMPY', 'SPEEDSTER', 'EDGY'
'RADICAL', 'BOOKWORM', 'BUMPKIN', 'POOFEH', 'CURLY'
'NONE'
}
PPM2.AvaliableEyeTypes = {
'DEFAULT', 'APERTURE'
}
PPM2.AvaliableEyeReflections = {
'DEFAULT', 'CRYSTAL_FOAL', 'CRYSTAL'
'FOAL', 'MALE'
}
PPM2.AvaliablePonyWings = {'DEFAULT', 'BATPONY'}
PPM2.AvaliablePonySuits = {'NONE', 'ROYAL_GUARD', 'SHADOWBOLTS_FULL', 'SHADOWBOLTS_LIGHT', 'WONDERBOLTS_FULL', 'WONDERBOLTS_LIGHT', 'SPIDERMANE_LIGHT', 'SPIDERMANE_FULL'}
do
i = -1
for _, mark in ipairs PPM2.DefaultCutiemarks
i += 1
PPM2["CMARK_#{mark\upper()}"] = i
PPM2.MIN_EYELASHES = 0
PPM2.MAX_EYELASHES = #PPM2.EyelashTypes - 1
PPM2.EYELASHES_NONE = #PPM2.EyelashTypes - 1
PPM2.MIN_TAILS = 0
PPM2.MAX_TAILS = #PPM2.AvaliableTails - 1
PPM2.MIN_TAILS_NEW = 0
PPM2.MAX_TAILS_NEW = #PPM2.AvaliableTailsNew - 1
PPM2.MIN_UPPER_MANES = 0
PPM2.MAX_UPPER_MANES = #PPM2.AvaliableUpperManes - 1
PPM2.MIN_LOWER_MANES = 0
PPM2.MAX_LOWER_MANES = #PPM2.AvaliableLowerManes - 1
PPM2.MIN_UPPER_MANES_NEW = 0
PPM2.MAX_UPPER_MANES_NEW = #PPM2.AvaliableUpperManesNew - 1
PPM2.MIN_LOWER_MANES_NEW = 0
PPM2.MAX_LOWER_MANES_NEW = #PPM2.AvaliableLowerManesNew - 1
PPM2.MIN_EYE_TYPE = 0
PPM2.MAX_EYE_TYPE = #PPM2.AvaliableEyeTypes - 1
PPM2.MIN_DETAIL = 0
PPM2.MAX_DETAIL = #PPM2.BodyDetails - 1
PPM2.MIN_CMARK = 0
PPM2.MAX_CMARK = #PPM2.DefaultCutiemarks - 1
PPM2.MIN_SUIT = 0
PPM2.MAX_SUIT = #PPM2.AvaliablePonySuits - 1
PPM2.MIN_WINGS = 0
PPM2.MAX_WINGS = #PPM2.AvaliablePonyWings - 1
PPM2.MIN_SOCKS = 0
PPM2.MAX_SOCKS = #PPM2.SocksTypes - 1
PPM2.GENDER_FEMALE = 0
PPM2.GENDER_MALE = 1
PPM2.MAX_BODY_DETAILS = 8
PPM2.RACE_EARTH = 0
PPM2.RACE_PEGASUS = 1
PPM2.RACE_UNICORN = 2
PPM2.RACE_ALICORN = 3
PPM2.RACE_ENUMS = {'EARTH', 'PEGASUS', 'UNICORN', 'ALICORN'}
PPM2.RACE_HAS_HORN = 0x1
PPM2.RACE_HAS_WINGS = 0x2
PPM2.AGE_FILLY = 0
PPM2.AGE_ADULT = 1
PPM2.AGE_MATURE = 2
PPM2.AGE_ENUMS = {'FILLY', 'ADULT', 'MATURE'}
PPM2.MIN_DERP_STRENGTH = 0.1
PPM2.MAX_DERP_STRENGTH = 1.3
PPM2.MIN_MALE_BUFF = 0
PPM2.DEFAULT_MALE_BUFF = 1
PPM2.MAX_MALE_BUFF = 2
PPM2.MAX_TATTOOS = 25
PPM2.TATTOOS_REGISTRY = {
'NONE', 'ARROW', 'BLADES', 'CROSS', 'DIAMONDINNER', 'DIAMONDOUTER'
'DRACO', 'EVILHEART', 'HEARTWAVE', 'JUNCTION', 'NOTE', 'NOTE2'
'TATTOO1', 'TATTOO2', 'TATTOO3', 'TATTOO4', 'TATTOO5', 'TATTOO6', 'TATTOO7'
'WING', 'HEART'
}
PPM2.MIN_TATTOOS = 0
PPM2.MAX_TATTOOS = #PPM2.TATTOOS_REGISTRY - 1
PPM2.MIN_WING = 0.1
PPM2.MIN_WINGX = -10
PPM2.MIN_WINGY = -10
PPM2.MIN_WINGZ = -10
PPM2.MAX_WING = 2
PPM2.MAX_WINGX = 10
PPM2.MAX_WINGY = 10
PPM2.MAX_WINGZ = 10
| 26.716049 | 181 | 0.721072 |
f002e6fdf8ebab985227d173b441ffcd0a73bb89 | 4,589 | -- Copyright 2016 Nils Nordman <[email protected]>
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
append = table.insert
builtin_whitelist_globals = {
'_G'
'_VERSION'
'assert'
'collectgarbage'
'dofile'
'error'
'getfenv'
'getmetatable'
'ipairs'
'load'
'loadfile'
'loadstring'
'module'
'next'
'pairs'
'pcall'
'print'
'rawequal'
'rawget'
'rawset'
'require'
'select'
'setfenv'
'setmetatable'
'tonumber'
'tostring'
'type'
'unpack'
'xpcall'
'coroutine'
'debug'
'io'
'math'
'os'
'package'
'string'
'table'
'true',
'false',
'nil'
}
config_for = (path) ->
has_moonscript = pcall require, 'moonscript'
look_for = { 'lint_config.lua' }
if has_moonscript
table.insert look_for, 1, 'lint_config.moon'
exists = (f) ->
fh = io.open f, 'r'
if fh
fh\close!
return true
false
dir = path\match('(.+)[/\\].+$') or path
while dir
for name in *look_for
config = "#{dir}/#{name}"
return config if exists(config)
dir = dir\match('(.+)[/\\].+$')
unless path\match('^/')
for name in *look_for
return name if exists(name)
nil
load_config_from = (config, file) ->
if type(config) == 'string' -- assume path to config
loader = loadfile
if config\match('.moon$')
loader = require("moonscript.base").loadfile
chunk = assert loader(config)
config = chunk! or {}
opts = {
report_loop_variables: config.report_loop_variables,
report_params: config.report_params
report_fndef_reassignments: config.report_fndef_reassignments
report_top_level_reassignments: config.report_top_level_reassignments
report_shadowing: config.report_shadowing
}
for list in *{
'whitelist_globals',
'whitelist_loop_variables',
'whitelist_params',
'whitelist_unused',
'whitelist_shadowing',
'whitelist_fndef_reassignments',
'whitelist_top_level_reassignments'
}
if config[list]
wl = {}
for k, v in pairs config[list]
if file\find(k)
for token in *v
append wl, token
opts[list] = wl
opts
whitelist = (...) ->
lists = {...}
unless #lists > 0
return -> false
wl = {}
patterns = {}
for list in *lists
for p in *list
if p\match '^%w+$'
append wl, p
else
append patterns, p
wl = {k, true for k in *wl}
(sym) ->
if wl[sym]
return true
for p in *patterns
if sym\match(p)
return true
false
evaluator = (opts = {}) ->
report_params = opts.report_params
report_params = false if report_params == nil
whitelist_params = whitelist opts.whitelist_params or {
'^_',
'%.%.%.'
}
report_loop_variables = opts.report_loop_variables
report_loop_variables = true if report_loop_variables == nil
whitelist_loop_variables = whitelist opts.whitelist_loop_variables or {
'^_',
'i',
'j'
}
report_shadowing = opts.report_shadowing
report_shadowing = true if report_shadowing == nil
builtin_whitelist_shadowing = whitelist { '%.%.%.', '_ENV' }
whitelist_shadowing = whitelist(opts.whitelist_shadowing) or builtin_whitelist_shadowing
report_fndef_reassignments = opts.report_fndef_reassignments
report_fndef_reassignments = true if report_fndef_reassignments == nil
whitelist_fndef_reassignments = whitelist(opts.whitelist_fndef_reassignments)
report_top_level_reassignments = opts.report_top_level_reassignments
report_top_level_reassignments = false if report_top_level_reassignments == nil
whitelist_top_level_reassignments = whitelist(opts.whitelist_top_level_reassignments)
whitelist_global_access = whitelist builtin_whitelist_globals, opts.whitelist_globals
whitelist_unused = whitelist {
'^_$',
'tostring',
'_ENV'
}, opts.whitelist_unused
{
allow_global_access: (p) ->
whitelist_global_access(p)
allow_unused_param: (p) ->
not report_params or whitelist_params(p)
allow_unused_loop_variable: (p) ->
not report_loop_variables or whitelist_loop_variables(p)
allow_unused: (p) ->
whitelist_unused(p)
allow_shadowing: (p) ->
not report_shadowing or (
whitelist_shadowing(p) or
builtin_whitelist_shadowing(p)
)
allow_fndef_reassignment: (p) ->
not report_fndef_reassignments or whitelist_fndef_reassignments(p)
allow_top_level_reassignment: (p) ->
not report_top_level_reassignments or whitelist_top_level_reassignments(p)
}
:config_for, :load_config_from, :evaluator
| 22.495098 | 90 | 0.671824 |
c112902122e33514aa0ff42c42354ce3117fae16 | 4,420 | db = require "lapis.db.cassandra"
import escape_literal, escape_identifier, config from db
import concat from table
import gen_index_name from require "lapis.db.base"
append_all = (t, ...) ->
for i=1, select "#", ...
t[#t + 1] = select i, ...
extract_options = (cols) ->
options = {}
cols = for col in *cols
if type(col) == "table" and col[1] != "raw"
for k,v in pairs col
options[k] = v
continue
col
cols, options
entity_exists = (name) ->
name = escape_literal name
cassandra_config = config().cassandra
columns, error, code = db.query "
SELECT * FROM \"system.schema_columns\" where
keyspace_name = #{cassandra_config.keyspace} AND columnfamily_name = #{name}
"
not error and #columns > 0
create_table = (name, columns, opts={}) ->
prefix = if opts.if_not_exists
"CREATE TABLE IF NOT EXISTS "
else
"CREATE TABLE "
buffer = {prefix, escape_identifier(name), " ("}
add = (...) -> append_all buffer, ...
-- Columns
for i, c in ipairs columns
add "\n "
if type(c) == "table"
name, kind = unpack c
add escape_identifier(name), " ", tostring kind
else
add c
add ",\n" unless i == #columns
-- Primary key(s)
if opts.primary_key
add ", \nPRIMARY KEY ("
if type(opts.primary_keys) == "table"
for i, c in ipairs opts.primary_key
add(c)
add ", " unless i == #opts.primary_key
else
add opts.primary_key
add ")"
add ")"
-- Table options
if opts.table_with
add "\nWITH "
i = 0
for n, c in pairs opts.primary_key
add "\nAND " unless i == 0
i += 1
add " #{n} = "
if type(c) == string
add "'#{c}'"
else
add(c)
add ";\n"
db.query concat buffer
drop_table = (tname) ->
cassandra_config = config().cassandra
escape_literal assert cassandra_config.keyspace
db.query "DROP TABLE #{escape_literal cassandra_config.keyspace}.#{escape_literal tname};"
create_index = (tname, ...) ->
index_name = gen_index_name tname, ...
column, options = extract_options {...}
buffer = {"CREATE"}
append_all buffer, " INDEX ", escape_identifier index_name
append_all buffer, " ON ", escape_identifier tname
append_all buffer, " (", escape_identifier(column), ")"
append_all buffer, ";"
db.query concat buffer
drop_index = (tname, ...) ->
index_name = gen_index_name tname, ...
tname = escape_identifier tname
db.query "DROP INDEX #{escape_identifier index_name};"
add_column = (tname, col_name, col_type) ->
tname = escape_identifier tname
col_name = escape_identifier col_name
db.query "ALTER TABLE #{tname} ADD #{col_name} #{col_type}"
drop_column = (tname, col_name) ->
tname = escape_identifier tname
col_name = escape_identifier col_name
db.query "ALTER TABLE #{tname} DROP COLUMN #{col_name};"
class ColumnType
default_options: { null: false }
new: (@base, @default_options) =>
__call: (length, opts={}) =>
out = @base
if type(length) == "table"
opts = length
length = nil
for k,v in pairs @default_options
opts[k] = v unless opts[k] != nil
if l = length or opts.length
out ..= "(#{l}"
if d = opts.decimals
out ..= ",#{d})"
else
out ..= ")"
-- -- type mods
-- if opts.unsigned
-- out ..= " UNSIGNED"
-- if opts.binary
-- out ..= " BINARY"
-- -- column mods
-- unless opts.null
-- out ..= " NOT NULL"
-- if opts.default != nil
-- out ..= " DEFAULT " .. escape_literal opts.default
-- if opts.auto_increment
-- out ..= " AUTO_INCREMENT"
-- if opts.unique
-- out ..= " UNIQUE"
if opts.primary_key
out ..= " PRIMARY KEY"
out
__tostring: => @__call {}
C = ColumnType
types = setmetatable {
id: C "uuid", primary_key: true
varchar: C "varchar"
char: C "ascii"
text: C "varchar"
blob: C "blob"
int: C "int"
integer: C "int"
bigint: C "bigint"
float: C "float"
double: C "double"
timestamp: C "timestamp"
boolean: C "boolean"
}, __index: (key) =>
error "Don't know column type `#{key}`"
{
:entity_exists
:gen_index_name
:types
:create_table
:drop_table
:create_index
:drop_index
:add_column
:drop_column
-- :rename_column
-- :rename_table
:ColumnType
}
| 22.436548 | 92 | 0.59638 |
dc322423ccf5e2ef62044085e01663652f851489 | 330 | import push, pop from require "lapis.environment"
import set_backend, init_logger from require "lapis.db.cassandra"
setup_db = (opts) ->
push "test", {
cassandra: {
host: "localhost"
keyspace: "lapis_test"
}
}
set_backend "cassandra"
init_logger!
teardown_db = ->
pop!
{:setup_db, :teardown_db}
| 16.5 | 65 | 0.663636 |
ebeaf3481001b09ad4c7c53a406558acf51d8e54 | 3,208 |
import setmetatable, getmetatable, tostring from _G
class DBRaw
raw = (val) -> setmetatable {tostring val}, DBRaw.__base
is_raw = (val) -> getmetatable(val) == DBRaw.__base
class DBList
list = (items) -> setmetatable {items}, DBList.__base
is_list = (val) -> getmetatable(val) == DBList.__base
unpack = unpack or table.unpack
-- is item a value we can insert into a query
is_encodable = (item) ->
switch type(item)
when "table"
switch getmetatable(item)
when DBList.__base, DBRaw.__base
true
else
false
when "function", "userdata", "nil"
false
else
true
TRUE = raw"TRUE"
FALSE = raw"FALSE"
NULL = raw"NULL"
import concat from table
import select from _G
format_date = (time) ->
os.date "!%Y-%m-%d %H:%M:%S", time
build_helpers = (escape_literal, escape_identifier) ->
append_all = (t, ...) ->
for i=1, select "#", ...
t[#t + 1] = select i, ...
flatten_set = (set) ->
escaped_items = [escape_literal item for item in set[2]]
assert escaped_items[1], "can't flatten empty set"
"(#{table.concat escaped_items, ", "})"
-- replace ? with values
interpolate_query = (query, ...) ->
values = {...}
i = 0
(query\gsub "%?", ->
i += 1
if values[i] == nil
error "missing replacement #{i} for interpolated query"
escape_literal values[i])
-- (col1, col2, col3) VALUES (val1, val2, val3)
encode_values = (t, buffer) ->
have_buffer = buffer
buffer or= {}
tuples = [{k,v} for k,v in pairs t]
cols = concat [escape_identifier pair[1] for pair in *tuples], ", "
vals = concat [escape_literal pair[2] for pair in *tuples], ", "
append_all buffer, "(", cols, ") VALUES (", vals, ")"
concat buffer unless have_buffer
-- col1 = val1, col2 = val2, col3 = val3
encode_assigns = (t, buffer) ->
join = ", "
have_buffer = buffer
buffer or= {}
for k,v in pairs t
append_all buffer, escape_identifier(k), " = ", escape_literal(v), join
buffer[#buffer] = nil
concat buffer unless have_buffer
-- { hello: "world", cat: db.NULL" } -> "hello" = 'world' AND "cat" IS NULL
encode_clause = (t, buffer) ->
join = " AND "
have_buffer = buffer
buffer or= {}
for k,v in pairs t
if v == NULL
append_all buffer, escape_identifier(k), " IS NULL", join
else
op = is_list(v) and " IN " or " = "
append_all buffer, escape_identifier(k), op, escape_literal(v), join
buffer[#buffer] = nil
concat buffer unless have_buffer
interpolate_query, encode_values, encode_assigns, encode_clause
gen_index_name = (...) ->
-- pass index_name: "hello_world" to override generated index name
count = select "#", ...
last_arg = select count, ...
if type(last_arg) == "table" and not is_raw(last_arg)
return last_arg.index_name if last_arg.index_name
parts = for p in *{...}
if is_raw p
p[1]\gsub("[^%w]+$", "")\gsub("[^%w]+", "_")
elseif type(p) == "string"
p
else
continue
concat(parts, "_") .. "_idx"
{
:NULL, :TRUE, :FALSE, :raw, :is_raw, :list, :is_list, :is_encodable, :format_date, :build_helpers, :gen_index_name
}
| 25.870968 | 116 | 0.608791 |
257b43d83b1dfdc2e30ab82426d014558453b739 | 748 |
import P, R, S from require "lpeg"
cont = R("\128\191")
multibyte_character = R("\194\223") * cont +
R("\224\239") * cont * cont +
R("\240\244") * cont * cont * cont
-- This is generated by web_sanitize and copied here for convenience, includes
-- all codepoints classified as whitespace compiled into optimal pattern
whitespace = S("\13\32\10\11\12\9") +
P("\239\187\191") +
P("\194") * S("\133\160") +
P("\225") * (P("\154\128") + P("\160\142")) +
P("\226") * (P("\128") * S("\131\135\139\128\132\136\140\175\129\133\168\141\130\134\169\138\137") + P("\129") * S("\159\160")) +
P("\227\128\128")
printable_character = S("\r\n\t") + R("\032\126") + multibyte_character
{:multibyte_character, :printable_character, :whitespace}
| 35.619048 | 131 | 0.618984 |
8bc181e427fb7d0a95172a1efbe266e6dac200f9 | 212 | listRange = zb2rhjxuHU526qygFxwLhELViAAatjAkatg7roSjCxLf21NLs
from => til => fn =>
(gen kv => end =>
kvs = (listRange from til h => (kv (nts (sub h from)) (fn h)) end)
(kv "length" (sub til from) kvs))
| 35.333333 | 70 | 0.636792 |
0041a9661db80581b4dd4e2bde329ba769b0ce47 | 49 | class Logger
info: (string) ->
return Logger | 12.25 | 21 | 0.673469 |
5e6a170d921af6b6df7e42f3b9c9d7e544ad9ca3 | 6,627 |
toArr = (aTable) ->
myArray = {}
for i,tbl in ipairs(aTable) do
nbKeys = 0
for k,v in pairs(tbl) do
nbKeys+=1
myArray[#myArray+1]=v
if(nbKeys==0) then
myArray[#myArray+1]="_null_"
for i,v in ipairs(myArray) do --quick fix for the nil value issue in table
if(v=="_null_") then myArray[i]=nil
return myArray
unpackArrValues = (aTable)->
return unpack toArr(aTable)
trim=(str)->
begin = str\match"^%s*()"
return begin > #str and "" or str\match(".*%S", begin)
--Check if a fullString begin with a startString
cmpStartsString=(fullString,startString)->
return string.sub(fullString,1,string.len(startString))==startString
clearTable = (t)->
for i=0, #t do t[i]=nil
dump = (...)->
if(type(...)=="nil") then
print "nil"
return
-- A reasonably bullet-proof table dumper that writes out in Moon syntax;
-- can limit the number of items dumped out, and cycles are detected.
-- No attempt at doing pretty indentation here, but it does try to produce
-- 'nice' looking output by separating the hash and the array part.
--
-- dump = require 'moondump'
-- ...
-- print dump t -- default, limit 1000, respect tostring
-- print dump t, limit:10000,raw:true -- ignore tostring
--
quote = (v) ->
if type(v) == 'string'
'%q'\format(v)
else
tostring(v)
--- return a string representation of a Lua value.
-- Cycles are detected, and a limit on number of items can be imposed.
-- @param t the table
-- @param options
-- limit on items, default 1000
-- raw ignore tostring
-- @return a string
dumpString = (t,options) ->
options = options or {}
limit = options.limit or 1000
buff = tables:{[t]:true}
k,tbuff = 1,nil
put = (v) ->
buff[k] = v
k += 1
put_value = (value) ->
if type(value) ~= 'table'
put quote value
if limit and k > limit
buff[k] = "..."
error "buffer overrun"
else
if not buff.tables[value] -- cycle detection!
buff.tables[value] = true
tbuff value
else
put "<cycle>"
put ','
tbuff = (t) ->
mt = getmetatable t unless options.raw
if type(t) ~= 'table' or mt and mt.__tostring
put quote t
else
put '{'
indices = #t > 0 and {i,true for i = 1,#t}
for key,value in pairs t -- first do the hash part
if indices and indices[key] then continue
if type(key) ~= 'string' then
key = '['..tostring(key)..']'
elseif key\match '%s'
key = quote key
put key..':'
put_value value
if indices -- then bang out the array part
for v in *t
put_value v
if buff[k - 1] == "," then k -= 1
put '}'
-- we pcall because that's the easiest way to bail out if there's an overrun.
pcall tbuff,t
table.concat(buff)
--return dumpString(...)
return dumpString(...,limit:40000,raw:true)
dumpPrint = (...)->
print dump(...)
dumpFile = (filename, content)->
file = io.open(filename, "w+")
file\write(content)
io.close(file)
prettyPrint = (...)->
--This module adds two functions to the `debug` module. While it may seem a
--little unorthodox, this after-the-fact modification of the existing lua
--standard libraries is because it is common that, when a project is ready for
--release, one adds `export debug = nil` to the beginning of the project, so
--that any lingering debug code that is slowing your application down is
--caught with error messages in the final stage of testing.
--Generally, `print` statements are also removed in this same stage, to
--prevent pollution of the console and because stringification of objects
--sometimes has a significant processor overhead. Consequently, it seems
--natural to put the debug printing function in the `debug` library, so that
--all unwanted testing code can be removed with one line.
--
--This module introduces two functions, `debug.write` and `debug.print`, which
--are analogous to the built-in `io.write` and `print` functions, except that
--they handle tables correctly.
--To prevent cycles from being printed, a simple rule is used that every table
--is only printed once in a given invocation of `debug.print` or
--`debug.write`. Even if there are no cycles, and the table structure just
--contains non-tree-like references, it will still print each table only once.
--Every key-value pair is printed on a separate line, so, although always
--remaining fairly readable, the output can get rather large fairly quickly.
ilevel = 0
indent = (a, b)->
steps, fn = if b
a, b
else
1, a
ilevel += steps
fn!
ilevel -= steps
writeindent = -> io.write " "\rep ilevel
debug.write = =>
visited = {}
_write = =>
if type(self) == 'table' and not visited[self]
if not (@@ and @@__name and not @__tostring)
visited[self] = true
print "{"
for k, v in pairs self
indent ->
writeindent!
_write k
io.write ': '
_write v
print!
writeindent!
_write "}"
elseif @__tostring
io.write @__tostring!
else
io.write @@__name
else
io.write tostring self
_write self
debug.print = (...)->
remaining = #{...}
for arg in *{...}
remaining -= 1
debug.write arg
io.write ', ' unless remaining == 0
print!
debug.print(...)
split = (str, sep)->
sep, fields = sep or ":", {}
pattern = string.format("([^%s]+)", sep)
str\gsub(pattern, ((c) -> fields[#fields+1] = c))
return fields
lenTbl = (t)->
i=0
for _ in pairs(t) do
i+=1
return i
getTimeStamp = ()->
if _G.socket ~= nil then
microSecs = _G.socket.gettime()*1000000
--print "genTS: "..microSecs
return microSecs
else
print "ERROR: TIMESTAMP SOCKET"
{:toArr, :cmpStartsString, :prettyPrint, :dumpPrint, :dump, :unpackArrValues,
:clearTable, :trim, :dumpFile, :split, :lenTbl, :getTimeStamp}
| 32.326829 | 83 | 0.564358 |
15e160fe086aec45214c47d11a502cbfe0ec8d35 | 390 | import java from smaug
TimeUtils = java.require "com.badlogic.gdx.utils.TimeUtils"
Gdx = java.require "com.badlogic.gdx.Gdx"
Thread = java.require "java.lang.Thread"
get_delta = ->
Gdx.graphics\getDeltaTime!
get_fps = ->
Gdx.graphics\getFramesPerSecond!
get_time = ->
TimeUtils\millis!
sleep = (ms) ->
Thread\sleep ms
{
:get_delta
:get_fps
:get_time
:sleep
}
| 15.6 | 59 | 0.689744 |
07e78a42a395fce4a55022fa70571114c0926cf9 | 635 | require "test"
test class VectorTest
zero_test: ->
v = Vector!
assert v.x == 0
assert v.y == 0
assert v.a == 0
assign_test: ->
v = Vector!
v.x = 1
v.y = 2
v.a = 3
assert v.x == 1
assert v.y == 2
assert v.a == 3
initialize_test: ->
v = Vector 4, 5, 6
assert v.x == 4
assert v.y == 5
assert v.a == 6
is_zero_test: ->
v = Vector!
assert v\is_zero!
is_not_zero_test: ->
v = Vector 1, 0, 0
assert not v\is_zero!
v = Vector 0, 1, 0
assert not v\is_zero!
v = Vector 0, 0, 1
assert not v\is_zero!
stop_test: ->
v = Vector 1, 2, 3
assert not v\is_zero!
v\stop!
assert v\is_zero! | 15.487805 | 23 | 0.573228 |
9c4ae40ec1e2040b3fde84c48e8c81da5f6218ea | 3,211 |
TEST_ENV = "test"
import normalize_headers from require "lapis.spec.request"
ltn12 = require "ltn12"
json = require "cjson"
import parse_query_string, encode_query_string from require "lapis.util"
class SpecServer
current_server: nil
new: (@runner) =>
unless @runner
import actions from require("lapis.cmd.actions")
@runner = switch actions\get_server_type!
when "cqueues"
require("lapis.cmd.cqueues").runner
else
require("lapis.cmd.nginx").nginx_runner
load_test_server: (overrides) =>
import get_free_port from require "lapis.cmd.util"
app_port = get_free_port!
more_config = { port: app_port }
if overrides
for k,v in pairs overrides
more_config[k] = v
@current_server = @runner\attach_server TEST_ENV, more_config
@current_server.app_port = app_port
@current_server
close_test_server: =>
@runner\detach_server!
@current_server = nil
get_current_server: =>
@current_server
-- hits the server in test environment
request: (path="", opts={}) =>
unless @current_server
error "The test server is not loaded! (did you forget to load_test_server?)"
http = require "socket.http"
headers = {}
method = opts.method
port = opts.port or @current_server.app_port
source = if data = opts.post or opts.data
method or= "POST" if opts.post
if type(data) == "table"
headers["Content-type"] = "application/x-www-form-urlencoded"
data = encode_query_string data
headers["Content-length"] = #data
ltn12.source.string(data)
-- if the path is a url then extract host and path
url_host, url_path = path\match "^https?://([^/]+)(.*)$"
if url_host
headers.Host = url_host
path = url_path
if override_port = url_host\match ":(%d+)$"
port = override_port
path = path\gsub "^/", ""
-- merge get parameters
if opts.get
_, url_query = path\match "^(.-)%?(.*)$"
get_params = if url_query
parse_query_string url_query
else
{}
for k,v in pairs opts.get
get_params[k] = v
path = path\gsub("^.-(%?.*)$", "") .. "?" .. encode_query_string get_params
if opts.headers
for k,v in pairs opts.headers
headers[k] = v
buffer = {}
res, status, headers = http.request {
url: "http://127.0.0.1:#{port}/#{path}"
redirect: false
sink: ltn12.sink.table buffer
:headers, :method, :source
}
assert res, status
body = table.concat buffer
headers = normalize_headers headers
if error_blob = headers.x_lapis_error
json = require "cjson"
{:summary, :err, :trace} = json.decode error_blob
error "\n#{summary}\n#{err}\n#{trace}"
if opts.expect == "json"
json = require "cjson"
unless pcall -> body = json.decode body
error "expected to get json from #{path}"
status, body, headers
default_server = SpecServer!
{
:SpecServer
load_test_server: default_server\load_test_server
close_test_server: default_server\close_test_server
get_current_server: default_server\get_current_server
request: default_server\request
}
| 25.688 | 82 | 0.64279 |
adfdb6bc8070bbee32ce4a0185148e3d100439cf | 1,913 | class HoverTime extends BarAccent
rightMargin = settings['hover-time-right-margin']
leftMargin = settings['hover-time-left-margin']
bottomMargin = settings['hover-time-bottom-margin']
offScreenPos = settings['hover-time-offscreen-pos']
new: =>
super!
@line = {
[[{%s%s\pos(]]\format settings['default-style'], settings['hover-time-style']
[[-100,0]]
[[)\an2}]]
[[????]]
}
@lastTime = 0
@lastX = -1
@position = offScreenPos
@animation = Animation offScreenPos, bottomMargin, @animationDuration, @\animate, nil, 0.5
reconfigure: =>
super!
rightMargin = settings['hover-time-right-margin']
leftMargin = settings['hover-time-left-margin']
bottomMargin = settings['hover-time-bottom-margin']
offScreenPos = settings['hover-time-offscreen-pos']
@line[2] = ('%g,%g')\format math.min( Window.w - rightMargin, math.max( leftMargin, Mouse.x ) ), @position
@line[1] = ([[{%s%s\pos(]])\format settings['default-style'], settings['hover-time-style']
@animation = Animation offScreenPos, bottomMargin, @animationDuration, @\animate, nil, 0.5
resize: =>
super!
@line[2] = ("%g,%g")\format math.min( Window.w - rightMargin, math.max( leftMargin, Mouse.x ) ), @yPos - @animation.value
animate: ( value ) =>
@position = @yPos - value
@line[2] = ("%g,%g")\format math.min( Window.w - rightMargin, math.max( leftMargin, Mouse.x ) ), @position
@needsUpdate = true
redraw: =>
if @active
super!
if Mouse.x != @lastX
@line[2] = ("%g,%g")\format math.min( Window.w - rightMargin, math.max( leftMargin, Mouse.x ) ), @position
@lastX = Mouse.x
hoverTime = mp.get_property_number( 'duration', 0 )*Mouse.x/Window.w
if hoverTime != @lastTime
@line[4] = ([[%d:%02d:%02d]])\format math.floor( hoverTime/3600 ), math.floor( (hoverTime/60)%60 ), math.floor( hoverTime%60 )
@lastTime = hoverTime
@needsUpdate = true
return @needsUpdate
| 33.561404 | 131 | 0.656038 |
14ec3d5f2dc762e999cae2d1d02b74b67b08e9e3 | 352 | #!/usr/bin/env moon
-- vim: ts=2 sw=2 et :
package.moonpath = '../src/?.moon;' .. package.moonpath
import cli from require "fun"
import Num from require "num"
eg={}
eg.num = ->
n=Num!
for i=1,1
n\adds {9,2, 5, 4, 12, 7, 8, 11, 9, 3,
7, 4, 12, 5, 4, 10, 9, 6,9,4}
assert 3.06 < n.sd and n.sd < 3.061
assert 7 == n.mu
cli eg
| 19.555556 | 55 | 0.539773 |
daf7ad28ec4048da1f1fa54b5873739ab8988c4a | 187 | -- Random
-- This plugin picks a random server to proxy to
M = {}
M.balance = (request, session, param) ->
return session['servers'][ math.random( #session['servers'] ) ]
return M
| 18.7 | 67 | 0.652406 |
3ca318a080d2ccb85562e925b95fbbf95dcdf784 | 106 | export modinfo = {
type: "function"
id: "Invoke"
func: (self, name, ...) ->
self[name](self, ...)
}
| 13.25 | 27 | 0.537736 |
bb59ad9c6295ec0957ce37d9c5d2b01193c8b678 | 161 |
db = require "lapis.db"
db = require "lapis.db"
import Model, enum from require "lapis.db.model"
class Keys extends Model
@table_name: => "keys2"
{:Keys}
| 13.416667 | 48 | 0.68323 |
6fca7b10fd32e486a3266ce5bcb3bf7fcf2674e0 | 3,882 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
Cursor = require 'aullar.cursor'
View = require 'aullar.view'
Selection = require 'aullar.selection'
Buffer = require 'aullar.buffer'
Gtk = require 'ljglibs.gtk'
describe 'Cursor', ->
local view, buffer, cursor, selection
before_each ->
buffer = Buffer ''
view = View buffer
cursor = view.cursor
selection = view.selection
window = Gtk.OffscreenWindow default_width: 800, default_height: 640
window\add view\to_gobject!
window\show_all!
pump_mainloop!
describe '.style', ->
it 'is "line" by default', ->
assert.equal 'line', cursor.style
it 'raises an error if set to anything else than "block" or "line"', ->
cursor.style = 'block'
cursor.style = 'line'
assert.raises 'foo', -> cursor.style = 'foo'
describe 'forward()', ->
it 'moves the cursor one character forward', ->
buffer.text = 'åäö'
cursor.pos = 1
cursor\forward!
assert.equals 3, cursor.pos -- 'å' is two bytes
it 'handles forwarding over the eof correctly', ->
buffer.text = 'x\n'
cursor.pos = 2
cursor\forward!
assert.equals 3, cursor.pos
cursor\forward!
assert.equals 3, cursor.pos
buffer.text = 'x'
cursor.pos = 1
cursor\forward!
assert.equals 2, cursor.pos
cursor\forward!
assert.equals 2, cursor.pos
it 'moves to the next line if needed', ->
buffer.text = 'å\nnext'
cursor.pos = 1
cursor\forward!
cursor\forward!
assert.equals 2, cursor.line
describe 'backward()', ->
it 'moves the cursor one character backwards', ->
buffer.text = 'åäö'
cursor.pos = 5 -- at 'ö'
cursor\backward!
assert.equals 3, cursor.pos
describe 'up()', ->
it 'moves the cursor one line up', ->
buffer.text = 'line 1\nline 2'
cursor.pos = 8
cursor\up!
assert.equals 1, cursor.line
it 'does nothing if the cursor is at the first line', ->
buffer.text = 'line 1\nline 2'
cursor.pos = 1
cursor\up!
assert.equals 1, cursor.pos
it 'respects the remembered column', ->
buffer.text = '12345\n12\n1234'
cursor.line = 3
cursor.column = 4
cursor\remember_column!
cursor\up!
assert.equal 2, cursor.line
assert.equal 3, cursor.column
cursor\up!
assert.equal 1, cursor.line
assert.equal 4, cursor.column
describe 'down()', ->
it 'moves the cursor one line down', ->
buffer.text = 'line 1\nline 2'
cursor.pos = 1
cursor\down!
assert.equals 2, cursor.line
it 'does nothing if the cursor is at the last line', ->
buffer.text = 'line 1\nline 2'
cursor.pos = 8
cursor\down!
assert.equals 8, cursor.pos
it 'respects the remembered column', ->
buffer.text = '12345\n12\n1234'
cursor.pos = 4
cursor\remember_column!
cursor\down!
assert.equal 2, cursor.line
assert.equal 3, cursor.column
cursor\down!
assert.equal 3, cursor.line
assert.equal 4, cursor.column
describe 'when the selection is marked as persistent', ->
it 'is updated as part of cursor movement', ->
buffer.text = '12345678'
cursor.pos = 4
selection\set 2, 4
selection.persistent = true
cursor\forward!
assert.equal 5, selection.end_pos
cursor.pos = 1
assert.equal 1, selection.end_pos
describe 'when .listener is set', ->
it 'calls listener.on_pos_changed with (listener, cursor) when moved', ->
buffer.text = '12345'
cursor.pos = 1
on_pos_changed = spy.new -> nil
cursor.listener = :on_pos_changed
cursor.pos = 3
assert.spy(on_pos_changed).was_called_with(cursor.listener, cursor)
| 27.728571 | 79 | 0.622102 |
c783c7b6e2b01f8b1771f37e026d785cefeca88e | 10,024 | require "spec.helpers" -- for one_of
db = require "lapis.db.postgres"
schema = require "lapis.db.postgres.schema"
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.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.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]]
}
}
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
| 21.556989 | 113 | 0.554769 |
501a4e90558212be7ff9a06e9e68cad76748004c | 15,813 | 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 }
import sorted_pairs from require "spec.helpers"
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"]]
}
{
-> db.insert "cats", { profile: "blue" }, db.raw "*"
[[INSERT INTO "cats" ("profile") VALUES ('blue') RETURNING *]]
}
{
-> db.insert "cats", { profile: "blue" }, db.raw "date_trunc('year', created_at) as create_year"
[[INSERT INTO "cats" ("profile") VALUES ('blue') RETURNING date_trunc('year', created_at) as create_year]]
}
{
-> db.insert "cats", { profile: "blue" }, "hello", db.raw "id + 3 as three_id"
[[INSERT INTO "cats" ("profile") VALUES ('blue') RETURNING "hello", id + 3 as three_id]]
}
{
-> db.insert "cats", { profile: "blue" }, returning: { }
[[INSERT INTO "cats" ("profile") VALUES ('blue')]]
}
{
-> db.insert "cats", { profile: "blue" }, returning: "*"
[[INSERT INTO "cats" ("profile") VALUES ('blue') RETURNING *]]
}
{
-> db.insert "cats", { profile: "blue" }, returning: { "one" }
[[INSERT INTO "cats" ("profile") VALUES ('blue') RETURNING "one"]]
}
{
-> db.insert "cats", { profile: "blue" }, returning: { "one", db.raw "a+c as thing" }
[[INSERT INTO "cats" ("profile") VALUES ('blue') RETURNING "one", a+c as thing]]
}
{
-> db.insert "cats", { profile: "blue" }, on_conflict: "do_nothing"
[[INSERT INTO "cats" ("profile") VALUES ('blue') ON CONFLICT DO NOTHING]]
}
{
-> db.insert "cats", { profile: "blue" }, on_conflict: "do_nothing", returning: "*"
[[INSERT INTO "cats" ("profile") VALUES ('blue') ON CONFLICT DO NOTHING RETURNING *]]
}
-- 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.create_index "user_data", "thing"
[[CREATE INDEX "user_data_thing_idx" ON "user_data" ("thing")]]
}
{
-> schema.create_index "user_data", "thing", unique: true
[[CREATE UNIQUE INDEX "user_data_thing_idx" ON "user_data" ("thing")]]
}
{
-> schema.create_index "user_data", "thing", unique: true, index_name: "good_idx"
[[CREATE UNIQUE INDEX "good_idx" ON "user_data" ("thing")]]
}
{
-> schema.create_index "user_data", "thing", if_not_exists: true
[[CREATE INDEX IF NOT EXISTS "user_data_thing_idx" ON "user_data" ("thing")]]
}
{
-> schema.create_index "user_data", "thing", unique: true, where: "age > 100"
[[CREATE UNIQUE INDEX "user_data_thing_idx" ON "user_data" ("thing") WHERE age > 100]]
}
{
-> schema.create_index "users", "friend_id", tablespace: "farket"
[[CREATE INDEX "users_friend_id_idx" ON "users" ("friend_id") TABLESPACE "farket"]]
}
{
-> schema.create_index "user_data", "one", "two"
[[CREATE INDEX "user_data_one_two_idx" ON "user_data" ("one", "two")]]
}
{
-> schema.create_index "user_data", db.raw("lower(name)"), "height"
[[CREATE INDEX "user_data_lower_name_height_idx" ON "user_data" (lower(name), "height")]]
}
{
-> schema.drop_index "user_data", "one", "two", "three"
[[DROP INDEX IF EXISTS "user_data_one_two_three_idx"]]
}
{
-> schema.drop_index index_name: "hello_world_idx"
[[DROP INDEX IF EXISTS "hello_world_idx"]]
}
{
-> schema.drop_index "user_data", "one", "two", "three", cascade: true
[[DROP INDEX IF EXISTS "user_data_one_two_three_idx" CASCADE]]
}
{
-> schema.drop_index "users", "height", { index_name: "user_tallness_idx", unique: true }
[[DROP INDEX IF EXISTS "user_tallness_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
describe "encode_assigns", ->
sorted_pairs!
it "writes output to buffer", ->
buffer = {"hello"}
-- nothing is returned when using buffer
assert.same nil, (db.encode_assigns {
one: "two"
zone: 55
age: db.NULL
}, buffer)
assert.same {
"hello"
'"age"', " = ", "NULL"
", "
'"one"', " = ", "'two'"
", "
'"zone"', " = ", "55"
}, buffer
it "fails when t is empty, buffer unchanged", ->
buffer = {"hello"}
assert.has_error(
-> db.encode_assigns {}, buffer
"encode_assigns passed an empty table"
)
assert.same { "hello" }, buffer
describe "encode_clause", ->
sorted_pairs!
it "writes output to buffer", ->
buffer = {"hello"}
-- nothing is returned when using buffer
assert.same nil, (db.encode_clause {
hello: "world"
lion: db.NULL
}, buffer)
assert.same {
"hello"
'"hello"', " = ", "'world'"
" AND "
'"lion"', " IS NULL"
}, buffer
it "fails when t is empty, buffer unchanged", ->
buffer = {"hello"}
assert.has_error(
-> db.encode_clause {}, buffer
"encode_clause passed an empty table"
)
assert.same { "hello" }, buffer
describe "encode_values", ->
sorted_pairs!
it "writes output to buffer", ->
buffer = {"hello"}
-- nothing is returned when using buffer
assert.same nil, (db.encode_values {
hello: "world"
lion: db.NULL
}, buffer)
assert.same {
"hello"
'(',
'"hello"', ', ', '"lion"'
') VALUES ('
"'world'", ', ', 'NULL'
')'
}, buffer
it "fails when t is empty, buffer unchanged", ->
buffer = {"hello"}
assert.has_error(
-> db.encode_values {}, buffer
"encode_values passed an empty table"
)
assert.same { "hello" }, buffer
| 21.514286 | 110 | 0.549674 |
d3e4692df04b79b35e778a4a204eec0894bb2050 | 2,400 | Dorothy!
SelectionPanelView = require "View.Control.Basic.SelectionPanel"
Button = require "Control.Basic.Button"
SelectionItem = require "Control.Basic.SelectionItem"
-- [signals]
-- "Selected",(item,index)->
-- [params]
-- items, title="", width=120, height=0.6*@H, itemHeight=50, fontSize=16, grouped=false, default=nil
Class
__partial: (args)=>
args.width or= 120
args.itemHeight or= 40
args.fontSize or= 16
args.height = args.height or (20+#args.items*(args.itemHeight+10)+(args.title and 70 or 0)+(args.subTitle and 30 or 0))
args.height = math.min CCDirector.winSize.height*0.6,args.height
SelectionPanelView args
__init: (args)=>
{:width,:items,:itemHeight,:fontSize,:grouped} = args
if grouped
default = args.default
@selectedItem = nil
selected = (button)->
@selectedItem.checked = false if @selectedItem and @selectedItem ~= button
button.checked = true unless button.checked
@selectedItem = button
for i,item in ipairs items
selectionItem = with SelectionItem {
text:item
fontSize:fontSize
width:width-20
height:itemHeight
}
.index = i
\slot "Tapped",selected
@menu\addChild selectionItem
if default == item
@selectedItem = selectionItem
@selectedItem\makeChecked!
else
for i,item in ipairs items
@menu\addChild with Button {
text:item
fontSize:fontSize
width:width-20
height:itemHeight
}
\slot "Tapped",->
@emit "Selected",item,i
@hide!
if grouped
@cancelBtn.text = "OK"
@cancelBtn\slot "Tapped",->
if @selectedItem
@emit "Selected",@selectedItem.text,@selectedItem.index
else
@emit "Selected",nil,nil
@hide!
else
@cancelBtn\slot "Tapped",->
@emit "Selected",nil,nil
@hide!
@scrollArea.viewSize = @menu\alignItemsVertically 10
@scrollArea\setupMenuScroll @menu
if @selectedItem
@scrollArea\scrollToPosY @selectedItem.positionY
CCDirector.currentScene\addChild @,editor.topMost
hide:=>
@scrollArea.touchEnabled = false
@menu.enabled = false
@opMenu.enabled = false
@cancelBtn\perform oScale 0.3,0,0,oEase.InBack
@perform oOpacity 0.3,0
@box\perform CCSequence {
CCSpawn {
oScale 0.3,0,0,oEase.InBack
oOpacity 0.3,0
}
CCCall -> @parent\removeChild @
}
| 27.586207 | 122 | 0.655833 |
402285bfde8973a03954084a87941565e0f5fd28 | 528 | -- Merge any number of hash tables (nil values will be removed)
M = {}
TK = require("PackageToolkit")
tail = (TK.module.import ..., "_tail").tail
merge2 = (TK.module.import ..., "_merge2").merge2
M.merge = (...) ->
tables = {...}
aux = (tables, accum) ->
if #tables == 0
return accum
else
return (aux (tail tables), (merge2 accum, tables[1]))
if #tables == 0
return {}
elseif #tables == 1
return tables[1]
else
return aux tables, {}
return M | 24 | 65 | 0.541667 |
d77919f6664a5cd61e20429d1bc71b7b29c160b2 | 3,302 | import new from require 'buffet.resty'
describe 'send()', ->
it 'should raise error if bad argument type', ->
err_tpl = "bad argument #2 to 'send' (string, number, boolean, nil, or array table expected, got %s)"
bf = new!
ok, err = pcall bf.send, bf, ->
assert.is.false, ok
assert.are.equal err_tpl\format('function'), err
f = io.tmpfile!
ok, err = pcall bf.send, bf, f
assert.is.false, ok
assert.are.equal err_tpl\format('userdata'), err
f\close!
describe 'should raise error if non-array table:', ->
for {msg, data} in *{
{'non-number', {'foo', 'bar', key: 'baz'}}
{'negative number', {'foo', 'bar', [-1]: 'baz'}}
{'floating-point number', {'foo', 'bar', [3.001]: 'baz'}}
{'non-number, nested', {'foo', {'bar', key: 'baz'}}}
{'negative number, nested', {'foo', 'bar', {[-1]: 'baz'}}}
{'floating-point number, nested', {'foo', 'bar', {[3.001]: 'baz'}}}
}
it msg, ->
bf = new!
ok, err = pcall bf.send, bf, data
assert.is.false, ok
assert.are.equal "bad argument #2 to 'send' (non-array table found)", err
describe 'should raise error if bad value type in table:', ->
for {bad_type, value} in *{
{'boolean', true}
{'nil', nil}
{'function', ->}
}
it bad_type, ->
tbl = {'foo', nil, 'bar'}
tbl[2] = value
bf = new!
ok, err = pcall bf.send, bf, tbl
assert.is.false, ok
assert.are.equal "bad argument #2 to 'send' (bad data type %s found)"\format(bad_type), err
it 'should return error if closed', ->
bf = new!
bf\close!
n, sent, err = nargs bf\send 'foo'
assert.are.equal 2, n
assert.is.nil sent
assert.are.equal 'closed', err
it 'should store sent data in send buffer', ->
bf = new!
bf\send 'foo'
bf\send 'bar'
bf\send 'baz'
assert.are.same bf._send_buffer, {'foo', 'bar', 'baz'}
describe 'should cast non-string value to string:', ->
for {msg, value, expected} in *{
{'int', 5, '5'}
{'float', 5.25, '5.25'}
{'boolean', false, 'false'}
{'nil', nil, 'nil'}
}
it msg, ->
bf = new!
n, sent = nargs bf\send value
assert.are.equal 1, n
assert.are.equal #expected, sent
assert.are.equal expected, bf._send_buffer[1]
it 'should flatten nested table', ->
bf = new!
n, sent = nargs bf\send {'alfa ', {'bravo ', {{'charlie '}, 'delta ', 'echo '}}, 'foxtrot ', 'golf'}
assert.are.equal 1, n
assert.are.equal 42, sent
assert.are.equal 'alfa bravo charlie delta echo foxtrot golf', bf._send_buffer[1]
it 'should flatten nested table with numbers', ->
bf = new!
n, sent = nargs bf\send {'foo', {1.23, {-432, 0.33}, 'bar', 'baz'}, 'qux'}
assert.are.equal 1, n
assert.are.equal 24, sent
assert.are.equal 'foo1.23-4320.33barbazqux', bf._send_buffer[1]
| 37.101124 | 109 | 0.496669 |
48b6abdfbd7a6b8a25c58b7901cae88b610926fd | 1,059 | -- This is in its own module to avoid having to require() the main
-- functionality in the case that someone is editing a filetype for which they
-- have precog disabled
vimw = require "facade"
start = ->
-- Skip if already initialized
if vimw.g_exists 'precog_initialized'
return nil
-- Initialize unset configuration options with defaults
vimw.g_defaults
precog_enable_globally: true
precog_autopredict: true
-- precog_prediction_delay_ms: 100
precog_fuzzy_prediction: false
precog_dedupe_results: false
precog_sources: vimw.empty_dict!
precog_filetype_blacklist: vimw.empty_dict!
-- Set up auto-enabling of predictions for buffers of any filetype not in the blacklist
vimw.exec [[
augroup precog_filetype_enable
au!
au BufEnter * if has_key(b:, "precog_enabled") == 0 && get(g:precog_filetype_blacklist, &filetype) == 0 | call precog#buffer_enable() | endif
augroup END
]]
vimw.g_set 'precog_initialized', true
vimw.option_set 'completeopt', 'menuone,preview,noselect'
{ :start }
| 33.09375 | 147 | 0.7356 |
82d49a83b68f3ada6442f450b8c2687ab1fac2ff | 4,154 | -- From https://gist.github.com/Kubuxu/e5e04c028d8aaeab4be8, works with big-endian order.
read_double = (bytes) ->
sign = 1
mantissa = bytes[2] % 2^4
for i = 3, 8
mantissa = mantissa * 256 + bytes[i]
if bytes[1] > 127
sign = -1
exponent = (bytes[1] % 128) * 2^4 + math.floor(bytes[2] / 2^4)
if exponent == 0
return 0
mantissa = (math.ldexp(mantissa, -52) + 1) * sign
return math.ldexp(mantissa, exponent - 1023)
write_double = (num) ->
bytes = {0,0,0,0,0,0,0,0}
if num == 0
return bytes
anum = math.abs(num)
mantissa, exponent = math.frexp(anum)
exponent = exponent - 1
mantissa = mantissa * 2 - 1
sign = num ~= anum and 128 or 0
exponent = exponent + 1023
bytes[1] = sign + math.floor(exponent / 2^4)
mantissa = mantissa * 2^4
currentmantissa = math.floor(mantissa)
mantissa = mantissa - currentmantissa
bytes[2] = (exponent % 2^4) * 2^4 + currentmantissa
for i= 3, 8
mantissa = mantissa * 2^8
currentmantissa = math.floor(mantissa)
mantissa = mantissa - currentmantissa
bytes[i] = currentmantissa
return bytes
-- Represents the FIRSTPASS_STATS struct of libvpx-vp8.
class FirstpassStats
duration_multiplier = 10000000.0
fields_before_duration = 16
fields_after_duration = 1
new: (before_duration, duration, after_duration) =>
@binary_data_before_duration = before_duration
@binary_duration = duration
@binary_data_after_duration = after_duration
-- All fields are doubles = 8 bytes.
@data_before_duration_size: () => fields_before_duration * 8
@data_after_duration_size: () => fields_after_duration * 8
@size: () => (fields_before_duration + 1 + fields_after_duration) * 8
get_duration: () =>
big_endian_binary_duration = reverse(@binary_duration)
read_double(reversed_binary_duration) / duration_multiplier
set_duration: (duration) =>
big_endian_binary_duration = write_double(duration * duration_multiplier)
@binary_duration = reverse(big_endian_binary_duration)
@from_bytes: (bytes) =>
before_duration = [b for b in *bytes[1, @data_before_duration_size!]]
duration = [b for b in *bytes[@data_before_duration_size! + 1, @data_before_duration_size! + 8]]
after_duration = [b for b in *bytes[@data_before_duration_size! + 8 + 1,]]
return self(before_duration, duration, after_duration)
_bytes_to_string: (bytes) =>
string.char(unpack(bytes))
as_binary_string: () =>
before_duration_string = self\_bytes_to_string(@binary_data_before_duration)
duration_string = self\_bytes_to_string(@binary_duration)
after_duration_string = self\_bytes_to_string(@binary_data_after_duration)
return before_duration_string .. duration_string .. after_duration_string
read_logfile_into_stats_array = (logfile_path) ->
file = assert(io.open(logfile_path, "rb"))
logfile_string = base64_decode(file\read!)
file\close!
stats_size = FirstpassStats\size!
assert(logfile_string\len! % stats_size == 0)
stats = {}
for offset=1,#logfile_string,stats_size
bytes = { logfile_string\byte(offset, offset + stats_size - 1) }
assert(#bytes == stats_size)
stats[#stats + 1] = FirstpassStats\from_bytes(bytes)
return stats
write_stats_array_to_logfile = (stats_array, logfile_path) ->
file = assert(io.open(logfile_path, "wb"))
logfile_string = ""
for stat in *stats_array
logfile_string ..= stat\as_binary_string!
file\write(base64_encode(logfile_string))
file\close!
vp8_patch_logfile = (logfile_path, encode_total_duration) ->
stats_array = read_logfile_into_stats_array(logfile_path)
-- Last FirstpassStats is a aggregated one.
average_duration = encode_total_duration / (#stats_array - 1)
for i=1, #stats_array - 1
stats_array[i]\set_duration(average_duration)
stats_array[#stats_array]\set_duration(encode_total_duration)
write_stats_array_to_logfile(stats_array, logfile_path)
| 34.907563 | 104 | 0.679586 |
267c1cf8defd15a3418b7b3dc0550747599d78c6 | 515 | export modinfo = {
type: "command"
desc: "Health"
alias: {"health", "sethealth"}
func: (Msg,Speaker) ->
for i = 1, #Msg
if string.sub(Msg, i, i) == ConfigSystem("Get", "Blet")
search = GetPlayers(string.sub(Msg, 1, i - 1))
for _,v in pairs(search)
if v.Character
if v.Character\FindFirstChild("Humanoid")
v.Character.Humanoid.MaxHealth = tonumber(string.sub(Msg, i+1))
v.Character.Humanoid.Health = tonumber(string.sub(Msg, i+1))
Output("Changed health",{Colors.Green})
} | 34.333333 | 70 | 0.642718 |
a2e72e3a5339432834400cc1fb0510baa18cbfc2 | 5,760 |
env = require "lapis.environment"
normalize_headers = do
normalize = (header) ->
header\lower!\gsub "-", "_"
(t) ->
setmetatable {normalize(k), v for k,v in pairs t}, __index: (name) =>
rawget @, normalize name
add_cookie = (headers, name, val) ->
import escape from require "lapis.util"
assign = "#{escape name}=#{escape val}"
if old = headers.Cookie
headers.Cookie = "#{old}; #{assign}"
else
headers.Cookie = assign
-- returns the result of request using app
-- mock_request App, "/hello"
-- mock_request App, "/hello", { host: "leafo.net" }
mock_request = (app_cls, url, opts={}) ->
stack = require "lapis.spec.stack"
import parse_query_string, encode_query_string from require "lapis.util"
import insert, concat from table
logger = require "lapis.logging"
old_logger = logger.request
logger.request = ->
-- look for existing params in url
url_base, url_query = url\match "^(.-)%?(.*)$"
url_base = url unless url_base
get_params = if url_query
parse_query_string url_query
else {}
-- copy in new params
if opts.get
for k,v in pairs opts.get
if type(k) == "number"
insert get_params, v
else
get_params[k] = v
-- filter out extra has params
for k,v in pairs get_params
if type(v) == "table"
get_params[v[1]] = nil
url_query = encode_query_string(get_params)
request_uri = url_base
if url_query == ""
url_query = nil
else
request_uri ..= "?" .. url_query
host = opts.host or "localhost"
request_method = opts.method or (opts.post and "POST") or "GET"
scheme = opts.scheme or "http"
server_port = opts.port or 80
http_host = host
unless server_port == 80
http_host ..= ":#{server_port}"
prev_request = normalize_headers(opts.prev or {})
headers = {
Host: host
Cookie: prev_request.set_cookie
}
if opts.cookies
for k, v in pairs opts.cookies
add_cookie headers, k, v
if opts.post
headers["Content-type"] = "application/x-www-form-urlencoded"
if opts.session
config = require("lapis.config").get!
import encode_session from require "lapis.session"
add_cookie headers, config.session_name, encode_session opts.session
if opts.headers
for k,v in pairs opts.headers
headers[k] = v
headers = normalize_headers headers
out_headers = {}
nginx = require "lapis.nginx"
buffer = {}
flatten = (tbl, accum={})->
for thing in *tbl
if type(thing) == "table"
flatten thing, accum
else
insert accum, thing
accum
hex = (str)->
(str\gsub ".", (c) -> string.format "%02x", string.byte c)
stack.push {
print: (...) ->
args = flatten { ... }
str = [tostring a for a in *args]
insert buffer, a for a in *args
true
say: (...) ->
ngx.print ...
ngx.print "\n"
md5: (str) ->
digest = require "openssl.digest"
hex((digest.new "md5")\final str)
header: out_headers
now: -> os.time!
update_time: => os.time!
ctx: { }
var: setmetatable {
:host
:http_host
:request_method
:request_uri
:scheme
:server_port
args: url_query
query_string: url_query
remote_addr: "127.0.0.1"
uri: url_base
}, __index: (name) =>
if header_name = name\match "^http_(.+)"
return headers[header_name]
req: {
read_body: ->
get_body_data: -> opts.body or opts.post and encode_query_string(opts.post) or nil
get_headers: -> headers
get_uri_args: ->
out = {}
add_arg = (k,v) ->
if current = out[k]
if type(current) == "table"
insert current, v
else
out[k] = {current, v}
else
out[k] = v
for k,v in pairs get_params
if type(v) == "table"
add_arg unpack v
else
add_arg k, v
out
get_post_args: ->
opts.post or {}
}
}
-- if app is already an instance just use it
app = app_cls.__base and app_cls! or app_cls
unless app.router
app\build_router!
env.push "test"
response = nginx.dispatch app
env.pop!
stack.pop!
logger.request = old_logger
out_headers = normalize_headers out_headers
body = concat(buffer)
unless opts.allow_error
if error_blob = out_headers.x_lapis_error
json = require "cjson"
{:summary, :err, :trace} = json.decode error_blob
error "\n#{summary}\n#{err}\n#{trace}"
if opts.expect == "json"
json = require "cjson"
unless pcall -> body = json.decode body
error "expected to get json from #{url}"
response.status or 200, body, out_headers
assert_request = (...) ->
res = {mock_request ...}
if res[1] == 500
assert false, "Request failed: " .. res[2]
unpack res
-- returns the result of running fn in the context of a mocked request
-- mock_action App, -> "hello"
-- mock_action App, "/path", -> "hello"
-- mock_action App, "/path", { host: "leafo.net"}, -> "hello"
mock_action = (app_cls, url, opts, fn) ->
if type(url) == "function" and opts == nil
fn = url
url = "/"
opts = {}
if type(opts) == "function" and fn == nil
fn = opts
opts = {}
local ret
handler = (...) ->
ret = { fn ... }
layout: false
class A extends app_cls
"/*": handler
"/": handler
assert_request A, url, opts
unpack ret
-- creates a reuest object and returns it
stub_request = (app_cls, url="/", opts={}) ->
local stub
class App extends app_cls
dispatch: (req, res) =>
stub = @.Request @, req, res
mock_request App, url, opts
stub
{ :mock_request, :assert_request, :normalize_headers, :mock_action, :stub_request }
| 22.412451 | 88 | 0.603299 |
5970358700078654af56953003e309b6fd7b5d63 | 7,081 | json = require'json'
simplehttp = require'simplehttp'
httpserver = require'handler.http.server'
ev = require'ev'
loop = ev.Loop.default
on_data = (req, resp, data) ->
--print('---- start request body')
--io.write(data) if data
--print('---- end request body')
return
on_finished = (req, resp) ->
channel = req.url\match('channel=(.+)')
unless channel
html = 'Invalid channel'
resp\set_status(404)
resp\set_header('Content-Type', 'text/html')
resp\set_header('Content-Length', #html)
resp\set_body(html)
resp\send()
return
else
channel = '#'..channel
html = [[
<!DOCTYPE html>
<html>
<head>
<!-- adapted from dbot's map by xt -->
<!-- set location with !location set yourlocation -->
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<title>IRC member map</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
</style>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key=AIzaSyC2Jfvn8PUvx90DuVE9Ofwui2_3LTU4OPw&sensor=false"></script>
<script src="//google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer_packed.js"></script>
</head><body>
<div id="map" style="width: 100%; height: 100%"></div>
<script type="text/javascript">
]]
markerdata = {}
for n,t in pairs ivar2.channels[channel].nicks
pos = ivar2.persist["location:coords:#{n}"]
if pos
lat, lon = pos\match('([^,]+),([^,]+)')
marker = {
account: n,
formattedAddress: ivar2.persist["location:place:#{n}"] or 'N/A',
lng: tonumber(lon),
lat: tonumber(lat),
channel: channel
}
markerdata[#markerdata + 1] = marker
if #markerdata == 0 then
html = 'Invalid channel'
resp\set_status(404)
resp\set_header('Content-Type', 'text/html')
resp\set_header('Content-Length', #html)
resp\set_body(html)
resp\send()
return
html ..= [[
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 3
});
var infoWindow = null;
var markers = [];
function makeInfoWindow(info) {
return new google.maps.InfoWindow({
content: makeMarkerDiv(info)
});
}
function makeMarkerDiv(h) {
return "<div style='line-height:1.35;overflow:hidden;white-space:nowrap'>" + h + "</div>";
}
function makeMarkerInfo(m) {
return "<strong>" + m.get("account") + " on " + m.get("channel") + "</strong> " +
m.get("formattedAddress");
}
function dismiss() {
if (infoWindow !== null) {
infoWindow.close();
}
}
]]..json.encode(markerdata)..[[.forEach(function (loc) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(loc.lat, loc.lng)
});
marker.setValues(loc);
markers.push(marker);
google.maps.event.addListener(marker, "mouseover", function () {
dismiss();
infoWindow = makeInfoWindow(makeMarkerInfo(marker));
infoWindow.open(map, marker);
});
google.maps.event.addListener(marker, "mouseout", dismiss);
google.maps.event.addListener(marker, "click", function () {
map.setZoom(Math.max(8, map.getZoom()));
map.setCenter(marker.getPosition());
});
});
var mc = new MarkerClusterer(map, markers, {
averageCenter: true
});
google.maps.event.addListener(mc, "mouseover", function (c) {
dismiss();
var markers = c.getMarkers();
infoWindow = makeInfoWindow(markers.map(makeMarkerInfo).join("<br>"));
infoWindow.setPosition(c.getCenter());
infoWindow.open(map);
});
google.maps.event.addListener(mc, "mouseout", dismiss);
google.maps.event.addListener(mc, "click", dismiss);
</script>
</body>
</html>
]]
--print('---- request finished, send response')
resp\set_status(200)
resp\set_header('Content-Type', 'text/html')
resp\set_header('Content-Length', #html)
resp\set_body(html)
resp\send()
on_response_sent = (resp) ->
return
on_request = (server, req, resp) ->
--print('---- start request headers: method =' .. req.method .. ', url = ' .. req.url)
--for k,v in pairs(req.headers)
-- print(k .. ": " .. v)
--print('---- end request headers')
-- check for '/favicon.ico' requests.
if req.url\lower() == '/favicon.ico'
-- return 404 Not found error
resp\set_status(404)
resp\send()
return
-- add callbacks to request.
req.on_data = on_data
req.on_finished = on_finished
-- add response callbacks.
resp.on_response_sent = on_response_sent
-- Check for already running server
if ivar2.webserver == nil
print '---- Starting webserver ---- '
ivar2.webserver = httpserver.new loop, {
name: "ivar2-HTTPServer/0.0.1",
on_request: on_request,
request_head_timeout: 1.0,
request_body_timeout: 1.0,
write_timeout: 10.0,
keep_alive_timeout: 1.0,
max_keep_alive_requests: 10,
}
ivar2.webserver\listen_uri "tcp://0.0.0.0:#{ivar2.config.webserverport}/"
else
-- Swap out the request handler with the reloaded one
ivar2.webserver.on_request = on_request
urlEncode = (str, space) ->
space = space or '+'
str = str\gsub '([^%w ])', (c) ->
string.format "%%%02X", string.byte(c)
return str\gsub(' ', space)
lookup = (address, cb) ->
API_URL = 'http://maps.googleapis.com/maps/api/geocode/json'
url = API_URL .. '?address=' .. urlEncode(address) .. '&sensor=false' .. '&language=en-GB'
simplehttp url, (data) ->
parsedData = json.decode data
if parsedData.status ~= 'OK'
return false, parsedData.status or 'unknown API error'
location = parsedData.results[1]
locality, country, adminArea
findComponent = (field, ...) ->
n = select('#', ...)
for i=1, n
searchType = select(i, ...)
for _, component in ipairs(location.address_components)
for _, type in ipairs(component.types)
if type == searchType
return component[field]
locality = findComponent('long_name', 'locality', 'postal_town', 'route', 'establishment', 'natural_feature')
adminArea = findComponent('short_name', 'administrative_area_level_1')
country = findComponent('long_name', 'country') or 'Nowhereistan'
if adminArea and #adminArea <= 5
if not locality
locality = adminArea
else
locality = locality..', '..adminArea
locality = locality or 'Null'
place = locality..', '..country
cb place, location.geometry.location.lat..','..location.geometry.location.lng
PRIVMSG:
'^%plocation set (.+)$': (source, destination, arg) =>
lookup arg, (place, loc) ->
nick = source.nick
@.persist["location:place:#{nick}"] = place
@.persist["location:coords:#{nick}"] = loc
say '%s %s', place, loc
'^%plocation map$': (source, destination, arg) =>
channel = destination\sub(2)
say "http://irc.lart.no:#{ivar2.config.webserverport}/?channel=#{channel}"
| 30.004237 | 143 | 0.628442 |
8ad474bcea0a2a0c352e0fe182918532b010aa75 | 1,159 | -- Copyright 2012-2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import colors from howl.ui
aullar_styles = require 'aullar.styles'
{:define, :define_default} = aullar_styles
set_for_theme = (theme) ->
for name, definition in pairs theme.styles
define name, definition
at_pos = (buffer, pos) ->
b_pos = buffer\byte_offset pos
buffer._buffer.styling\at b_pos
-- define some default styles
define 'black', color: colors.black
define 'red', color: colors.red
define 'green', color: colors.green
define 'yellow', color: colors.yellow
define 'blue', color: colors.blue
define 'magenta', color: colors.magenta
define 'cyan', color: colors.cyan
define 'white', color: colors.white
-- define some default formatting styles
define 'bold', font: bold: true
define 'emphasis', font: italic: true
-- alias some default styles
define 'symbol', 'key'
define 'global', 'member'
define 'regex', 'string'
define 'type_def', 'type'
return setmetatable {
:set_for_theme
:define
:define_default
:at_pos
}, __index: (t, k) ->
aullar_styles.is_defined(k) and aullar_styles.def_for(k) or nil
| 26.953488 | 79 | 0.737705 |
c6ac94f90aeb10348e95f81f598407a9e8924807 | 257 | Component = require "lib.concord.component"
Bounds = Component (entity, top, bottom, left, right) ->
entity.top = top or 0
entity.bottom = bottom or love.graphics.getHeight!
entity.left = left or 0
entity.right = right or love.graphics.getWidth!
Bounds | 32.125 | 56 | 0.743191 |
f15b122c68cfd906a9ca0fc71240e8000b14795d | 2,580 | void = {key,true for key in *{
"area", "base", "br", "col"
"command", "embed", "hr", "img"
"input", "keygen", "link", "meta"
"param", "source", "track", "wbr"
}}
escapes = {
['&']: '&'
['<']: '<'
['>']: '>'
['"']: '"'
["'"]: '''
}
pair= (buffer = {}) ->
if type(buffer) != 'table'
error 2, "Argument must be a table or nil"
environment = {}
escape = (value) ->
(=>@) tostring(value)\gsub [[[<>&]'"]], escapes
split = (tab) ->
ary = {}
for k,v in ipairs(tab) do
ary[k]=v
tab[k]=nil
return ary, tab
flatten = (tab, flat={}) ->
for key, value in pairs tab
if type(key)=="number"
if type(value)=="table"
flatten(value, flat)
else
flat[#flat+1]=value
else
if type(value)=="table"
flat[key] = table.concat value ' '
else
flat[key] = value
flat
attrib = (args) ->
res = setmetatable {}, __tostring: =>
tab = ["#{key}=\"#{value}\"" for key, value in pairs(@) when type(value)=='string' or type(value)=='number']
#tab > 0 and ' '..table.concat(tab,' ') or ''
for key, value in pairs(args)
if type(key)=='string'
res[key] = value
r = true
return res
handle = (args) ->
for arg in *args
switch type(arg)
when 'table'
handle arg
when 'function'
arg!
else
table.insert buffer, tostring arg
environment.raw = (text) ->
table.insert buffer, text
environment.text = (text) ->
table.insert buffer, (escape text)
environment.tag = (tagname, ...) ->
inner, args = split flatten {...}
table.insert buffer, "<#{tagname}#{attrib args}>"
handle inner
table.insert buffer, "</#{tagname}>" unless void[key]
setmetatable environment, {
__index: (key) =>
_ENV[key] or (...) ->
environment.tag(key, ...)
}
return environment, buffer
build = if _VERSION == 'lua 5.1' then
(fnc) ->
assert(type(fnc)=='function', 'wrong argument to render, expecting function')
env, buf = pair
setfenv(fnc, env)
fnc!
buf
else
(fnc) ->
assert(type(fnc)=='function', 'wrong argument to render, expecting function')
env, buf = pair!
hlp = do -- gotta love this syntax ♥
_ENV = env
-> aaaaa -- needs to access a global to get the environment upvalue
debug.upvaluejoin(fnc, 1, hlp, 1) -- Set environment
fnc!
buf.render = => table.concat @, "\n"
buf
render = (fnc) ->
build(fnc)\render!
{:render, :build, :pair}
| 23.888889 | 114 | 0.534884 |
e49bbb407276000c2fa7824e74052abd7e0a0eae | 1,236 |
find_nginx = do
nginx_bin = "nginx"
nginx_search_paths = {
"/usr/local/openresty/nginx/sbin/"
"/usr/sbin/"
""
}
local nginx_path
->
return nginx_path if nginx_path
for prefix in *nginx_search_paths
cmd = "#{prefix}#{nginx_bin} -v 2>&1"
handle = io.popen cmd
out = handle\read!
handle\close!
if out\match "^nginx version: ngx_openresty/"
nginx_path = "#{prefix}#{nginx_bin}"
return nginx_path
filters = {
pg: (url) ->
user, password, host, db = url\match "^postgres://(.*):(.*)@(.*)/(.*)$"
error "failed to parse postgres server url" unless user
"%s dbname=%s user=%s password=%s"\format host, db, user, password
}
compile_config = (config, opts={}) ->
env = setmetatable {}, __index: (key) =>
v = os.getenv "LAPIS_" .. key\upper!
return v if v != nil
opts[key\lower!]
out = config\gsub "(${%b{}})", (w) ->
name = w\sub 4, -3
filter_name, filter_arg = name\match "^(%S+)%s+(.+)$"
if filter = filters[filter_name]
value = env[filter_arg]
if value == nil then w else filter value
else
value = env[name]
if value == nil then w else value
out
{ :compile_config, :filters, :find_nginx }
| 25.75 | 75 | 0.58657 |
eabed7327a6c1ea241bc47f1c7dc6d0464e11b20 | 5,763 |
--
-- Copyright (C) 2017-2019 DBot
-- 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.
hook.Add 'PlayerSpawn', 'PPM2.Hooks', =>
if IsValid(@__ppm2_ragdoll)
@__ppm2_ragdoll\Remove()
@UnSpectate()
timer.Simple 0, ->
return unless @IsValid()
if @GetPonyData()
@GetPonyData()\PlayerRespawn()
net.Start('PPM2.PlayerRespawn')
net.WriteEntity(@)
net.Broadcast()
do
REQUIRE_CLIENTS = {}
safeSendFunction = ->
for ply, data in pairs REQUIRE_CLIENTS
if not IsValid(ply)
REQUIRE_CLIENTS[ply] = nil
continue
ent = table.remove(data, 1)
if not ent
REQUIRE_CLIENTS[ply] = nil
continue
data = ent\GetPonyData()
continue if not data
data\NetworkTo(ply)
errorTrack = (err) ->
PPM2.Message 'Networking Error: ', err
PPM2.Message debug.traceback()
timer.Create 'PPM2.Require', 0.25, 0, -> xpcall(safeSendFunction, errorTrack)
net.Receive 'PPM2.Require', (len = 0, ply = NULL) ->
return if not IsValid(ply)
REQUIRE_CLIENTS[ply] = {}
target = REQUIRE_CLIENTS[ply]
for _, ent in ipairs ents.GetAll()
if ent ~= ply
data = ent\GetPonyData()
if data
table.insert(target, ent)
PPM2.ENABLE_NEW_RAGDOLLS = CreateConVar('ppm2_sv_new_ragdolls', '1', {FCVAR_NOTIFY, FCVAR_REPLICATED}, 'Enable new ragdolls')
ENABLE_NEW_RAGDOLLS = PPM2.ENABLE_NEW_RAGDOLLS
RAGDOLL_COLLISIONS = CreateConVar('ppm2_sv_ragdolls_collisions', '1', {FCVAR_NOTIFY, FCVAR_REPLICATED}, 'Enable ragdolls collisions')
createPlayerRagdoll = =>
@__ppm2_ragdoll\Remove() if IsValid(@__ppm2_ragdoll)
@__ppm2_ragdoll = ents.Create('prop_ragdoll')
rag = @GetRagdollEntity()
rag\Remove() if IsValid(rag)
with @__ppm2_ragdoll
\SetModel(@GetModel())
\SetPos(@GetPos())
\SetAngles(@EyeAngles())
\SetCollisionGroup(COLLISION_GROUP_INTERACTIVE_DEBRIS) if RAGDOLL_COLLISIONS\GetBool()
\SetCollisionGroup(COLLISION_GROUP_WORLD) if not RAGDOLL_COLLISIONS\GetBool()
\Spawn()
\Activate()
hook.Run 'PlayerSpawnedRagdoll', @, @GetModel(), @__ppm2_ragdoll
.__ppm2_ragdoll_parent = @
\SetCollisionGroup(COLLISION_GROUP_INTERACTIVE_DEBRIS)
\SetNWBool('PPM2.IsDeathRagdoll', true)
vel = @GetVelocity()
\SetVelocity(vel)
\SetAngles(@EyeAngles())
@Spectate(OBS_MODE_CHASE)
@SpectateEntity(@__ppm2_ragdoll)
for boneID = 0, @__ppm2_ragdoll\GetBoneCount() - 1
physobjID = @__ppm2_ragdoll\TranslateBoneToPhysBone(boneID)
pos, ang = @GetBonePosition(boneID)
physobj = @__ppm2_ragdoll\GetPhysicsObjectNum(physobjID)
physobj\SetVelocity(vel)
physobj\SetMass(300) -- lol
physobj\SetPos(pos, true) if pos
physobj\SetAngles(ang) if ang
copy = @GetPonyData()\Clone(@__ppm2_ragdoll)
copy\Create()
ALLOW_RAGDOLL_DAMAGE = CreateConVar('ppm2_sv_ragdoll_damage', '1', {FCVAR_ARCHIVE, FCVAR_NOTIFY}, 'Should death ragdoll cause damage?')
hook.Add 'EntityTakeDamage', 'PPM2.DeathRagdoll', (dmg) =>
attacker = dmg\GetAttacker()
return if not IsValid(attacker)
if attacker.__ppm2_ragdoll_parent
dmg\SetAttacker(attacker.__ppm2_ragdoll_parent)
if not ALLOW_RAGDOLL_DAMAGE\GetBool()
dmg\SetDamage(0)
dmg\SetMaxDamage(0)
hook.Add 'PostPlayerDeath', 'PPM2.Hooks', =>
return if not @GetPonyData()
@GetPonyData()\PlayerDeath()
net.Start('PPM2.PlayerDeath')
net.WriteEntity(@)
net.Broadcast()
if ENABLE_NEW_RAGDOLLS\GetBool() and @IsPony()
createPlayerRagdoll(@)
return
hook.Add 'PlayerDeath', 'PPM2.Hooks', =>
return if not @GetPonyData()
if ENABLE_NEW_RAGDOLLS\GetBool() and @IsPony()
createPlayerRagdoll(@)
return
hook.Add 'EntityRemoved', 'PPM2.PonyDataRemove', =>
return if @IsPlayer()
return if not @GetPonyData()
with @GetPonyData()
net.Start('PPM2.PonyDataRemove')
net.WriteUInt(.netID, 16)
net.Broadcast()
\Remove()
return
hook.Add 'PlayerDisconnected', 'PPM2.NotifyClients', =>
@__ppm2_ragdoll\Remove() if IsValid(@__ppm2_ragdoll)
data = @GetPonyData()
return if not data
net.Start('PPM2.NotifyDisconnect')
net.WriteUInt(data.netID, 16)
net.Broadcast()
BOTS_ARE_PONIES = CreateConVar('ppm2_bots', '1', {FCVAR_ARCHIVE, FCVAR_NOTIFY}, 'Whatever spawn bots as ponies')
hook.Add 'PlayerSetModel', 'PPM2.Bots', =>
return if not BOTS_ARE_PONIES\GetBool()
return if not @IsBot()
@SetModel('models/ppm/player_default_base_new.mdl')
return true
PlayerSpawnBot = =>
return if not BOTS_ARE_PONIES\GetBool()
return if not @IsBot()
timer.Simple 1, ->
return if not IsValid(@)
@SetViewOffset(Vector(0, 0, PPM2.PLAYER_VIEW_OFFSET))
@SetViewOffsetDucked(Vector(0, 0, PPM2.PLAYER_VIEW_OFFSET_DUCK))
if not @GetPonyData()
data = PPM2.NetworkedPonyData(nil, @)
PPM2.Randomize(data)
data\Create()
hook.Add 'PlayerSpawn', 'PPM2.Bots', PlayerSpawnBot
timer.Simple 0, -> PlayerSpawnBot(ply) for _, ply in ipairs player.GetAll()
| 33.312139 | 135 | 0.740066 |
d172dd6d1879a7fd8b84d690534d56cc7708009d | 1,515 | class Group extends Item
_serializeFields:
children: []
new: (arg0) =>
super\new(arg)
-- Allow Group to have children and named children
@_children = []
@_namedChildren = {}
@addChildren (if isArray(arg0) then arg0 else arg) if arg0 and not @_set(arg0)
_changed: _changed = (flags) =>
_changed\base(flags)
--- Apply matrix now that we have content.
@applyMatrix() if flags & ChangeFlag.HIERARCHY and not @_matrix.isIdentity()
-- Clear cached clip item whenever hierarchy changes
delete @_clipItem if flags & (ChangeFlag.HIERARCHY | ChangeFlag.CLIPPING)
_getClipItem: =>
-- Allow us to set _clipItem to null when none is found and still return
-- it as a defined value without searching again
return @_clipItem if @_clipItem isnt nil
i = 0
l = @_children.length
while i < l
child = @_children[i]
return @_clipItem = child if child._clipMask
i++
-- Make sure we're setting _clipItem to null so it won't be searched for
-- nex time.
@_clipItem = nil
isClipped: =>
!!@_getClipItem()
setClipped: (clipped) =>
child = @getFirstChild()
child\setClipMask clipped if child
_draw: (ctx, param) =>
clipItem = param.clipItem = @_getClipItem()
clipItem\draw ctx, param\extend(clip: true) if clipItem
i = 0
l = @_children.length
while i < l
item = @_children[i]
item\draw ctx, param if item isnt clipItem
i++
param.clipItem = nil | 27.053571 | 82 | 0.641584 |
37d3051f51b35c77265dc1694bfd531a4363ff87 | 6,995 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, command, dispatch, interact, config, keymap from howl
import Window from howl.ui
describe 'command', ->
local cmd
run = (...) ->
f = coroutine.wrap (...) -> command.run ...
f ...
before_each ->
app.window = Window!
cmd = name: 'foo', description: 'desc', handler: spy.new -> 'foo-result'
after_each ->
app.window = nil
command.unregister name for name in *command.names!
describe '.register(command)', ->
it 'raises an error if any of the mandatory fields are missing', ->
assert.raises 'name', -> command.register {}
assert.raises 'description', -> command.register name: 'foo'
assert.raises 'handler', -> command.register name: 'foo', description: 'do'
assert.raises 'factory', -> command.register name: 'foo', description: 'do'
it '.names() returns a list of all command names', ->
command.register cmd
assert.includes command.names!, 'foo'
it '.get(name) returns the command with the specified name', ->
command.register cmd
assert.equal command.get('foo').handler, cmd.handler
it 'calling .<name>(args) invokes command, passing arguments', ->
command.register cmd
command.foo('arg1', 'arg2')
assert.spy(cmd.handler).was_called 1
assert.spy(cmd.handler).was_called_with 'arg1', 'arg2'
describe '.alias(target, name)', ->
it 'raises an error if target does not exist', ->
assert.raises 'exist', -> command.alias 'nothing', 'something'
it 'allows for multiple names for the same command', ->
command.register cmd
command.alias 'foo', 'bar'
assert.equal 'foo', command.get('bar').alias_for
assert.includes command.names!, 'bar'
it '.unregister(command) removes the command and any aliases', ->
command.register cmd
command.alias 'foo', 'bar'
command.unregister 'foo'
assert.is_nil command.foo
assert.is_nil command.bar
assert.same command.names!, {}
context 'when command name is a non-lua identifier', ->
before_each -> cmd.name = 'foo-cmd:bar'
it 'register() adds accessible aliases', ->
command.register cmd
assert.not_nil command.foo_cmd_bar
it 'the accessible alias is not part of names()', ->
command.register cmd
assert.same command.names!, { 'foo-cmd:bar' }
it 'calling .<accessible_name>(args) invokes command, passing arguments', ->
command.register cmd
dispatch.launch -> command.foo_cmd_bar('arg1', 'arg2')
assert.spy(cmd.handler).was_called 1
assert.spy(cmd.handler).was_called_with 'arg1', 'arg2'
it 'unregister() removes the accessible name as well', ->
command.register cmd
command.unregister 'foo-cmd:bar'
assert.is_nil command.foo_cmd_bar
describe '.run(cmd_string)', ->
context 'when <cmd_string> is empty or missing', ->
it 'displays the commandline with a ":" prompt', ->
run!
assert.equals ':', app.window.command_line.prompt
context 'when <cmd_string> is given', ->
context 'and it matches a command', ->
it 'that command is invoked', ->
command.register cmd
run cmd.name
assert.spy(cmd.handler).was_called 1
context 'and the command specifies an input function', ->
local cmd
before_each ->
cmd =
name: 'with-input'
description: 'test'
input: spy.new -> 'input-result1', 'input-result2'
handler: spy.new ->
command.register cmd
it 'calls the command input function, passing through extra args', ->
run cmd.name, 'arg1', 'arg2'
assert.spy(cmd.input).was_called 1
assert.spy(cmd.input).was_called_with 'arg1', 'arg2'
it 'passes the result of the input function into the handler', ->
run cmd.name
assert.spy(cmd.handler).was_called 1
assert.spy(cmd.handler).was_called_with 'input-result1', 'input-result2'
it 'does not call handler if input function returns nil', ->
cmd = {
name: 'cancelled-input'
description: 'test'
input: ->
handler: spy.new ->
}
command.register cmd
run cmd.name
assert.spy(cmd.handler).was_called 0
it 'sets spillover to any text arguments before invoking the input', ->
local spillover
command.register
name: 'with-input'
description: 'test'
input: -> spillover = app.window.command_line\pop_spillover!
handler: ->
run 'with-input hello cmd'
assert.equal 'hello cmd', spillover
it 'displays the ":<cmd_string> " in the command line during input', ->
local prompt
cmd = {
name: 'getp'
description: 'desc'
input: -> prompt = app.window.command_line.command_widget.text
handler: ->
}
command.register cmd
run 'getp'
assert.equals ':'..cmd.name..' ', prompt
context 'and the command does not specify an input function', ->
it 'calls the command handler, passing through extra args', ->
cmd = {
name: 'without-input'
description: 'test'
handler: spy.new ->
}
command.register cmd
run cmd.name, 'arg1', 'arg2'
assert.spy(cmd.handler).was_called 1
assert.spy(cmd.handler).was_called_with 'arg1', 'arg2'
context 'and it matches an alias', ->
it 'the aliased command is invoked', ->
command.register cmd
command.alias cmd.name, 'aliascmd'
run 'aliascmd'
assert.spy(cmd.handler).was_called 1
context 'and it contains <non-interactive-command>space<args>', ->
before_each ->
log.clear!
command.register cmd
it 'logs an error', ->
run cmd.name .. ' args'
assert.not_nil log.last_error
it 'the command line contains the command name', ->
run cmd.name .. ' args'
assert.equals cmd.name, app.window.command_line.text
context 'and it contains <invalid-command>space<args>', ->
it 'logs an error', ->
run 'no-such-command hello cmd'
assert.not_nil log.last_error
it 'the command line contains the passed text', ->
run 'no-such-command hello cmd'
assert.equals 'no-such-command hello cmd', app.window.command_line.text
context 'when it specifies a unknown command', ->
it 'displays the <cmd_string> in the commandline text', ->
run 'what-the-heck now'
assert.equals 'what-the-heck now', app.window.command_line.text
| 35.688776 | 84 | 0.599285 |
14d52f8ed561c83c0a8d46354ff59abf9987529a | 482 | Command = require('lib/commands/command')
{ :Vector, :Direction } = require('vendor/hug/lib/geo')
class MoveCommand extends Command
new: (@entity, @velocity, @speed) =>
exec: () =>
if @velocity.class == Direction
speed = if @speed then @speed else @entity.maxSpeed
@velocity = Vector(@velocity, speed)
@entity\set('velocity', @velocity)
@entity.animation.value\resume()
undo: () =>
{ :velocity } = @entity\get()
@entity\set('velocity', velocity - @velocity)
| 25.368421 | 55 | 0.6639 |
4e7f9f78fe828383e0cf5256ad1d87998e97856a | 2,586 | Slot = require('settings.slots.slot')
class Slots
new: () =>
@slots = [Slot(i) for i = 1, STATE.NUM_SLOTS]
assert(#@slots == STATE.NUM_SLOTS, 'settings.slots.init.Slots')
@settings = {}
scrollBar = SKIN\GetMeter('ScrollBar')
assert(scrollBar ~= nil, 'settings.slots.init.Slots')
@scrollBarStart = if scrollBar then scrollBar\GetY() else 0
@scrollBarMaxHeight = if scrollBar then scrollBar\GetH() else 0
@scrollBarHeight = @scrollBarMaxHeight
@scrollBarStep = 0
updateScrollBar: (numSettings) =>
if numSettings > STATE.NUM_SLOTS
@scrollBarHeight = math.round(@scrollBarMaxHeight / (numSettings - STATE.NUM_SLOTS + 1))
@scrollBarStep = (@scrollBarMaxHeight - @scrollBarHeight) / (numSettings - STATE.NUM_SLOTS)
else
@scrollBarHeight = @scrollBarMaxHeight
@scrollBarStep = 0
SKIN\Bang(('[!SetOption "ScrollBar" "H" "%d"]')\format(@scrollBarHeight))
update: (settings) =>
@settings = settings
@updateScrollBar(#settings)
@scroll()
return #settings - STATE.NUM_SLOTS + 1
getNumSettings: () => return #@settings
getSetting: (index) => return @settings[index + STATE.SCROLL_INDEX - 1]
updateSlot: (index) =>
@slots[index]\update(@getSetting(index))
scroll: () =>
yPos = @scrollBarStart + (STATE.SCROLL_INDEX - 1) * @scrollBarStep
SKIN\Bang(('[!SetOption "ScrollBar" "Y" "%d"]')\format(yPos))
@updateSlot(index) for index = 1, STATE.NUM_SLOTS
performAction: (index) => @getSetting(index)\perform()
toggleBoolean: (index) =>
@getSetting(index)\toggle()
@updateSlot(index)
startBrowsingFolderPath: (index) =>
@getSetting(index)\startBrowsing()
editFolderPath: (index, path) =>
@getSetting(index)\setValue(path)
@updateSlot(index)
cycleSpinner: (index, direction) =>
setting = @getSetting(index)
setting\setIndex(setting\getIndex() + direction)
@updateSlot(index)
incrementInteger: (index) =>
@getSetting(index)\incrementValue()
@updateSlot(index)
decrementInteger: (index) =>
@getSetting(index)\decrementValue()
@updateSlot(index)
setInteger: (index, value) =>
@getSetting(index)\setValue(value)
@updateSlot(index)
cycleFolderPathSpinner: (index, direction) =>
setting = @getSetting(index)
setting\setIndex(setting\getIndex() + direction)
@updateSlot(index)
startBrowsingFolderPathSpinner: (index) =>
@getSetting(index)\startBrowsing()
editFolderPathSpinner: (index, path) =>
setting = @getSetting(index)
setting\setPath(setting.index, path)
@updateSlot(index)
editString: (index, value) =>
@getSetting(index)\setValue(value)
@updateSlot(index)
return Slots
| 28.733333 | 94 | 0.708817 |
b0b0f19be124546cb1a99e28ac0835c5ff2d1b86 | 7,997 | ----------------------------------------------------------------
-- A @{Block} for the main @{RomlDoc} compiled files.
--
-- @classmod MainBlock
-- @author Richard Voelker
-- @license MIT
----------------------------------------------------------------
local FunctionBlock
local DoBlock
local SpaceBlock
local DoubleBlock
local TableBlock
local MetatableBlock
local IfElseBlock
local IfBlock
local Line
local RequireLine
if game
pluginModel = script.Parent.Parent.Parent.Parent
FunctionBlock = require(pluginModel.com.blacksheepherd.code.FunctionBlock)
DoBlock = require(pluginModel.com.blacksheepherd.code.DoBlock)
SpaceBlock = require(pluginModel.com.blacksheepherd.code.SpaceBlock)
DoubleBlock = require(pluginModel.com.blacksheepherd.code.DoubleBlock)
TableBlock = require(pluginModel.com.blacksheepherd.code.TableBlock)
MetatableBlock = require(pluginModel.com.blacksheepherd.code.MetatableBlock)
IfElseBlock = require(pluginModel.com.blacksheepherd.code.IfElseBlock)
IfBlock = require(pluginModel.com.blacksheepherd.code.IfBlock)
Line = require(pluginModel.com.blacksheepherd.code.Line)
RequireLine = require(pluginModel.com.blacksheepherd.code.RequireLine)
else
FunctionBlock = require "com.blacksheepherd.code.FunctionBlock"
DoBlock = require "com.blacksheepherd.code.DoBlock"
SpaceBlock = require "com.blacksheepherd.code.SpaceBlock"
DoubleBlock = require "com.blacksheepherd.code.DoubleBlock"
TableBlock = require "com.blacksheepherd.code.TableBlock"
MetatableBlock = require "com.blacksheepherd.code.MetatableBlock"
IfElseBlock = require "com.blacksheepherd.code.IfElseBlock"
IfBlock = require "com.blacksheepherd.code.IfBlock"
Line = require "com.blacksheepherd.code.Line"
RequireLine = require "com.blacksheepherd.code.RequireLine"
-- {{ TBSHTEMPLATE:BEGIN }}
class MainRomlBlock
----------------------------------------------------------------
-- Constant for adding children to the variable @{Block}.
--
-- @prop BLOCK_VARS
----------------------------------------------------------------
@BLOCK_VARS = 1
----------------------------------------------------------------
-- Constant for adding children to the update function @{Block}.
--
-- @prop BLOCK_UPDATE_FUNCTIONS
----------------------------------------------------------------
@BLOCK_UPDATE_FUNCTIONS = 2
----------------------------------------------------------------
-- Constant for adding children to the object creation @{Block}.
--
-- @prop BLOCK_CREATION
----------------------------------------------------------------
@BLOCK_CREATION = 4
----------------------------------------------------------------
-- Constant for adding children to the update function call
-- @{Block}.
--
-- @prop BLOCK_FUNCTION_CALLS
----------------------------------------------------------------
@BLOCK_FUNCTION_CALLS = 8
----------------------------------------------------------------
-- Create the MainRomlBlock.
--
-- @tparam MainRomlBlock self
-- @tparam string name The name of the subclass for the
-- @{RomlDoc}
----------------------------------------------------------------
new: (name) =>
@_children = {}
table.insert @_children, RequireLine("com.blacksheepherd.roml", "RomlVar")
table.insert @_children, RequireLine("com.blacksheepherd.roml", "RomlDoc")
table.insert @_children, RequireLine("com.blacksheepherd.roml", "RomlObject")
@_extraRequiresBlock = SpaceBlock!
@_hasCustomObjectBuilderRequire = false
table.insert @_children, @_extraRequiresBlock
table.insert @_children, Line("local #{name}")
cBlock = DoBlock!
cBlock\AddChild Line("local _parent_0 = RomlDoc")
baseBlock = TableBlock("_base_0")
createFunctionBlock = FunctionBlock("_create", "self, parent, vars")
createFunctionBlock\AddChild Line("self._rootObject = RomlObject(self, parent)")
createFunctionBlock\AddChild Line("local objTemp")
@_varsBlock = SpaceBlock!
@_updateFunctionsBlock = SpaceBlock!
@_creationBlock = SpaceBlock!
@_functionCallsBlock = SpaceBlock!
createFunctionBlock\AddChild @_varsBlock
createFunctionBlock\AddChild @_updateFunctionsBlock
createFunctionBlock\AddChild @_creationBlock
createFunctionBlock\AddChild @_functionCallsBlock
baseBlock\AddChild createFunctionBlock
cBlock\AddChild baseBlock
cBlock\AddChild Line("_base_0.__index = _base_0")
cBlock\AddChild Line("setmetatable(_base_0, _parent_0.__base)")
metatableBlock = MetatableBlock("_class_0")
initFunctionBlock = FunctionBlock("__init", "self, parent, vars, ross")
initFunctionBlock\AddChild Line("return _parent_0.__init(self, parent, vars, ross)")
metatableBlock\AddChild DoubleBlock.TOP, initFunctionBlock
metatableBlock\AddChild DoubleBlock.TOP, Line("__base = _base_0")
metatableBlock\AddChild DoubleBlock.TOP, Line("__name = \"#{name}\"")
metatableBlock\AddChild DoubleBlock.TOP, Line("__parent = _parent_0")
indexFunctionBlock = FunctionBlock("__index", "cls, name")
indexFunctionBlock\AddChild Line("local val = rawget(_base_0, name)")
valueNilCheckBlock = IfElseBlock("val == nil")
valueNilCheckBlock\AddChild DoubleBlock.TOP, Line("return _parent_0[name]")
valueNilCheckBlock\AddChild DoubleBlock.BOTTOM, Line("return val")
indexFunctionBlock\AddChild valueNilCheckBlock
metatableBlock\AddChild DoubleBlock.BOTTOM, indexFunctionBlock
callFunctionBlock = FunctionBlock("__call", "cls, ...")
callFunctionBlock\AddChild Line("local _self_0 = setmetatable({}, _base_0)")
callFunctionBlock\AddChild Line("cls.__init(_self_0, ...)")
callFunctionBlock\AddChild Line("return _self_0")
metatableBlock\AddChild DoubleBlock.BOTTOM, callFunctionBlock
cBlock\AddChild metatableBlock
cBlock\AddChild Line("_base_0.__class = _class_0")
cBlock\AddChild Line("local self = _class_0")
newFunctionBlock = FunctionBlock("self.new", "parent, vars, ross")
newFunctionBlock\AddChild Line("return #{name}(parent, vars, ross)")
cBlock\AddChild newFunctionBlock
inheritanceIfBlock = IfBlock("_parent_0.__inherited")
inheritanceIfBlock\AddChild Line("_parent_0.__inherited(_parent_0, _class_0)")
cBlock\AddChild inheritanceIfBlock
cBlock\AddChild Line("#{name} = _class_0")
table.insert @_children, cBlock
table.insert @_children, Line("return #{name}")
----------------------------------------------------------------
-- Add a child to the create function of the subclass inside the
-- specified block.
--
-- @tparam MainRomlBlock self
-- @tparam string block One of @{BLOCK_VARS},
-- @{BLOCK_UPDATE_FUNCTIONS}, @{BLOCK_CREATION},
-- or @{BLOCK_FUNCTION_CALLS}.
-- @tparam Block/Line child The child to add.
----------------------------------------------------------------
AddChild: (block, child) =>
switch block
when @@BLOCK_VARS
@_varsBlock\AddChild child
when @@BLOCK_UPDATE_FUNCTIONS
@_updateFunctionsBlock\AddChild child
when @@BLOCK_CREATION
@_creationBlock\AddChild child
when @@BLOCK_FUNCTION_CALLS
@_functionCallsBlock\AddChild child
----------------------------------------------------------------
-- Adds the require for the @{CustomObjectBuilder} class to the
-- top of the @{RomlDoc} if it is not already there.
--
-- @tparam MainRomlBlock self
----------------------------------------------------------------
AddCustomObjectBuilderRequire: =>
unless @_hasCustomObjectBuilderRequire
@_hasCustomObjectBuilderRequire = true
@_extraRequiresBlock\AddChild RequireLine("com.blacksheepherd.customobject", "CustomObjectBuilder")
----------------------------------------------------------------
-- Render the MainRomlBlock and all children @{Block}s/@{Line}s.
--
-- @tparam MainRomlBlock self
----------------------------------------------------------------
Render: =>
buffer = ""
for child in *@_children
buffer ..= child\Render!
if child.__class.__name != "SpaceBlock" or child.__class.__name == "SpaceBlock" and #child._children > 0
buffer ..= "\n"
return buffer
-- {{ TBSHTEMPLATE:END }}
return MainRomlBlock
| 39.009756 | 107 | 0.65437 |
39a16129f405fe9535fc8a7fe6a7852c68972c45 | 2,509 | -- Copyright 2013-2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import style from howl.ui
style.define 'haml_element', 'keyword'
style.define 'haml_doctype', 'special'
style.define 'haml_id', 'constant'
howl.util.lpeg_lexer ->
blank = capture 'whitespace', space^1
operator = capture 'operator', S',=>-'
name = alpha * (alnum + S'_-')^0
ruby_interpolation = capture('operator', '#{') * sub_lex('ruby', '}') * capture('operator', '}')
dq_string = sequence({
capture('string', '"'),
any({
ruby_interpolation,
capture('string', any(P'\\"', complement('"')))
})^0,
capture('string', '"')
})
sq_string = capture 'string', span("'", "'")
string = any dq_string, sq_string
instance_var = capture 'member', '@' * name
ruby_key = capture 'key', any(P':' * name, name * ':')
attributes_halt = #S'%%.#'
hash_attributes = any ruby_key, blank, operator, string, instance_var, complement(S',}')^1, complement(P'}' + attributes_halt)
hash_attribute_list = capture('operator', '{') * hash_attributes^0 * (capture('operator', '}') + attributes_halt)
html_key = capture('key', (name + ':')^1) * capture('operator', '=')
html_attributes = any html_key, blank, operator, string, instance_var, complement(P')' + attributes_halt)
html_attribute_list = capture('operator', '(') * html_attributes^0 * (capture('operator', ')') + attributes_halt)
attributes = any hash_attribute_list, html_attribute_list
object_ref = capture('operator', '[') * any(ruby_key, instance_var, blank, operator, complement(']'))^0 * capture('operator', ']')
ruby_start = capture 'operator', S'&!'^0 * S'-='
ruby_finish = eol - B','
ruby = ruby_start * blank * sub_lex('ruby', ruby_finish)
escape = capture('operator', '\\') * (capture('default', 1) - eol)
comment = capture 'comment', any('/', '-#') * scan_through_indented!
doctype = capture 'haml_doctype', span('!!!', eol)
element = sequence {
capture('haml_element', '%' * name),
(attributes + object_ref)^-1,
capture('haml_element', S'/<>')^-1
}
classes = capture('class', '.' * name) * attributes^-1
id = capture('haml_id', "#" * name) * attributes^-1
filter = sequence {
capture('preproc', ':'),
sub_lex_by_pattern_match_time(name, 'operator', scan_through_indented!)
}
any {
escape
element,
classes,
id,
comment,
ruby,
ruby_interpolation,
filter,
operator,
doctype,
}
| 33.905405 | 132 | 0.636509 |
e444c70043f2e6b980be02280f30c718be0aee06 | 19,082 |
db = require "lapis.nginx.postgres"
import Model from require "lapis.db.model"
import with_query_fn, assert_queries from require "spec.helpers"
time = 1376377000
describe "lapis.db.model", ->
local queries
local query_mock
local restore_query
local old_date
setup ->
export ngx = { null: nil }
restore_query = with_query_fn (q) ->
table.insert queries, (q\gsub("%s+", " ")\gsub("[\n\t]", " "))
-- try to find a mock
for k,v in pairs query_mock
if q\match k
return v
{}
old_date = os.date
os.date = (str) ->
old_date str, time
teardown ->
export ngx = nil
restore_query!
os.date = old_date
before_each ->
queries = {}
query_mock = {}
it "should select", ->
class Things extends Model
Things\select!
Things\select "where id = ?", 1234
Things\select fields: "hello" -- broke
Things\select "where id = ?", 1234, fields: "hello, world"
assert_queries {
'SELECT * from "things" '
'SELECT * from "things" where id = 1234'
'SELECT hello from "things" '
'SELECT hello, world from "things" where id = 1234'
}, queries
it "should find", ->
class Things extends Model
Things\find "hello"
Things\find cat: true, weight: 120
Things\find_all { 1,2,3,4,5 }
Things\find_all { "yeah" }
Things\find_all { }
Things\find_all { 1,2,4 }, "dad"
Things\find_all { 1,2,4 }, fields: "hello"
Things\find_all { 1,2,4 }, fields: "hello, world", key: "dad"
Things\find_all { 1,2,4 }, {
fields: "hello, world"
key: "dad"
where: {
color: "blue"
height: "10px"
}
}
class Things2 extends Model
@primary_key: {"hello", "world"}
Things2\find 1,2
assert_queries {
[[SELECT * from "things" where "id" = 'hello' limit 1]]
{
[[SELECT * from "things" where "cat" = TRUE AND "weight" = 120 limit 1]]
[[SELECT * from "things" where "weight" = 120 AND "cat" = TRUE limit 1]]
}
[[SELECT * from "things" where "id" in (1, 2, 3, 4, 5)]]
[[SELECT * from "things" where "id" in ('yeah')]]
[[SELECT * from "things" where "dad" in (1, 2, 4)]]
[[SELECT hello from "things" where "id" in (1, 2, 4)]]
[[SELECT hello, world from "things" where "dad" in (1, 2, 4)]]
{
[[SELECT hello, world from "things" where "dad" in (1, 2, 4) and "height" = '10px' AND "color" = 'blue']]
[[SELECT hello, world from "things" where "dad" in (1, 2, 4) and "color" = 'blue' AND "height" = '10px']]
}
{
[[SELECT * from "things" where "world" = 2 AND "hello" = 1 limit 1]]
[[SELECT * from "things" where "hello" = 1 AND "world" = 2 limit 1]]
}
}, queries
it "should paginate", ->
query_mock['COUNT%(%*%)'] = {{ c: 127 }}
query_mock['BLAH'] = {{ hello: "world"}}
class Things extends Model
p = Things\paginated [[where group_id = ? order by name asc]], 123
p\get_all!
assert.same 127, p\total_items!
assert.same 13, p\num_pages!
p\get_page 1
p\get_page 4
p2 = Things\paginated [[order by name asc]], 123, per_page: 25
p2\get_page 3
p3 = Things\paginated "", fields: "hello, world", per_page: 12
p3\get_page 2
p4 = Things\paginated fields: "hello, world", per_page: 12
p4\get_page 2
p5 = Things\paginated [[order by BLAH]]
iter = p5\each_page!
iter!
iter!
p6 = Things\paginated [[join whales on color = blue order by BLAH]]
p6\total_items!
p6\get_page 2
assert_queries {
'SELECT * from "things" where group_id = 123 order by name asc'
'SELECT COUNT(*) as c from "things" where group_id = 123 '
'SELECT * from "things" where group_id = 123 order by name asc limit 10 offset 0 '
'SELECT * from "things" where group_id = 123 order by name asc limit 10 offset 30 '
'SELECT * from "things" order by name asc limit 25 offset 50 '
'SELECT hello, world from "things" limit 12 offset 12 '
'SELECT hello, world from "things" limit 12 offset 12 '
'SELECT * from "things" order by BLAH limit 10 offset 0 '
'SELECT * from "things" order by BLAH limit 10 offset 10 '
'SELECT COUNT(*) as c from "things" join whales on color = blue '
'SELECT * from "things" join whales on color = blue order by BLAH limit 10 offset 10 '
}, queries
it "should ordered paginate", ->
import OrderedPaginator from require "lapis.db.pagination"
class Things extends Model
pager = OrderedPaginator Things, "id", "where color = blue"
res, np = pager\get_page!
res, np = pager\get_page 123
assert_queries {
'SELECT * from "things" where color = blue order by "id" ASC limit 10'
'SELECT * from "things" where "id" > 123 and (color = blue) order by "id" ASC limit 10'
}, queries
it "should ordered paginate with multiple keys", ->
import OrderedPaginator from require "lapis.db.pagination"
class Things extends Model
query_mock['SELECT'] = { { id: 101, updated_at: 300 }, { id: 102, updated_at: 301 } }
pager = OrderedPaginator Things, {"id", "updated_at"}, "where color = blue"
res, next_id, next_updated_at = pager\get_page!
assert.same 102, next_id
assert.same 301, next_updated_at
pager\after!
pager\before!
pager\after 100
pager\before 32
pager\after 100, 200
pager\before 32, 42
assert_queries {
'SELECT * from "things" where color = blue order by "id" ASC, "updated_at" ASC limit 10'
'SELECT * from "things" where color = blue order by "id" ASC, "updated_at" ASC limit 10'
'SELECT * from "things" where color = blue order by "id" DESC, "updated_at" DESC limit 10'
'SELECT * from "things" where "id" > 100 and (color = blue) order by "id" ASC, "updated_at" ASC limit 10'
'SELECT * from "things" where "id" < 32 and (color = blue) order by "id" DESC, "updated_at" DESC limit 10'
'SELECT * from "things" where "id" > 100 and "updated_at" > 200 and (color = blue) order by "id" ASC, "updated_at" ASC limit 10'
'SELECT * from "things" where "id" < 32 and "updated_at" < 42 and (color = blue) order by "id" DESC, "updated_at" DESC limit 10'
}, queries
it "should create model", ->
class Things extends Model
query_mock['INSERT'] = { { id: 101 } }
thing = Things\create color: "blue"
assert.same { id: 101, color: "blue" }, thing
class TimedThings extends Model
@timestamp: true
thing2 = TimedThings\create hello: "world"
class OtherThings extends Model
@primary_key: {"id_a", "id_b"}
query_mock['INSERT'] = { { id_a: "hello", id_b: "world" } }
thing3 = OtherThings\create id_a: 120, height: "400px"
assert.same { id_a: "hello", id_b: "world", height: "400px"}, thing3
assert_queries {
[[INSERT INTO "things" ("color") VALUES ('blue') RETURNING "id"]]
{
[[INSERT INTO "timed_things" ("hello", "created_at", "updated_at") VALUES ('world', '2013-08-13 06:56:40', '2013-08-13 06:56:40') RETURNING "id"]]
[[INSERT INTO "timed_things" ("created_at", "hello", "updated_at") VALUES ('2013-08-13 06:56:40', 'world', '2013-08-13 06:56:40') RETURNING "id"]]
[[INSERT INTO "timed_things" ("created_at", "updated_at", "hello" ) VALUES ('2013-08-13 06:56:40', '2013-08-13 06:56:40', 'world') RETURNING "id"]]
[[INSERT INTO "timed_things" ("hello", "updated_at", "created_at") VALUES ('world', '2013-08-13 06:56:40', '2013-08-13 06:56:40') RETURNING "id"]]
[[INSERT INTO "timed_things" ("updated_at", "hello", "created_at") VALUES ('2013-08-13 06:56:40', 'world', '2013-08-13 06:56:40') RETURNING "id"]]
[[INSERT INTO "timed_things" ("updated_at", "created_at", "hello" ) VALUES ('2013-08-13 06:56:40', '2013-08-13 06:56:40', 'world') RETURNING "id"]]
}
{
[[INSERT INTO "other_things" ("height", "id_a") VALUES ('400px', 120) RETURNING "id_a", "id_b"]]
[[INSERT INTO "other_things" ("id_a", "height") VALUES (120, '400px') RETURNING "id_a", "id_b"]]
}
}, queries
it "should refresh model", ->
class Things extends Model
query_mock['SELECT'] = { { id: 123 } }
instance = Things\load { id: 123 }
instance\refresh!
assert.same { id: 123 }, instance
instance\refresh "hello"
assert.same { id: 123 }, instance
instance\refresh "foo", "bar"
assert.same { id: 123 }, instance
assert_queries {
'SELECT * from "things" where "id" = 123'
'SELECT "hello" from "things" where "id" = 123'
'SELECT "foo", "bar" from "things" where "id" = 123'
}, queries
it "should refresh model with composite primary key", ->
class Things extends Model
@primary_key: {"a", "b"}
query_mock['SELECT'] = { { a: "hello", b: false } }
instance = Things\load { a: "hello", b: false }
instance\refresh!
assert.same { a: "hello", b: false }, instance
instance\refresh "hello"
assert.same { a: "hello", b: false }, instance
assert_queries {
[[SELECT * from "things" where "a" = 'hello' AND "b" = FALSE]]
[[SELECT "hello" from "things" where "a" = 'hello' AND "b" = FALSE]]
}, queries
it "should update model", ->
class Things extends Model
thing = Things\load { id: 12 }
thing\update color: "green", height: 100
assert.same { height: 100, color: "green", id: 12 }, thing
thing2 = Things\load { age: 2000, sprit: true }
thing2\update "age"
class TimedThings extends Model
@primary_key: {"a", "b"}
@timestamp: true
thing3 = TimedThings\load { a: 2, b: 3 }
thing3\update! -- does nothing
-- thing3\update "what" -- should error set to null
thing3\update great: true -- need a way to stub date before testing
thing3.hello = "world"
thing3\update "hello", timestamp: false
thing3\update { cat: "dog" }, timestamp: false
assert_queries {
{
[[UPDATE "things" SET "height" = 100, "color" = 'green' WHERE "id" = 12]]
[[UPDATE "things" SET "color" = 'green', "height" = 100 WHERE "id" = 12]]
}
[[UPDATE "things" SET "age" = 2000 WHERE "id" IS NULL]]
{
[[UPDATE "timed_things" SET "updated_at" = '2013-08-13 06:56:40', "great" = TRUE WHERE "a" = 2 AND "b" = 3]]
[[UPDATE "timed_things" SET "great" = TRUE, "updated_at" = '2013-08-13 06:56:40' WHERE "a" = 2 AND "b" = 3]]
[[UPDATE "timed_things" SET "updated_at" = '2013-08-13 06:56:40', "great" = TRUE WHERE "b" = 3 AND "a" = 2]]
[[UPDATE "timed_things" SET "great" = TRUE, "updated_at" = '2013-08-13 06:56:40' WHERE "b" = 3 AND "a" = 2]]
}
[[UPDATE "timed_things" SET "hello" = 'world' WHERE "a" = 2 AND "b" = 3]]
[[UPDATE "timed_things" SET "cat" = 'dog' WHERE "a" = 2 AND "b" = 3]]
}, queries
it "should delete model", ->
class Things extends Model
thing = Things\load { id: 2 }
thing\delete!
thing = Things\load { }
thing\delete!
class Things2 extends Model
@primary_key: {"key1", "key2"}
thing = Things2\load { key1: "blah blag", key2: 4821 }
thing\delete!
assert_queries {
[[DELETE FROM "things" WHERE "id" = 2]]
[[DELETE FROM "things" WHERE "id" IS NULL]]
{
[[DELETE FROM "things" WHERE "key1" = 'blah blag' AND "key2" = 4821]]
[[DELETE FROM "things" WHERE "key2" = 4821 AND "key1" = 'blah blag']]
}
}, queries
it "should check unique constraint", ->
class Things extends Model
query_mock['SELECT 1'] = {{ yes: 1 }}
assert.same true, Things\check_unique_constraint "name", "world"
query_mock['SELECT 1'] = {}
assert.same false, Things\check_unique_constraint color: "red", height: 10
assert_queries {
[[SELECT 1 from "things" where "name" = 'world' limit 1]]
{
[[SELECT 1 from "things" where "height" = 10 AND "color" = 'red' limit 1]]
[[SELECT 1 from "things" where "color" = 'red' AND "height" = 10 limit 1]]
}
}, queries
it "should include other association", ->
class Things extends Model
class ThingItems extends Model
things = [Things\load { id: i, thing_id: 100 + i } for i=1,10]
ThingItems\include_in things, "thing_id"
ThingItems\include_in things, "thing_id", flip: true
ThingItems\include_in things, "thing_id", where: { dad: true }
ThingItems\include_in things, "thing_id", fields: "one, two, three"
assert_queries {
[[SELECT * from "thing_items" where "id" in (101, 102, 103, 104, 105, 106, 107, 108, 109, 110)]]
[[SELECT * from "thing_items" where "thing_id" in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)]]
[[SELECT * from "thing_items" where "id" in (101, 102, 103, 104, 105, 106, 107, 108, 109, 110) and "dad" = TRUE]]
[[SELECT one, two, three from "thing_items" where "id" in (101, 102, 103, 104, 105, 106, 107, 108, 109, 110)]]
}, queries
it "should create model with extend syntax", ->
m = Model\extend "the_things", {
timestamp: true
primary_key: {"hello", "world"}
constraints: {
hello: =>
}
}
assert.same "the_things", m\table_name!
assert.same {"hello", "world"}, { m\primary_keys! }
assert.truthy m.constraints.hello
describe "constraints", ->
it "should prevent update/insert for failed constraint", ->
query_mock['INSERT'] = { { id: 101 } }
class Things extends Model
@constraints: {
name: (val) => val == "hello" and "name can't be hello"
}
assert.same { nil, "name can't be hello"}, { Things\create name: "hello" }
thing = Things\load { id: 0, name: "hello" }
assert.same { nil, "name can't be hello"}, { thing\update "name" }
assert_queries { }, queries
it "should prevent create for missing field", ->
class Things extends Model
@constraints: {
name: (val) =>
"missing `name`" unless val
}
assert.same { nil, "missing `name`"}, { Things\create! }
it "should allow to update values on create and on update", ->
query_mock['INSERT'] = { { id: 101 } }
class Things extends Model
@constraints: {
name: (val, column, values) => values.name = 'changed from ' .. val
}
thing = Things\create name: 'create'
thing\update name: 'update'
assert_queries {
[[INSERT INTO "things" ("name") VALUES ('changed from create') RETURNING "id"]]
[[UPDATE "things" SET "name" = 'changed from update' WHERE "id" = 101]]
}, queries
describe "relations", ->
local models
before_each ->
models = {}
package.loaded.models = models
it "should make has_one getter based on class name", ->
query_mock['SELECT'] = { { id: 101 } }
models.Users = class extends Model
@primary_key: "id"
class Posts extends Model
@relations: {
{"user", has_one: "Users"}
}
post = Posts!
post.user_id = 123
assert post\get_user!
assert post\get_user!
assert_queries {
'SELECT * from "users" where "id" = 123 limit 1'
}, queries
it "should make has_one getter based on function", ->
called = 0
class Posts extends Model
@relations: {
{
"thing"
has_one: =>
called += 1
"yes"
}
}
post = Posts!
post.user_id = 123
assert.same "yes", post\get_thing!
assert.same "yes", post\get_thing!
assert.same 1, called
assert_queries { }, queries
it "should make has_one getters for extend syntax", ->
query_mock['SELECT'] = { { id: 101 } }
models.Users = class extends Model
@primary_key: "id"
m = Model\extend "the_things", {
relations: {
{"user", has_one: "Users"}
}
}
obj = m!
obj.user_id = 101
assert obj\get_user! == obj\get_user!
assert_queries {
'SELECT * from "users" where "id" = 101 limit 1'
}, queries
it "should make has_one getter flipped", ->
query_mock['SELECT'] = { { id: 101 } }
models.UserData = class extends Model
@primary_key: "user_id"
class Users extends Model
@relations: {
{"data", has_one: "UserData", flip: true}
}
user = Users!
user.id = 123
assert user\get_data!
assert_queries {
'SELECT * from "user_data" where "user_id" = 123 limit 1'
}, queries
it "should make has_many getter", ->
query_mock['SELECT'] = { { id: 101 } }
models.Posts = class extends Model
models.Users = class extends Model
@relations: {
{"posts", has_many: "Posts"}
{"more_posts", has_many: "Posts", where: {color: "blue"}}
}
user = models.Users!
user.id = 1234
user\get_posts!\get_page 1
user\get_posts!\get_page 2
user\get_more_posts!\get_page 2
user\get_posts(per_page: 44)\get_page 3
assert_queries {
'SELECT * from "posts" where "user_id" = 1234 limit 10 offset 0 '
'SELECT * from "posts" where "user_id" = 1234 limit 10 offset 10 '
{
[[SELECT * from "posts" where "user_id" = 1234 AND "color" = 'blue' limit 10 offset 10 ]]
[[SELECT * from "posts" where "color" = 'blue' AND "user_id" = 1234 limit 10 offset 10 ]]
}
'SELECT * from "posts" where "user_id" = 1234 limit 44 offset 88 '
}, queries
describe "enum", ->
import enum from require "lapis.db.model"
it "should create an enum", ->
e = enum {
hello: 1
world: 2
foo: 3
bar: 3
}
describe "with enum", ->
local e
before_each ->
e = enum {
hello: 1
world: 2
foo: 3
bar: 4
}
it "should get enum values", ->
assert.same "hello", e[1]
assert.same "world", e[2]
assert.same "foo", e[3]
assert.same "bar", e[4]
assert.same 1, e.hello
assert.same 2, e.world
assert.same 3, e.foo
assert.same 4, e.bar
it "should get enum for_db", ->
assert.same 1, e\for_db "hello"
assert.same 1, e\for_db 1
assert.same 2, e\for_db "world"
assert.same 2, e\for_db 2
assert.same 3, e\for_db "foo"
assert.same 3, e\for_db 3
assert.same 4, e\for_db "bar"
assert.same 4, e\for_db 4
assert.has_error ->
e\for_db "far"
assert.has_error ->
e\for_db 5
it "should get enum to_name", ->
assert.same "hello", e\to_name "hello"
assert.same "hello", e\to_name 1
assert.same "world", e\to_name "world"
assert.same "world", e\to_name 2
assert.same "foo", e\to_name "foo"
assert.same "foo", e\to_name 3
assert.same "bar", e\to_name "bar"
assert.same "bar", e\to_name 4
| 30.097792 | 155 | 0.581333 |
29cb1a11bb91a5b4888d48760ef2428e292975ba | 268 |
import Gtk from require "lgi"
if path = arg and unpack arg
import PreviewWindow from require "gifine.preview_window"
preview = PreviewWindow!
preview\set_frames_from_dir path
else
import LoadWindow from require "gifine.load_window"
LoadWindow!
Gtk.main!
| 19.142857 | 59 | 0.779851 |
02e6406c53a7ce35ccf8ddc7c3cf553f2ba29472 | 840 | parent = ...
split = (str, symbol="%s") -> [x for x in string.gmatch(str, "([^"..symbol.."]+)")]
root1 = (split parent, ".")[1]
tail = require(root1..".".."._lists._tail")["tail"]
head = require(root1..".".."._lists._head")["head"]
M = {}
-- check whether two list or nested lists are equal
M.equal_lists = (list1, list2) ->
condition1 = (type list1) == 'table'
condition2 = (type list2) == 'table'
return false if condition1 and not condition2
return false if condition2 and not condition1
return (list1 == list2) if (not condition1) and (not condition2)
-- Now, both inputs are lists
return false if #list1 != #list2
return true if #list1 == 0 and #list2 == 0
if M.equal_lists (head list1), (head list2)
return M.equal_lists (tail list1), (tail list2)
else
return false
return M | 36.521739 | 83 | 0.625 |
02511349e8de0b5d8a5d7d33538e441cd9578a3a | 4,548 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
--
-- This supports more efficient mappings of character (code points) <->
-- byte offsets for gap buffer contents, by caching offsets and thus
-- making scans shorter
ffi = require 'ffi'
bit = require 'bit'
require 'ljglibs.cdefs.glib'
tonumber = tonumber
band = bit.band
ffi.cdef [[
struct ao_mapping {
size_t c_offset;
size_t b_offset;
}
]]
NR_MAPPINGS = 20
IDX_LAST = NR_MAPPINGS - 1
MIN_SPAN_CHARS = 1000
MIN_SPAN_BYTES = 1500
zero_mapping = ffi.new 'struct ao_mapping'
mapping_for_char = (mappings, char_offset) ->
m = zero_mapping
for i = 0, IDX_LAST
nm = mappings[i]
break if nm.c_offset == 0 or nm.c_offset > char_offset
m = nm
m
mapping_for_byte = (mappings, byte_offset) ->
m = zero_mapping
for i = 0, IDX_LAST
nm = mappings[i]
break if nm.c_offset == 0 or nm.b_offset > byte_offset
m = nm
m
update_for = (mappings, char_offset, byte_offset) ->
idx = 0
for i = 0, IDX_LAST
nm = mappings[i]
return nm if nm.c_offset == char_offset -- already present
break if nm.c_offset == 0
break if nm.c_offset > char_offset
idx = i + 1
if idx == NR_MAPPINGS -- rebalancing time
idx = NR_MAPPINGS / 2
for i = idx + 1, IDX_LAST
mappings[i].c_offset = 0
m = mappings[idx]
m.c_offset = char_offset
m.b_offset = byte_offset
m
gb_char_offset = (gb, start_offset, end_offset) ->
idx = start_offset
idx += gb.gap_size if idx >= gb.gap_start
b_end = end_offset > gb.gap_start and (end_offset + gb.gap_size) or end_offset
c_offset = 0
p = gb.array
while idx < b_end
if idx >= gb.gap_start and idx < gb.gap_end
idx += gb.gap_size
idx = idx + 1
while p[idx] != 0 and band(p[idx], 0xc0) == 0x80 -- continuation byte
idx = idx + 1
c_offset += 1
c_offset
gb_byte_offset = (gb, start_offset, char_offset) ->
idx = start_offset
idx += gb.gap_size if idx >= gb.gap_start
p = gb.array
while char_offset > 0
if idx >= gb.gap_start and idx < gb.gap_end
idx += gb.gap_size
idx += 1
char_offset -= 1
while p[idx] != 0 and band(p[idx], 0xc0) == 0x80 -- continuation byte
idx += 1
delta = idx >= gb.gap_end and gb.gap_size or 0
(idx - start_offset) - delta
Offsets = {
char_offset: (gb, byte_offset) =>
m = mapping_for_byte @mappings, byte_offset
-- should we create a new mapping, closer this offset?
if (byte_offset - m.b_offset) > MIN_SPAN_BYTES and
(gb.size - byte_offset) > MIN_SPAN_BYTES
m_b_offset = byte_offset - (byte_offset % MIN_SPAN_BYTES)
-- position may be in the middle of a sequence here, so back up as needed
while m_b_offset > 0 and band(gb\get_ptr(m_b_offset, 1)[0], 0xc0) == 0x80
m_b_offset -= 1
c_offset = m.c_offset + gb_char_offset(gb, m.b_offset, m_b_offset)
m = update_for @mappings, c_offset, m_b_offset
tonumber m.c_offset + gb_char_offset(gb, m.b_offset, byte_offset)
byte_offset: (gb, char_offset) =>
m = mapping_for_char(@mappings, char_offset), char_offset
-- should we create a new mapping, closer this offset?
if char_offset - m.c_offset > MIN_SPAN_CHARS
m_c_offset = char_offset - (char_offset % MIN_SPAN_CHARS)
b_offset = m.b_offset + gb_byte_offset(gb, m.b_offset, m_c_offset - m.c_offset)
m = update_for(@mappings, m_c_offset, b_offset)
tonumber m.b_offset + gb_byte_offset(gb, m.b_offset, char_offset - m.c_offset)
adjust_for_insert: (byte_offset, bytes, characters) =>
mappings = @mappings
for i = 0, IDX_LAST
m = mappings[i]
if m.c_offset != 0 and m.b_offset > byte_offset
m.b_offset += bytes
m.c_offset += characters
adjust_for_delete: (byte_offset, bytes, characters) =>
mappings = @mappings
for i = 0, IDX_LAST
m = mappings[i]
if m.c_offset != 0 and m.b_offset > byte_offset
-- update the mapping if we can (mapping is outside of deletion)
if m.b_offset > byte_offset + bytes
m.b_offset -= bytes
m.c_offset -= characters
else
-- otherwise invalidate this and subsequent mappings
@invalidate_from m.b_offset
break
invalidate_from: (byte_offset) =>
mappings = @mappings
for i = 0, IDX_LAST
nm = mappings[i]
nm.c_offset = 0 if nm.b_offset > byte_offset
}
-> setmetatable { mappings: ffi.new "struct ao_mapping[#{NR_MAPPINGS}]" }, __index: Offsets
| 28.074074 | 91 | 0.66029 |
029876b286287710e59a56e4f512895e8972a340 | 2,033 |
colors = require "ansicolors"
import insert from table
config = require("lapis.config").get!
local *
flatten_params_helper = (params, out = {}, sep= ", ")->
return {"{}"} unless params
insert out, "{ "
for k,v in pairs params
insert out, tostring k
insert out, ": "
if type(v) == "table"
flatten_params v, out
else
insert out, ("%q")\format v
insert out, sep
-- remove last ", "
out[#out] = nil if out[#out] == sep
insert out, " }"
out
flatten_params = (params) ->
table.concat flatten_params_helper params
query = do
log_tpl = colors("%{bright}%{cyan}SQL: %{reset}%{magenta}%s%{reset}")
(q) ->
l = config.logging
return unless l and l.queries
print log_tpl\format q
request = (r) ->
l = config.logging
return unless l and l.requests
import req, res from r
status = if res.statusline
res.statusline\match " (%d+) "
else
res.status or "200"
status = tostring status
status_color = if status\match "^2"
"green"
elseif status\match "^5"
"red"
else
"yellow"
t = "[%{#{status_color}}%s%{reset}] %{bright}%{cyan}%s%{reset} - %s"
cmd = "#{req.cmd_mth} #{req.cmd_url}"
print colors(t)\format status, cmd, flatten_params r.url_params
migration = do
log_tpl = colors("%{bright}%{yellow}Migrating: %{reset}%{green}%s%{reset}")
(name) -> print log_tpl\format name
notice = do
log_tpl = colors("%{bright}%{yellow}Notice: %{reset}%s")
(msg) -> print log_tpl\format msg
migration_summary = (count) ->
noun = if count == 1
"migration"
else
"migrations"
print colors("%{bright}%{yellow}Ran%{reset} #{count} %{bright}%{yellow}#{noun}")
start_server = (port, environment_name) ->
l = config.logging
return unless l and l.server
print colors("%{bright}%{yellow}Listening on port #{port}%{reset}")
if environment_name
print colors("%{bright}%{yellow}Environment: #{environment_name}%{reset}")
{ :request, :query, :migration, :migration_summary, :notice, :flatten_params,
:start_server }
| 22.842697 | 82 | 0.635514 |
6dd916e14c5027f60b75a852c97e734dca85d522 | 13,734 | script_name="Perspective"
script_description="Zeght's perspective.py but in moonscript by Alendt, with a few tweaks from Zahuczky"
script_author=""
script_version="1.1"
class Point
new: (@x, @y, @z) =>
if @z == nil
@z = 0
repr: () =>
if math.abs(@z) > 1e5
@x, @y, @z
else
@x, @y
add: (p) =>
return Point @x + p.x, @y + p.y, @z + p.z
sub: (p) =>
return Point @x - p.x, @y - p.y, @z - p.z
length: =>
return math.sqrt @x^2 + @y^2 + @z^2
rot_y: (a) =>
rot_v = Point @x * math.cos(a) - @z * math.sin(a), @y, @x * math.sin(a) + @z * math.cos(a)
return rot_v
rot_x: (a) =>
rot_v = Point @x, @y * math.cos(a) + @z * math.sin(a), -@y * math.sin(a) + @z * math.cos(a)
return rot_v
rot_z: (a) =>
rot_v = Point @x * math.cos(a) + @y * math.sin(a), -@x * math.sin(a) + @y * math.cos(a), @z
return rot_v
mul: (m) =>
return Point @x * m, @y * m, @z * m
vector = (a, b) ->
return Point b.x - a.x, b.y - a.y, b.z - a.z
vec_pr = (a, b) ->
return Point a.y * b.z - a.z * b.y, -a.x * b.z + a.z * b.x, a.x * b.y - a.y * b.x
sc_pr = (a, b) ->
return a.x*b.x + a.y*b.y + a.z*b.z
dist = (a, b) ->
return a\sub(b)\length!
round = (val, n) ->
if n
return math.floor((val * 10^n) + 0.5) / (10^n)
else
return math.floor(val+0.5)
intersect = (l1, l2) ->
if vec_pr(vector(l1[1], l1[2]), vector(l2[1], l2[2]))\length! == 0
return l1[1]\add(vector(l1[1], l1[2])\mul(1e30))
else
d = ((l1[1].x - l1[2].x)*(l2[1].y - l2[2].y) - (l1[1].y - l1[2].y)*(l2[1].x-l2[2].x))
x = (vec_pr(l1[1], l1[2]).z*(l2[1].x-l2[2].x) - vec_pr(l2[1], l2[2]).z*(l1[1].x-l1[2].x))
y = (vec_pr(l1[1], l1[2]).z*(l2[1].y-l2[2].y) - vec_pr(l2[1], l2[2]).z*(l1[1].y-l1[2].y))
x /= d
y /= d
return Point x, y
unrot = (coord_in, org, diag, get_rot) -> --diag=true, get_rot=false
screen_z = 312.5
shift = org\mul(-1)
coord = [c\add(shift) for c in *coord_in]
center = intersect({coord[1], coord[3]}, {coord[2], coord[4]})
center = Point(center.x, center.y, screen_z)
rays = [Point(c.x, c.y, screen_z) for c in *coord]
f = {}
for i = 0, 1
vp1 = vec_pr(rays[1 + i], center)\length!
vp2 = vec_pr(rays[3 + i], center)\length!
a = rays[1 + i]
c = rays[3 + i]\mul(vp1/vp2)
m = a\add(c)\mul(0.5)
r = center.z/m.z
a = a\mul(r)
c = c\mul(r)
table.insert(f, a)
table.insert(f, c)
a, c, b, d = f[1], f[2], f[3], f[4]
ratio = math.abs(dist(a, b) / dist(a, d))
diag_diff = (dist(a, c) - dist(b, d)) / (dist(a, c) + dist(b, d))
n = vec_pr(vector(a,b), vector(a,c))
n0 = vec_pr(vector(rays[1], rays[2]), vector(rays[1], rays[3]))
if sc_pr(n, n0) > 0 export flip = 1 else export flip = -1
if not get_rot
if diag return diag_diff else return ratio
if flip < 0
return nil
fry = math.atan(n.x/n.z)
s = ""
s = s.."\\fry"..round((-fry / math.pi * 180), 2)
export debfry = round((-fry / math.pi * 180), 2)
rot_n = n\rot_y(fry)
frx = -math.atan(rot_n.y/rot_n.z)
if n0.z < 0
frx += math.pi
s = s.."\\frx"..round((-frx / math.pi * 180), 2)
export debfrx = round((-frx / math.pi * 180), 2)
n = vector(a, b)
ab_unrot = vector(a, b)\rot_y(fry)\rot_x(frx)
ac_unrot = vector(a, c)\rot_y(fry)\rot_x(frx)
ad_unrot = vector(a, d)\rot_y(fry)\rot_x(frx)
frz = math.atan2(ab_unrot.y, ab_unrot.x)
s = s.."\\frz"..round((-frz / math.pi * 180), 2)
export debfrz = round((-frz / math.pi * 180), 2)
ad_unrot = ad_unrot\rot_z(frz)
fax = ad_unrot.x/ad_unrot.y
if math.abs(fax) > 0.01
s = s.."\\fax"..round(fax, 2)
return s
binary_search = (f, l, r, eps) ->
fl = f(l)
fr = f(r)
if fl <= 0 and fr >= 0
export op = (a, b) ->
if a > b
return true
else
return false
elseif fl >= 0 and fr <= 0
export op = (a, b) ->
if a < b
return true
else
return false
else
return nil
while (r - l > eps)
c = (l + r) / 2
if op(f(c), 0)
r = c
else
l = c
return (l + r) / 2
find_ex = (f, coord) ->
w_center = {0, 0}
w_size = 100000.0
iterations = math.floor(math.log(w_size * 100) / math.log(4))
s = 4
for k = 0, iterations-1
res = {}
for i = -s, s-1
x = w_center[1] + w_size*i/10
for j = -s, s-1
y = w_center[2] + w_size*j/10
table.insert(res, {unrot(coord, Point(x, y), true, false), x, y})
export ex = f(res)
w_center = {ex[2], ex[3]}
w_size = w_size / 3
return Point(ex[2], ex[3])
zero_on_ray = (coord, center, v, a, eps) ->
vrot = v\rot_z(a)
f = (x) ->
p = vrot\mul(x)\add(center)
return unrot(coord, p, true, false)
l = binary_search(f, 0, (center\length! + 1000000) / v\length!, eps)
if l == nil
return nil
p = vrot\mul(l)\add(center)
ratio = unrot(coord, p, false, false)
r = unrot(coord, p, true, false)
if r == nil
return nil
else
return p, ratio
find_rot = (t, n, t_center) ->
for i = 1, n
table.insert(t[i], dist(t_center, t[i][2]))
m = t[1][4]
r = t[1]
for i = 1, n
if m > t[i][4]
m = t[i][4]
r = t[i]
return r[1], r[2], r[3]
find_mn_point = (t) ->
j = 1
for k, v in pairs(t)
if t[j] != nil
j += 1
else break
rs = t[1][1]
rl = t[1]
for i = 1, j-1
if rs > t[i][1]
rs = t[i][1]
rl = t[i]
return rl
find_mx_point = (t) ->
j = 1
for k, v in pairs(t)
if t[j] != nil
j += 1
else break
rs = t[1][1]
rl = t[1]
for i = 1, j-1
if rs < t[i][1]
rs = t[i][1]
rl = t[i]
return rl
count_e = (t) ->
e = 0
for i = 1, 100
if t[i] != nil
e += 1
else break
return e
perspective = (line, tr_org, tr_center, tr_ratio) ->
clip = line.text\match("clip%b()")
if clip == nil
aegisub.log("\\clip missing")
coord = {}
for cx, cy in clip\gmatch("([-%d.]+).([-%d.]+)")
table.insert(coord, Point(cx, cy))
mn_point = find_ex(find_mn_point, coord)
mx_point = find_ex(find_mx_point, coord)
target_ratio = dist(coord[1], coord[2])/dist(coord[1], coord[4])
c = mn_point\add(mx_point)\mul(0.5)
v = mn_point\sub(mx_point)\rot_z(math.pi / 2)\mul(100000)
inf_p = c\add(v)
if unrot(coord, inf_p, true, false) > 0
mn_center = true
export center = mn_point
export other = mx_point
else
mn_center = false
export center = mx_point
export other = mn_point
v = other\sub(center)
rots = {}
steps = 100
for i = 0, steps-1
a = 2 * math.pi * i / steps
zero = {}
zero[1], zero[2] = zero_on_ray(coord, center, v, a, 1e-02)
if zero[1] != nil
p, ratio = zero[1], zero[2]
table.insert(rots, {ratio, p, a})
if tr_org
if line.text\match("org%b()")
export pos_org = line.text\match("org%b()")
elseif line.text\match("pos%b()")
export pos_org = line.text\match("pos%b()")
else
aegisub.log("\\org or \\pos missing")
aegisub.cancel!
px, py = pos_org\match("([-%d.]+).([-%d.]+)")
target_org = Point(px, py)
tf_tags = unrot(coord, target_org, true, true)
if tf_tags == nil
aegisub.log(tf_tags)
else
return ""..tf_tags
if count_e(rots) == 0
aegisub.log("No proper perspective found.")
aegisub.cancel!
if tr_center
t_center = coord[1]\add(coord[2])\add(coord[3])\add(coord[4])\mul(0.25)
ratio, p, a = find_rot(rots, count_e(rots), t_center)
tf_tags = unrot(coord, p, true, true)
if tf_tags == nil
aegisub.log(tf_tags)
else
return "\\org("..round(p.x, 1)..","..round(p.y, 1)..")"..tf_tags
if tr_ratio
segs = {}
for i = 0, count_e(rots)-1
if i == 0
i2 = count_e(rots)
if (rots[i2-1][1] - target_ratio) * (rots[i+1][1] - target_ratio) <= 0
table.insert(segs, {rots[i2-1][3], rots[i+1][3]})
elseif i == 1
i2 = 2
if (rots[i2-1][1] - target_ratio) * (rots[i+1][1] - target_ratio) <= 0
table.insert(segs, {rots[i2-1][3], rots[i+1][3]})
else
if (rots[i][1] - target_ratio) * (rots[i+1][1] - target_ratio) <= 0
table.insert(segs, {rots[i][3], rots[i+1][3]})
for i = 1, count_e(segs)
seg = {}
seg = {segs[i][1], segs[i][2]}
f = (x) ->
t_res = {}
t_res[1], t_res[2] = zero_on_ray(coord, center, v, x, 1e-05)
if t_res[1] != nil
p, ratio = t_res[1], t_res[2]
return (ratio - target_ratio)
else
return 1e7
a = binary_search(f, seg[1], seg[2], 1e-04)
if a == nil then
a = seg[1]
p, ratio = zero_on_ray(coord, center, v, a, 1e-05)
tf_tags = unrot(coord, p, true, true)
if tf_tags != nil
return "\\org("..round(p.x, 1)..","..round(p.y, 1)..")"..tf_tags
delete_old_tag = (line) ->
line.text = line.text\gsub("\\frx([-%d.]+)", "")\gsub("\\fry([-%d.]+)", "")\gsub("\\frz([-%d.]+)", "")\gsub("\\org%b()", "")\gsub("\\fax([-%d.]+)", "")\gsub("\\fay([-%d.]+)", "")
return line.text
aegi1 = (sub, sel) ->
for si, li in ipairs(sel)
line = sub[li]
result = perspective(line, true, false, false)
line.text = delete_old_tag(line)
line.text = line.text\gsub("\\clip", result.."\\clip")
sub[li] = line
if debfry > 90 and debfry < 270 aegisub.debug.out("Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
elseif debfry > -270 and debfry < -90 aegisub.debug.out("Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
elseif debfrx > 90 and debfrx < 270 aegisub.debug.out("Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
elseif debfrx > -270 and debfrx < -90 aegisub.debug.out("Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
elseif debfrz > 90 or debfrz < -90 aegisub.debug.out("Uh-oh! Seems like your text was rotated a lot! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
aegi2 = (sub, sel) ->
for si, li in ipairs(sel)
line = sub[li]
result = perspective(line, false, true, false)
line.text = delete_old_tag(line)
line.text = line.text\gsub("\\clip", result.."\\clip")
sub[li] = line
if debfry > 90 and debfry < 270 aegisub.debug.out("Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
elseif debfry > -270 and debfry < -90 aegisub.debug.out("Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
elseif debfrx > 90 and debfrx < 270 aegisub.debug.out("Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
elseif debfrx > -270 and debfrx < -90 aegisub.debug.out("Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
elseif debfrz > 90 or debfrz < -90 aegisub.debug.out("Uh-oh! Seems like your text was rotated a lot! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
aegi3 = (sub, sel) ->
for si, li in ipairs(sel)
line = sub[li]
result = perspective(line, false, false, true)
line.text = delete_old_tag(line)
line.text = line.text\gsub("\\clip", result.."\\clip")
sub[li] = line
if debfry > 90 and debfry < 270 aegisub.debug.out("Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
elseif debfry > -270 and debfry < -90 aegisub.debug.out("Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
elseif debfrx > 90 and debfrx < 270 aegisub.debug.out("Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
elseif debfrx > -270 and debfrx < -90 aegisub.debug.out("Uh-oh! Seems like your text was mirrored! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
elseif debfrz > 90 or debfrz < -90 aegisub.debug.out("Uh-oh! Seems like your text was rotated a lot! Are you sure that's what you wanted? Here's a reminder: You need to draw your clip in a manner, where the first point of your clip is the upper left, then going clockwise from there.")
aegisub.register_macro("Perspective/Transform for target org", "Transform for target org", aegi1)
aegisub.register_macro("Perspective/Transforms near center of tetragon", "Transforms near center of tetragon", aegi2)
aegisub.register_macro("Perspective/Transforms with target ratio", "Transforms with target ratio", aegi3)
| 34.594458 | 286 | 0.623125 |
f4cd56a2c84813b1c08d8f4b4038171b51c49eb2 | 5,045 |
-- 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.
properties.Add('dpp2_transferent', {
Type: 'simple'
MenuLabel: 'gui.dpp2.property.transferent'
Order: 1670
MenuIcon: 'icon16/pencil_go.png'
Filter: (ent, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_REGULAR\GetBool()
return false if not IsValid(ent)
return #player.GetHumans() > 1 and ent\DPP2GetOwner() == ply and DPP2.cmd_perm_watchdog\HasPermission('dpp2_transferent')
MenuOpen: (option, ent, tr) =>
return if not IsValid(ent)
lply = LocalPlayer()
menu = option\AddSubMenu()
for ply in *player.GetHumans()
if ply ~= lply
exec = ->
return DPP2.NotifyError(nil, nil, 'message.dpp2.property.transferent.nolongervalid') if not IsValid(ent)
return DPP2.NotifyError(nil, nil, 'message.dpp2.property.transferent.noplayer') if not IsValid(ply)
RunConsoleCommand('dpp2_transferent', ent\EntIndex(), ply\UserID())
menu\AddOption(ply\Nick(), exec)\SetIcon(not ply\IsAdmin() and 'icon16/user.png' or 'icon16/shield.png')
})
properties.Add('dpp2_transfercontraption', {
Type: 'simple'
MenuLabel: 'gui.dpp2.property.transfercontraption'
Order: 1671
MenuIcon: 'icon16/folder_go.png'
Filter: (ent, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_REGULAR\GetBool()
return false if not IsValid(ent)
return #player.GetHumans() > 1 and ent\DPP2HasContraption() and ent\DPP2GetContraption()\HasOwner(ply) and DPP2.cmd_perm_watchdog\HasPermission('dpp2_transferent')
MenuOpen: (option, ent, tr) =>
return if not IsValid(ent)
lply = LocalPlayer()
menu = option\AddSubMenu()
for ply in *player.GetHumans()
if ply ~= lply
exec = ->
return DPP2.NotifyError(nil, nil, 'message.dpp2.property.transferent.nolongervalid') if not IsValid(ent)
return DPP2.NotifyError(nil, nil, 'message.dpp2.property.transferent.noplayer') if not IsValid(ply)
return DPP2.NotifyError(nil, nil, 'message.dpp2.property.transfercontraption.nolongervalid') if not ent\DPP2HasContraption()
RunConsoleCommand('dpp2_transfercontraption', ent\DPP2GetContraption()\GetID(), ply\UserID())
menu\AddOption(ply\Nick(), exec)\SetIcon(not ply\IsAdmin() and 'icon16/user.png' or 'icon16/shield.png')
})
properties.Add('dpp2_transfertoworldent', {
Type: 'simple'
MenuLabel: 'gui.dpp2.property.transfertoworldent'
Order: 1672
MenuIcon: 'icon16/world_go.png'
Filter: (ent, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_ADMIN\GetBool()
return false if not IsValid(ent)
return ent\DPP2GetOwner() == ply and DPP2.cmd_perm_watchdog\HasPermission('dpp2_transfertoworldent')
Action: (ent, tr) =>
return DPP2.NotifyError(nil, nil, 'message.dpp2.property.transferent.nolongervalid') if not IsValid(ent)
RunConsoleCommand('dpp2_transfertoworldent', ent\EntIndex())
})
properties.Add('dpp2_transfertoworldcontraption', {
Type: 'simple'
MenuLabel: 'gui.dpp2.property.transfertoworldcontraption'
Order: 1673
MenuIcon: 'icon16/world_link.png'
Filter: (ent, ply = LocalPlayer()) =>
return false if not DPP2.CL_ENABLE_PROPERTIES\GetBool()
return false if not DPP2.CL_ENABLE_PROPERTIES_ADMIN\GetBool()
return false if not IsValid(ent)
return ent\DPP2HasContraption() and ent\DPP2GetContraption()\HasOwner(ply) and DPP2.cmd_perm_watchdog\HasPermission('dpp2_transfertoworldcontraption')
Action: (ent, tr) =>
return DPP2.NotifyError(nil, nil, 'message.dpp2.property.transferent.nolongervalid') if not IsValid(ent)
return DPP2.NotifyError(nil, nil, 'message.dpp2.property.transfercontraption.nolongervalid') if not ent\DPP2HasContraption()
RunConsoleCommand('dpp2_transfertoworldcontraption', ent\DPP2GetContraption()\GetID())
})
if CLIENT
DPP2.cmd_existing.transfertoworld = true
DPP2.cmd_existing.transferunfallback = true
| 44.254386 | 165 | 0.760357 |
9c7cc4d6e7ac7060ecb6e63ee00f0384796a8b5e | 5,995 | {:delegate_to} = howl.util.table
base1 = '#93a1a1'
base2 = '#eee8d5'
base3 = '#fdf6e3'
base00 = '#657b83'
base01 = '#586e75'
base02 = '#073642'
yellow = '#b58900'
orange = '#cb4b16'
red = '#dc322f'
magenta = '#d33682'
violet = '#6c71c4'
blue = '#268bd2'
cyan = '#2aa198'
green = '#859900'
background = base3
current = base2
selection = lightblue
comment = base1
string = cyan
number = blue
keyword = green
class_name = yellow
operator = base00
member = base02
key = blue
-- General styling for context boxes (editor, command_line)
content_box = {
background:
color: background
border:
width: 1
color: base1
border_right:
width: 3
color: base1
border_bottom:
width: 3
color: base1
header:
background:
image:
path: theme_file('sprinkles.png')
border_bottom:
color: base1
color: brown
font: bold: true
padding: 1
footer:
background:
color: base2
border_top:
color: base1
color: brown
font: bold: true
padding: 1
}
return {
window:
background:
image:
path: theme_file('lightpaperfibers.png')
status:
font: bold: true, italic: true
color: blue
info: color: green
warning: color: orange
error: color: red
:content_box
popup: {
background:
color: current
border:
color: base1
alpha: 0.5
}
editor: delegate_to content_box, {
indicators:
default:
color: yellow
title:
color: yellow
font: bold: true, italic: true
current_line:
background: current
gutter:
color: base1
background:
color: base2
alpha: 0.7
}
flairs:
indentation_guide:
type: flair.PIPE,
foreground: '#aaaaaa',
line_type: 'dotted'
line_width: 1
indentation_guide_1:
type: flair.PIPE,
foreground: blue,
foreground_alpha: 0.3
line_width: 1
indentation_guide_2:
type: flair.PIPE,
foreground: green,
foreground_alpha: 0.4
line_width: 1
indentation_guide_3:
type: flair.PIPE,
foreground: green,
line_type: 'dotted'
line_width: 1
edge_line:
type: flair.PIPE,
foreground: green,
foreground_alpha: 0.3,
line_type: 'solid'
line_width: 0.5
search:
type: highlight.ROUNDED_RECTANGLE
foreground: darkgreen
foreground_alpha: 1
background: blue
text_color: white
height: 'text'
search_secondary:
foreground: lightblue
line_width: 1
type: highlight.ROUNDED_RECTANGLE
background: black
background_alpha: 0.6
text_color: white
height: 'text'
replace_strikeout:
type: highlight.ROUNDED_RECTANGLE
foreground: black
background: red
text_color: lightgray
background_alpha: 0.7
height: 'text'
brace_highlight:
type: highlight.ROUNDED_RECTANGLE
text_color: white
background: blue
background_alpha: 0.6
height: 'text'
brace_highlight_secondary:
type: highlight.RECTANGLE
foreground: blue
line_width: 1
height: 'text'
list_selection:
type: highlight.RECTANGLE
foreground: blue
foreground_alpha: 0.5
background: blue
background_alpha: 0.2
list_highlight:
type: highlight.UNDERLINE
text_color: black
line_width: 2
cursor:
type: highlight.RECTANGLE
background: base01
width: 2
height: 'text'
block_cursor:
type: highlight.RECTANGLE,
background: base01
text_color: background
height: 'text',
min_width: 'letter'
selection:
type: highlight.ROUNDED_RECTANGLE
background: selection
background_alpha: 0.6
min_width: 'letter'
styles:
default:
color: black
red: color: red
green: color: green
yellow: color: yellow
blue: color: blue
magenta: color: magenta
cyan: color: cyan
comment:
font: italic: true
color: comment
variable: color: yellow
label:
color: orange
font: italic: true
line_number:
color: base1
background: base2
key:
color: key
font: bold: true
char: color: green
wrap_indicator: 'blue'
fdecl:
color: key
font: bold: true
keyword:
color: keyword
font: bold: true
class:
color: class_name
font:
bold: true
type_def:
color: class_name
font:
bold: true
size: 'large'
family: 'Purisa,Latin Modern Sans'
definition: color: yellow
function: color: blue
number:
color: number
font: bold: true
operator:
color: operator
font: bold: true
preproc: color: red
special:
color: cyan
font: bold: true
tag: color: purple
type:
color: class_name
font: bold: true
member:
color: member
font: bold: true
info: color: blue
constant: color: orange
string: color: string
regex:
color: green
background: wheat
embedded:
background: wheat
color: black
-- Markup and visual styles
error:
font:
italic: true
bold: true
color: red
warning:
font: italic: true
color: orange
h1:
color: white
background: yellow
font: bold: true
h2:
color: white
background: comment
h3:
color: violet
background: current
font: italic: true
emphasis:
font:
bold: true
italic: true
strong: font: italic: true
link_label:
color: blue
underline: true
link_url:
color: comment
table:
background: wheat
color: black
underline: true
addition: color: green
deletion: color: red
change: color: yellow
}
| 16.839888 | 59 | 0.590158 |
48c08f4b9f64447e664175de44cdf5d93e22b539 | 2,279 | DependencyControl = require("l0.DependencyControl") {
name: "ScrollHandler"
description: "Library to save and load subtitle grid scrollbar positions on Windows"
author: "CoffeeFlux"
version: "1.0.0"
moduleName: "Flux.ScrollHandler"
url: "https://github.com/TypesettingTools/CoffeeFlux-Aegisub-Scripts/blob/master/modules/Flux.ScrollHandler.moon"
feed: "https://raw.githubusercontent.com/TypesettingTools/CoffeeFlux-Aegisub-Scripts/master/DependencyControl.json"
{
"ffi"
}
}
ffi = DependencyControl\requireModules!
if jit.os != 'Windows'
return class ScrollHandlerStub
new: =>
savePos: =>
loadPos: =>
version: =>
-- WARNING: Hilarious hacks below
ffi.cdef [[
uintptr_t GetForegroundWindow();
uintptr_t SendMessageA(uintptr_t hWnd, uintptr_t Msg, uintptr_t wParam, uintptr_t lParam);
uintptr_t FindWindowExA(uintptr_t hWndParent, uintptr_t hWndChildAfter, uintptr_t lpszClass, uintptr_t lpszWindow);
]]
msgs = {
WM_VSCROLL: 0x0115
SBM_SETPOS: 0xE0
SBM_GETPOS: 0xE1
SB_THUMBPOSITION: 4
SB_ENDSCROLL: 8
SB_SETTEXT: 0x401
}
class ScrollHandler
new: =>
@scrollPositions = {}
checkHandle = =>
if not @handle
@handle = {}
@handle.App = ffi.C.GetForegroundWindow!
@handle.Container = ffi.C.FindWindowExA @handle.App, 0, ffi.cast('uintptr_t','wxWindowNR'), 0
@handle.SubsGrid = ffi.C.FindWindowExA @handle.Container, 0, 0, 0
@handle.ScrollBar = ffi.C.FindWindowExA @handle.SubsGrid, 0, 0, 0
@handle.App != 0
savePos: (key) =>
return unless checkHandle @
@scrollPositions[key] = tonumber ffi.C.SendMessageA @handle.ScrollBar, msgs.SBM_GETPOS, 0, 0
-- aegisub.dialog.status_msg string.format 'Jumpscroll %s: saved position %d'\format key, @scrollpos[key]
loadPos: (key) =>
return unless @scrollPositions[key] and checkHandle @
ffi.C.SendMessageA @handle.SubsGrid, msgs.WM_VSCROLL, msgs.SB_THUMBPOSITION, @handle.ScrollBar
ffi.C.SendMessageA @handle.ScrollBar, msgs.SBM_SETPOS, @scrollPositions[key], 0
ffi.C.SendMessageA @handle.SubsGrid, msgs.WM_VSCROLL, msgs.SB_ENDSCROLL, @handle.ScrollBar
-- aegisub.dialog.status_msg string.format 'Jumpscroll %s: scrolled to position %d'\format key, @scrollpos[key]
version: DependencyControl
return DependencyControl\register ScrollHandler | 34.014925 | 119 | 0.744625 |
e502a3e3c910cd9b73f35b6a45a71fa773fcd737 | 5,797 | ---------------------------------------------------------------------------
-- Environment ------------------------------------------------------------
---------------------------------------------------------------------------
import floor from math
import pairs, ipairs from _G
{ :isnumber, sigcheck:T } = require('typecheck')
---------------------------------------------------------------------------
-- Implementation ---------------------------------------------------------
---------------------------------------------------------------------------
isidx = (k) -> isnumber(k) and k >= 1 and floor(k) == k
ieach = (list, fn) -> for _, v in ipairs list do fn v
ieachi = (list, fn) -> for i, v in ipairs list do fn i, v
ieachr = (list, fn) -> for i = #list, 1, -1 do fn list[i]
each = (dict, fn) -> for _, v in pairs dict do fn v
eachk = (dict, fn) -> for k, v in pairs dict do fn k, v
imap = (list, fn) ->
t = {}
for i, v in ipairs list
t[i] = fn v
return t
map = (dict, fn) ->
t = {}
for k, v in pairs dict
t[isidx(k) and #t + 1 or k] = fn v
return t
imapi = (list, fn) ->
t = {}
for i, v in ipairs list
t[i] = fn(i, v)
return t
mapk = (dict, fn) ->
t = {}
for k, v in pairs dict
t[isidx(k) and #t + 1 or k] = fn k, v
return t
ifilter = (list, fn) ->
t = {}
for i, v in ipairs list
t[i] = v if fn v
return t
filter = (dict, fn) ->
t = {}
for k, v in pairs dict
t[isidx(k) and #t + 1 or k] = v if fn v
return t
ifilteri = (list, fn) ->
t = {}
for i, v in ipairs list
t[i] = v if fn(i, v)
return t
filterk = (dict, fn) ->
t = {}
for k, v in pairs dict
t[isidx(k) and #t + 1 or k] = v if fn k, v
return t
ireduce = (list, init, fn) ->
len = #list
return init if len == 0
r = fn(init, list[1])
for i = 2, len do r = fn r, list[i]
return r
reduce = (dict, init, fn) ->
r = init
for k, v in pairs dict do r = fn r, v
return r
reducek = (dict, init, fn) ->
r = init
for k, v in pairs dict do r = fn r, k, v
return r
indexof = (list, e) ->
for i, v in ipairs list do return i if v == e
return nil
index = (list, fn) ->
for i, v in ipairs list do return i if fn v
return nil
keyof = (dict, e) ->
for k, v in pairs dict do return k if v == e
return nil
key = (dict, fn) ->
for k, v in pairs dict do return k if fn v
return nil
first = (list, fn) ->
for i, v in ipairs list do return v if fn v
return nil
last = (list, fn) ->
for i = #list, 0, -1
v = list[i]
break if v == nil
return v if fn v
return nil
contains = (dict, e) ->
for k, v in pairs dict do return true if v == e
return false
find = (dict, fn) ->
for k, v in pairs dict do return v if fn k, v
return nil
all = (dict, fn) ->
for k, v in pairs dict do return false if not fn v
return true
any = (dict, fn) ->
for k, v in pairs dict do return true if fn v
return false
keys = (dict) ->
t = {}
for k, _ in pairs dict do t[#t + 1] = k
return t
values = (dict) ->
t = {}
for _, v in pairs dict do t[#t + 1] = v
return t
enpair = (dict) ->
t = {}
for _, v in ipairs dict do t[v[1]] = v[2]
return t
depair = (dict) ->
t = {}
for _, v in ipairs dict do t[v[1]] = v[2]
return t
unset = (dict, fn) ->
for k, v in pairs dict
dict[k] = nil if fn v
return dict
unsetk = (dict, fn) ->
for k, v in pairs dict
dict[k] = nil if fn k, v
return dict
removek = (dict, key) ->
v = dict[key]
dict[key] = nil
return v
copy = (dict) -> { k, v for k, v in pairs dict }
copyk = (dict, keys) -> { k, dict[k] for _, k in ipairs keys }
join = (l1, l2) ->
for i = 1, #l2 do l1[#l1 + 1] = l2[i]
return l1
merge = (d1, d2) ->
for k, v in pairs d2 do d1[k] = v
return d1
mergek = (d1, d2, keys) ->
for _, k in ipairs keys do d1[k] = d2[k]
return d1
extend = (d1, d2) ->
for k, v in pairs d2 do d1[k] = v if d1[k] == nil
return d1
override = (d1, d2) ->
for k, _ in pairs d1
v = d2[k]
d1[k] = v if v != nil
return d1
---------------------------------------------------------------------------
-- Interface --------------------------------------------------------------
---------------------------------------------------------------------------
merge {
ieach: T 'table, function', ieach
ieachi: T 'table, function', ieachi
ieachr: T 'table, function', ieachr
each: T 'table, function', each
eachk: T 'table, function', eachk
imap: T 'table, function', imap
map: T 'table, function', map
imapi: T 'table, function', imapi
mapk: T 'table, function', mapk
ifilter: T 'table, function', ifilter
filter: T 'table, function', filter
ifilteri: T 'table, function', ifilteri
filterk: T 'table, function', filterk
ireduce: T 'table, ?, function', ireduce
reduce: T 'table, ?, function', reduce
reducek: T 'table, ?, function', reducek
indexof: T 'table, any', indexof
index: T 'table, function', index
keyof: T 'table, any', keyof
key: T 'table, function', key
first: T 'table, function', first
last: T 'table, function', last
contains: T 'table, any', contains
find: T 'table, function', find
all: T 'table, function', all
any: T 'table, function', any
keys: T 'table', keys
values: T 'table', values
enpair: T 'table', enpair
depair: T 'table', depair
unset: T 'table, function', unset
unsetk: T 'table, function', unsetk
removek: T 'table, any', removek
copy: T 'table', copy
copyk: T 'table, table', copyk
join: T 'table, table', join
merge: T 'table, table', merge
mergek: T 'table, table', mergek
extend: T 'table, table', extend
override: T 'table, table', override
}, table
| 24.053942 | 75 | 0.500259 |