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
|
---|---|---|---|---|---|
99559ae54c580475d8bd71f25a75d14107d31d1e | 2,054 | curl = require"cURL"
ffi = require"ffi"
M = {}
M.curl_exec = (options) ->
handle = curl.easy()
for i, v in pairs(options)
handle["setopt_" .. i\lower()](handle, v)
result = handle\perform!
handle\close!
return result
M.curl_read_url = (url, in_options) ->
options = {}
data = ""
options["WRITEFUNCTION"] = (str) ->
data ..= str
return #str
options["URL"] = url
if in_options
for i, v in pairs(in_options)
options[i] = v
M.curl_exec(options)
return data
M.curl_multi_read = (in_options) ->
options = {}
addme = {}
ret = {}
for i, v in pairs(in_options)
if type(i) == "number"
ret[i] = ""
v["WRITEFUNCTION"] = (str) ->
ret[i] ..= str
return #str
addme[i] = curl.easy()
for i1, v1 in pairs(v)
addme[i]["setopt_" .. i1\lower()](addme[i], v1)
else
options[i\lower()] = v
handle = curl.multi(options)
for i, v in pairs(addme)
handle\add_handle(v)
while handle\perform() ~= 0
os.execute("sleep .1")
return ret
M.curl_post_url = (url, post_data, in_options) ->
options = {}
options["POST"] = 1
options["POSTFIELDS"] = post_data
--options["POSTFIELDSIZE"] = #post_data
if in_options
for i, v in pairs(in_options)
options[i] = v
M.curl_read_url(url, options)
M.curl_new_slist = (options) ->
return options
M.url_decode = (str) ->
str = string.gsub(str, "+", " ")
str = string.gsub(str, "%%(%x%x)", (h) -> string.char(tonumber(h,16)) )
str = string.gsub(str, "\r\n", "\n")
return str
M.url_encode = (str) ->
if (str)
str = string.gsub(str, "\n", "\r\n")
str = string.gsub(str, "([^%w %-%_%.%~])", (c) -> string.format("%%%02X", string.byte(c)))
str = string.gsub(str, " ", "+")
return str
M.gen_get_args = (tbl) ->
conv = {}
for i, v in pairs(tbl)
table.insert(conv, M.url_encode(tostring(i)) .. "=" .. M.url_encode(tostring(v)))
return table.concat(conv, "&")
M.gen_uri_args = (tbl) ->
conv = {}
for i, v in pairs(tbl)
table.insert(conv, M.url_encode(tostring(i)) .. ":" .. M.url_encode(tostring(v)))
return table.concat(conv, "+")
return M | 21.395833 | 92 | 0.604187 |
89325423ef8753ec5c12cac3c7064d9f5079537b | 5,838 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import signal, timer, config, command from howl
import style from howl.ui
tinsert = table.insert
paragraph_break_line = (line) ->
mode_check = line.buffer\mode_at(line.start_pos).is_paragraph_break
return mode_check(line) if mode_check
return true if line.is_blank or line\umatch '^[ \t]'
start_style = style.at_pos line.buffer, line.start_pos
start_style and start_style\contains 'embedded'
mode_allows_breaking = (line) ->
mode = line.buffer\mode_at line.start_pos
if mode and mode.line_is_reflowable
return mode\line_is_reflowable(line)
true
paragraph_at = (line) ->
lines = {}
start = line
start = start.previous if start.is_blank and start.previous
start = line.next if start.is_blank and line.next
return {} if start.is_blank
back = start
while back
tinsert lines, 1, back unless back.is_blank
break if paragraph_break_line back
back = back.previous
next = start.next
while next and not paragraph_break_line next
tinsert lines, next
next = next.next
lines
can_reflow = (line, limit) ->
return false unless mode_allows_breaking line
len = line.ulen
first_blank = line\find('[\t ]')
if len > limit
return false if not first_blank
return true if first_blank <= len
cut_off = first_blank or len
prev = line.previous
return true if prev and not prev.is_blank and prev.ulen + cut_off + 1 <= limit
next = line.next
if next and not next.is_blank
return true if next.ulen + cut_off + 1 <= limit
next_first_blank = next\find('%s')
return true if next_first_blank and len + next_first_blank <= limit
false
reflow_paragraph_at = (line, limit) ->
-- find the first line that need to be reflowed
return false unless can_reflow line, limit
lines = paragraph_at line
return false unless #lines > 0
start_line = nil
for p_line in *lines
if can_reflow p_line, limit
start_line = p_line
break
return false unless start_line -- no, we're good already
-- now find the end line
end_line = lines[#lines]
while end_line != start_line and not mode_allows_breaking(end_line)
end_line = end_line.previous
buffer = start_line.buffer
chunk = buffer\chunk start_line.start_pos, end_line.end_pos
orig_text = chunk.text
text = orig_text
has_eol = orig_text\ends_with buffer.eol
text = text\usub 1, text.ulen - 1 if has_eol
text = text\gsub buffer.eol, ' '
new_lines = {}
start_pos = 1
while start_pos and (start_pos + limit <= text.ulen)
start_search = start_pos + limit
i = start_search
while i > start_pos and not text[i].is_blank
i -= 1
if i == start_pos
i = text\ufind('[ \t]', start_search) or text.ulen + 1
if i
tinsert new_lines, text\usub start_pos, i - 1
start_pos = i + 1
tinsert(new_lines, text\usub(start_pos)) if start_pos <= text.ulen
reflowed = table.concat(new_lines, buffer.eol)
reflowed ..= buffer.eol if has_eol
reflowed ..= buffer.eol if start_pos == text.ulen + 1
if reflowed != orig_text
chunk.text = reflowed
return true
false
-------------------------------------------------------------------------------
-- reflow commands and auto handling
-------------------------------------------------------------------------------
config.define
name: 'hard_wrap_column'
description: 'The column at which to wrap text (hard-wrap)'
type_of: 'number'
default: 80
config.define
name: 'auto_reflow_text'
description: 'Whether to automatically reflow text according to `hard_wrap_column`'
type_of: 'boolean'
default: false
is_reflowing = false
do_reflow = (editor, line, reflow_at) ->
return if editor.buffer.read_only
is_reflowing = true
cur_pos = editor.cursor.pos
reflowed = reflow_paragraph_at line, reflow_at
editor.cursor.pos = cur_pos
is_reflowing = false
reflowed
command.register
name: 'editor-reflow-paragraph',
description: 'Reflows the current paragraph according to `hard_wrap_column`'
handler: ->
editor = howl.app.editor
cur_line = editor.current_line
paragraph = paragraph_at cur_line
if #paragraph > 0
hard_wrap_column = editor.buffer\config_at(cur_line.start_pos).hard_wrap_column
if do_reflow editor, cur_line, hard_wrap_column
log.info "Reflowed paragraph to max #{hard_wrap_column} columns"
else
log.info "Paragraph unchanged"
else
log.info 'Could not find paragraph to reflow'
reflow_check = (args) ->
return if args.buffer.read_only
editor = howl.app.editor
return unless editor
return if args.part_of_revision or not editor.buffer == args.buffer
at_pos = args.buffer\char_offset args.at_pos
config = args.buffer\config_at at_pos
return if is_reflowing or not config.auto_reflow_text
reflow_at = config.hard_wrap_column
if not reflow_at
log.error "`auto_reflow_text` enabled but `hard_wrap_column` is not set"
return
cur_style = style.at_pos args.buffer, math.max(at_pos - 1, 1)
return if cur_style and cur_style\contains 'embedded'
-- check whether the modification affects the current line
cur_line = editor.current_line
return unless cur_line
cur_start_pos = cur_line.byte_start_pos
cur_end_pos = cur_line.byte_end_pos
start_pos = args.at_pos
if start_pos >= cur_start_pos and start_pos <= cur_end_pos
-- it does, but can we reflow?
if can_reflow cur_line, reflow_at
-- can't do modification in callback so do it asap
timer.asap do_reflow, editor, cur_line, reflow_at
return true
signal.connect 'text-deleted', reflow_check
signal.connect 'text-inserted', (args) ->
reflow_check(args) unless args.text == args.buffer.eol
{
:paragraph_at
:can_reflow
:reflow_paragraph_at
}
| 29.336683 | 85 | 0.703323 |
a581b07a4f3ce5e5badfa57f1a057e2691ee4ed3 | 973 | export core = {
methane: 4 -- 1 in
energy: 100
glucose: 50
timer: 2
}
import methanogen from require "core/bacteria"
graph = require "core/graph"
love.graphics.setBackgroundColor .95, 1, .95
core.load = =>
print "hey"
math.randomseed os.time!
@cells = {}
@atoms = {}
for i = 0, 450
with love.graphics
@cells[i] = methanogen.make (math.random 0, .getWidth!), math.random 0, .getHeight!
core.update = (dt) =>
if love.keyboard.isDown "down"
@glucose -= 0.5
if love.keyboard.isDown "up"
@glucose += 0.5
@energy = @glucose - @methane * 0.5
@methane = @glucose / 2
@timer -= dt * 5
if @timer <= 0
graph\plot graph.points_a, 10 + @energy + (math.random -10, 10) / 10, 0
graph\plot graph.points_b, 10 + @methane + (math.random -10, 10) / 10, 1
@timer = 2
graph\update dt
for i = 0, #@cells
@cells[i]\update dt
core.draw = =>
for i = 0, #@cells
@cells[i]\draw!
graph\draw!
core | 17.375 | 89 | 0.593011 |
9a7f7e5777a81014b73646123e0295e7e982f2f3 | 12,456 | export script_name = "Interpolate Tags"
export script_description = "Interpolates values of selected tags"
export script_author = "Zeref"
export script_version = "0.0.3"
-- LIB
zf = require "ZF.main"
-- captures of all interpolable tags
tagsIpol = {
fs: "\\fs%s*(%d[%.%d]*)", fsp: "\\fsp%s*(%-?%d[%.%d]*)", fscx: "\\fscx%s*(%d[%.%d]*)"
fscy: "\\fscy%s*(%d[%.%d]*)", frz: "\\frz%s*(%-?%d[%.%d]*)", frx: "\\frx%s*(%-?%d[%.%d]*)"
fry: "\\fry%s*(%-?%d[%.%d]*)", fax: "\\fax%s*(%-?%d[%.%d]*)", fay: "\\fay%s*(%-?%d[%.%d]*)"
bord: "\\bord%s*(%d[%.%d]*)", xbord: "\\xbord%s*(%d[%.%d]*)", ybord: "\\ybord%s*(%d[%.%d]*)"
shad: "\\shad%s*(%-?%d[%.%d]*)", xshad: "\\xshad%s*(%-?%d[%.%d]*)", yshad: "\\yshad%s*(%-?%d[%.%d]*)"
blur: "\\blur%s*(%d[%.%d]*)", ["1c"]: "\\1c%s*(&?[Hh]%x+&?)", ["2c"]: "\\2c%s*(&?[Hh]%x+&?)"
["3c"]: "\\3c%s*(&?[Hh]%x+&?)", ["4c"]: "\\4c%s*(&?[Hh]%x+&?)", ["1a"]: "\\1a%s*(&?[Hh]%x+&?)"
["2a"]: "\\2a%s*(&?[Hh]%x+&?)", ["3a"]: "\\3a%s*(&?[Hh]%x+&?)", ["4a"]: "\\4a%s*(&?[Hh]%x+&?)"
alpha: "\\alpha%s*(&?[Hh]%x+&?)", pos: "\\pos%b()", move: "\\move%b()"
org: "\\org%b()", clip: "\\i?clip%b()"
}
-- interpolates all selected tags
ipolTags = (firstLine, lastLine, length, selectedTags, accel, layer) ->
-- if no tag is selected, returns nil
return nil if #selectedTags <= 0
-- gets the tag type
getTyper = (tag) ->
if tag\match "%dc"
return "color"
elseif tag\match("%da") or tag == "alpha"
return "alpha"
elseif tag == "pos" or tag == "move" or tag == "org" or tag == "clip"
return "other"
return "number"
-- does the interpolation from two values
makeIpol = (first, last, tag, typer = "number") ->
-- transforms values between commas into numbers
toNumber = (value, tagCurr) ->
args = {}
value = value\gsub("%s+", "")\gsub("\\#{tagCurr}%((.-)%)", "%1")\gsub "[^,]*", (i) ->
args[#args + 1] = tonumber i
return unpack args
if typer != "other"
ipol = {}
for k = 1, length
t = (k - 1) ^ accel / (length - 1) ^ accel
val = zf.util\interpolation(t, typer, first, last)
val = (typer != "color" and typer != "alpha") and zf.math\round(val) or val
ipol[#ipol + 1] = "\\#{tag}#{val}"
return ipol
interpol = {}
switch tag
when "pos"
assert first and last, "expected tag \" \\pos \""
fx, fy = toNumber(first, "pos")
lx, ly = toNumber(last, "pos")
for k = 1, length
t = (k - 1) ^ accel / (length - 1) ^ accel
px = zf.math\round zf.util\interpolation(t, "number", fx, lx)
py = zf.math\round zf.util\interpolation(t, "number", fy, ly)
interpol[k] = "\\pos(#{px},#{py})"
when "org"
assert first and last, "expected tag \" \\org \""
fx, fy = toNumber(first, "org")
lx, ly = toNumber(last, "org")
for k = 1, length
t = (k - 1) ^ accel / (length - 1) ^ accel
px = zf.math\round zf.util\interpolation(t, "number", fx, lx)
py = zf.math\round zf.util\interpolation(t, "number", fy, ly)
interpol[k] = "\\org(#{px},#{py})"
when "move"
-- gets the start and end time of the move tag
getTime = (args) -> if args[1] then args[1], args[2] elseif args[3] then args[3], args[4]
assert first and last, "expected tag \" \\move \""
fx1, fy1, fx2, fy2, ft1, ft2 = toNumber(first, "move")
lx1, ly1, lx2, ly2, lt1, lt2 = toNumber(last, "move")
tms, tme = getTime({ft1, ft2, lt1, lt2})
for k = 1, length
t = (k - 1) ^ accel / (length - 1) ^ accel
px1 = zf.math\round zf.util\interpolation(t, "number", fx1, lx1)
py1 = zf.math\round zf.util\interpolation(t, "number", fy1, ly1)
px2 = zf.math\round zf.util\interpolation(t, "number", fx2, lx2)
py2 = zf.math\round zf.util\interpolation(t, "number", fy2, ly2)
mve = "\\move(#{px1},#{py1},#{px2},#{py2}"
interpol[k] = (tms and tme) and "#{mve},#{tms},#{tme})" or "#{mve})"
when "clip"
assert first and last, "expected tag \" \\i?clip \""
cp = first\match("\\iclip") and "\\iclip" or "\\clip"
fv = zf.util\clip_to_draw first
lv = zf.util\clip_to_draw last
for k = 1, length
t = (k - 1) ^ accel / (length - 1) ^ accel
shape = zf.util\interpolation(t, "shape", fv, lv)
interpol[k] = "#{cp}(#{shape})"
return interpol
-- sets up the interpolation specifically
interpolations = {}
for s, sel in pairs selectedTags
for tag, cap in pairs tagsIpol
if tag == sel
typer = getTyper tag
getFirst = firstLine.tags\gsub("\\t%b()", "")\match cap
getLast = lastLine.tags\gsub("\\t%b()", "")\match cap
if typer != "other"
if getFirst and not getLast
getLast = lastLine.style[tag]
elseif getLast and not getFirst
getFirst = firstLine.style[tag]
interpolations[s] = (getFirst and getLast) and makeIpol(getFirst, getLast, tag, typer) or {}
else
interpolations[s] = makeIpol(getFirst, getLast, tag, "other") if layer == 1
-- concatenates the interpolated tag layers
concatIpol = {}
lens = [interpolations[k] and #interpolations[k] or 0 for k = 1, #interpolations]
table.sort lens, (a, b) -> a > b
len = lens[1] or 0
for k = 1, len
concatIpol[k] = ""
for i = 1, #interpolations
concatIpol[k] ..= interpolations[i] and (interpolations[i][k] or "") or ""
return concatIpol
-- Creates the entire structure for the interpolation
class CreateIpol
new: (subs, sel, selectedTags, elements) =>
@subs, @sel = subs, sel
@selectedTags = selectedTags
@ignoreText = elements.igt
@acc = elements.acc
-- index all selected lines
allLines: =>
lines = {}
for _, i in ipairs @sel
l = @subs[i]
-- checks if the lines are really text
text = zf.tags\remove("full", l.text)
assert not text\match("m%s+%-?%d[%.%-%d mlb]*"), "text expected"
assert text\gsub("%s+", "") != "", "text expected"
-- gets text metrics
meta, styles = zf.util\tags2styles(@subs, l)
karaskel.preproc_line(@subs, meta, styles, l)
-- fixes problems for different tags with equal values
l.text = l.text\gsub("\\c%s*(&?[Hh]%x+&?)", "\\1c%1")
l.text = l.text\gsub("\\fr%s*(%-?%d[%.%d]*)", "\\frz%1")
lines[#lines + 1] = l
return lines
-- get all selected lines
getLines: => @lines = @allLines!
-- splits the lines into tags and text and adds the style
sptLines: =>
@getLines!
cfs, afs = util.color_from_style, util.alpha_from_style
for k = 1, #@lines
splited = zf.text(@subs, @lines[k], @lines[k].text)\tags(false)
@lines[k] = {}
for t, tag in ipairs splited
@lines[k][t] = {
tags: tag.tags
text: tag.text_stripped_with_space
style: {
"fs": tag.styleref.fontsize
"fsp": tag.styleref.spacing
"fscx": tag.styleref.scale_x
"fscy": tag.styleref.scale_y
"frz": tag.styleref.angle
"bord": tag.styleref.outline
"xbord": 0
"ybord": 0
"shad": tag.styleref.shadow
"xshad": 0
"yshad": 0
"blur": 0
"frx": 0
"fry": 0
"fax": 0
"fay": 0
"1c": cfs tag.styleref.color1
"2c": cfs tag.styleref.color2
"3c": cfs tag.styleref.color3
"4c": cfs tag.styleref.color4
"1a": afs tag.styleref.color1
"2a": afs tag.styleref.color2
"3a": afs tag.styleref.color3
"4a": afs tag.styleref.color4
"alpha": afs tag.styleref.color1
}
}
-- gets the interpolation for all tag layers
getIpol: =>
@sptLines! -- gets the split line values
@interpolatedTags, len, lenTL = {}, #@lines, nil
if @ignoreText
lenTL = math.max(#@lines[1], #@lines[len])
for k = 1, lenTL
first = @lines[1][k] or @lines[1][#@lines[1]]
last = @lines[len][k] or @lines[len][#@lines[len]]
@interpolatedTags[k] = ipolTags(first, last, len, @selectedTags, @acc, k)
else
lenTL = math.min(#@lines[1], #@lines[len])
for k = 1, lenTL
first = @lines[1][k]
last = @lines[len][k]
@interpolatedTags[k] = ipolTags(first, last, len, @selectedTags, @acc, k)
-- configures and concatenates all output
concat: =>
@getIpol!
-- deletes the origin tags that were interpolated
deleteOld = (src, new) ->
for t, tag in pairs tagsIpol
-- hides transformations
src = src\gsub "\\t%b()", (v) ->
v = v\gsub "\\", "\\XT"
return v
if src\match(tag) and new\match(tag)
src = src\gsub tag, ""
return new .. src\gsub "\\XT", "\\"
@result = {}
for k, i in ipairs @sel
l = @subs[i]
@result[k] = {}
if @ignoreText
-- gets the line that has the most tag layers
mostTags = #@lines[1] > #@lines[#@lines] and @lines[1] or @lines[#@lines]
for t, tag in ipairs mostTags
inTag = @interpolatedTags[t] and (@interpolatedTags[t][k] or "") or ""
srTag = (@lines[k][t] and @lines[k][t].tags or "")\sub(2, -2)
nwTag = deleteOld(srTag, inTag)
@result[k][t] = "{#{nwTag}}" .. tag.text
else
for t, tag in ipairs @lines[k]
inTag = @interpolatedTags[t] and (@interpolatedTags[t][k] or "") or ""
srTag = tag.tags\sub(2, -2)
nwTag = deleteOld(srTag, inTag)
@result[k][t] = "{#{nwTag}}" .. tag.text
l.text = table.concat(@result[k])\gsub "{}", ""
@subs[i] = l
return @subs
main = (subs, sel) ->
inter = zf.config\load(zf.config\interface(script_name)(tagsIpol), script_name)
local buttons, elements
while true
buttons, elements = aegisub.dialog.display(inter, {"Ok", "Save", "Reset", "Cancel"}, {close: "Cancel"})
inter = switch buttons
when "Save"
zf.config\save(inter, elements, script_name, script_version)
zf.config\load(inter, script_name)
when "Reset"
zf.config\interface(script_name)(tagsIpol)
break if buttons == "Ok" or buttons == "Cancel"
selecteds = {}
for e, element in pairs elements
if e != "igt" and e != "acc"
selecteds[#selecteds + 1] = element == true and e or nil
aegisub.progress.task "Processing..."
subs = CreateIpol(subs, sel, selecteds, elements)\concat! if buttons == "Ok"
aegisub.register_macro script_name, script_description, main, (subs, sel) -> #sel > 1 | 46.133333 | 112 | 0.462588 |
17739825a745f74db1cde71bec1d9daa1ab971a2 | 477 | return (ASS, ASSFInst, yutilsMissingMsg, createASSClass, Functional, LineCollection, Line, logger, SubInspector, Yutils) ->
Indexed = createASSClass "Tag.Indexed", ASS.Number, {"value"}, {"number"}, {precision: 0, positive: true}
Indexed.cycle = (down) =>
min, max = @__tag.range[1], @__tag.range[2]
if down then
return @value <= min and @set(max) or @add -1
else
return @value >= max and @set(min) or @add 1
Indexed.lerp = nil
return Indexed
| 36.692308 | 123 | 0.660377 |
44e1d6770fc59007981b1d99226559a636201a57 | 114 |
if ngx
return { md5: ngx.md5 }
crypto = require "crypto"
md5 = (str) ->
crypto.digest "md5", str
{ :md5 }
| 10.363636 | 26 | 0.578947 |
af700e10d34f549da2c30c1b5010731bffd15a19 | 10,878 |
util = require "moonscript.util"
dump = require "moonscript.dump"
transform = require "moonscript.transform"
import NameProxy, LocalName from require "moonscript.transform.names"
import Set from require "moonscript.data"
import ntype, has_value from require "moonscript.types"
statement_compilers = require "moonscript.compile.statement"
value_compilers = require "moonscript.compile.value"
import concat, insert from table
import pos_to_line, get_closest_line, trim, unpack from util
mtype = util.moon.type
indent_char = " "
local Line, DelayedLine, Lines, Block, RootBlock
-- a buffer for building up lines
class Lines
new: =>
@posmap = {}
mark_pos: (pos, line=#@) =>
@posmap[line] = pos unless @posmap[line]
-- append a line or lines to the buffer
add: (item) =>
switch mtype item
when Line
item\render self
when Block
item\render self
else -- also captures DelayedLine
@[#@ + 1] = item
@
flatten_posmap: (line_no=0, out={}) =>
posmap = @posmap
for i, l in ipairs @
switch mtype l
when "string", DelayedLine
line_no += 1
out[line_no] = posmap[i]
line_no += 1 for _ in l\gmatch"\n"
out[line_no] = posmap[i]
when Lines
_, line_no = l\flatten_posmap line_no, out
else
error "Unknown item in Lines: #{l}"
out, line_no
flatten: (indent=nil, buffer={}) =>
for i = 1, #@
l = @[i]
t = mtype l
if t == DelayedLine
l = l\render!
t = "string"
switch t
when "string"
insert buffer, indent if indent
insert buffer, l
-- insert breaks between ambiguous statements
if "string" == type @[i + 1]
lc = l\sub(-1)
if (lc == ")" or lc == "]") and @[i + 1]\sub(1,1) == "("
insert buffer, ";"
insert buffer, "\n"
when Lines
l\flatten indent and indent .. indent_char or indent_char, buffer
else
error "Unknown item in Lines: #{l}"
buffer
__tostring: =>
-- strip non-array elements
strip = (t) ->
if "table" == type t
[strip v for v in *t]
else
t
"Lines<#{util.dump(strip @)\sub 1, -2}>"
-- Buffer for building up a line
-- A plain old table holding either strings or Block objects.
-- Adding a line to a line will cause that line to be merged in.
class Line
pos: nil
append_list: (items, delim) =>
for i = 1,#items
@append items[i]
if i < #items then insert self, delim
nil
append: (first, ...) =>
if Line == mtype first
-- print "appending line to line", first.pos, first
@pos = first.pos unless @pos -- bubble pos if there isn't one
@append value for value in *first
else
insert self, first
if ...
@append ...
-- todo: try to remove concats from here
render: (buffer) =>
current = {}
add_current = ->
buffer\add concat current
buffer\mark_pos @pos
for chunk in *@
switch mtype chunk
when Block
for block_chunk in *chunk\render Lines!
if "string" == type block_chunk
insert current, block_chunk
else
add_current!
buffer\add block_chunk
current = {}
else
insert current, chunk
if current[1]
add_current!
buffer
__tostring: =>
"Line<#{util.dump(@)\sub 1, -2}>"
class DelayedLine
new: (fn) =>
@prepare = fn
prepare: ->
render: =>
@prepare!
concat @
class Block
header: "do"
footer: "end"
export_all: false
export_proper: false
value_compilers: value_compilers
__tostring: =>
h = if "string" == type @header
@header
else
unpack @header\render {}
"Block<#{h}> <- " .. tostring @parent
new: (@parent, @header, @footer) =>
@_lines = Lines!
@_names = {}
@_state = {}
@_listeners = {}
with transform
@transform = {
value: .Value\bind self
statement: .Statement\bind self
}
if @parent
@root = @parent.root
@indent = @parent.indent + 1
setmetatable @_state, { __index: @parent._state }
setmetatable @_listeners, { __index: @parent._listeners }
else
@indent = 0
set: (name, value) =>
@_state[name] = value
get: (name) =>
@_state[name]
get_current: (name) =>
rawget @_state, name
listen: (name, fn) =>
@_listeners[name] = fn
unlisten: (name) =>
@_listeners[name] = nil
send: (name, ...) =>
if fn = @_listeners[name]
fn self, ...
declare: (names) =>
undeclared = for name in *names
is_local = false
real_name = switch mtype name
when LocalName
is_local = true
name\get_name self
when NameProxy then name\get_name self
when "table"
name[1] == "ref" and name[2]
when "string"
-- TODO: don't use string literal as ref
name
continue unless is_local or real_name and not @has_name real_name, true
-- put exported names so they can be assigned to in deeper scope
@put_name real_name
continue if @name_exported real_name
real_name
undeclared
whitelist_names: (names) =>
@_name_whitelist = Set names
name_exported: (name) =>
return true if @export_all
return true if @export_proper and name\match"^%u"
put_name: (name, ...) =>
value = ...
value = true if select("#", ...) == 0
name = name\get_name self if NameProxy == mtype name
@_names[name] = value
-- Check if a name is defined in the current or any enclosing scope
-- skip_exports: ignore names that have been exported using `export`
has_name: (name, skip_exports) =>
return true if not skip_exports and @name_exported name
yes = @_names[name]
if yes == nil and @parent
if not @_name_whitelist or @_name_whitelist[name]
@parent\has_name name, true
else
yes
is_local: (node) =>
t = mtype node
return @has_name(node, false) if t == "string"
return true if t == NameProxy or t == LocalName
if t == "table"
if node[1] == "ref" or (node[1] == "chain" and #node == 2)
return @is_local node[2]
false
free_name: (prefix, dont_put) =>
prefix = prefix or "moon"
searching = true
name, i = nil, 0
while searching
name = concat {"", prefix, i}, "_"
i = i + 1
searching = @has_name name, true
@put_name name if not dont_put
name
init_free_var: (prefix, value) =>
name = @free_name prefix, true
@stm {"assign", {name}, {value}}
name
-- add something to the line buffer
add: (item, pos) =>
with @_lines
\add item
\mark_pos pos if pos
item
-- todo: pass in buffer as argument
render: (buffer) =>
buffer\add @header
buffer\mark_pos @pos
if @next
buffer\add @_lines
@next\render buffer
else
-- join an empty block into a single line
if #@_lines == 0 and "string" == type buffer[#buffer]
buffer[#buffer] ..= " " .. (unpack Lines!\add @footer)
else
buffer\add @_lines
buffer\add @footer
buffer\mark_pos @pos
buffer
block: (header, footer) =>
Block self, header, footer
line: (...) =>
with Line!
\append ...
is_stm: (node) =>
statement_compilers[ntype node] != nil
is_value: (node) =>
t = ntype node
@value_compilers[t] != nil or t == "value"
-- compile name for assign
name: (node, ...) =>
if type(node) == "string"
node
else
@value node, ...
value: (node, ...) =>
node = @transform.value node
action = if type(node) != "table"
"raw_value"
else
node[1]
fn = @value_compilers[action]
unless fn
error {
"compile-error"
"Failed to find value compiler for: " .. dump.value node
node[-1]
}
out = fn self, node, ...
-- store the pos, creating a line if necessary
if type(node) == "table" and node[-1]
if type(out) == "string"
out = with Line! do \append out
out.pos = node[-1]
out
values: (values, delim) =>
delim = delim or ', '
with Line!
\append_list [@value v for v in *values], delim
stm: (node, ...) =>
return if not node -- skip blank statements
node = @transform.statement node
result = if fn = statement_compilers[ntype(node)]
fn self, node, ...
else
-- coerce value into statement
if has_value node
@stm {"assign", {"_"}, {node}}
else
@value node
if result
if type(node) == "table" and type(result) == "table" and node[-1]
result.pos = node[-1]
@add result
nil
stms: (stms, ret) =>
error "deprecated stms call, use transformer" if ret
{:current_stms, :current_stm_i} = @
@current_stms = stms
for i=1,#stms
@current_stm_i = i
@stm stms[i]
@current_stms = current_stms
@current_stm_i = current_stm_i
nil
splice: (fn) =>
lines = {"lines", @_lines}
@_lines = Lines!
@stms fn lines
class RootBlock extends Block
new: (@options) =>
@root = self
super!
__tostring: => "RootBlock<>"
root_stms: (stms) =>
unless @options.implicitly_return_root == false
stms = transform.Statement.transformers.root_stms self, stms
@stms stms
render: =>
-- print @_lines
buffer = @_lines\flatten!
buffer[#buffer] = nil if buffer[#buffer] == "\n"
table.concat buffer
format_error = (msg, pos, file_str) ->
line_message = if pos
line = pos_to_line file_str, pos
line_str, line = get_closest_line file_str, line
line_str = line_str or ""
(" [%d] >> %s")\format line, trim line_str
concat {
"Compile error: "..msg
line_message
}, "\n"
value = (value) ->
out = nil
with RootBlock!
\add \value value
out = \render!
out
tree = (tree, options={}) ->
assert tree, "missing tree"
scope = (options.scope or RootBlock) options
runner = coroutine.create ->
scope\root_stms tree
success, err = coroutine.resume runner
unless success
error_msg, error_pos = if type(err) == "table"
switch err[1]
when "user-error", "compile-error"
unpack err, 2
else
-- unknown error, bubble it
error "Unknown error thrown", util.dump error_msg
else
concat {err, debug.traceback runner}, "\n"
return nil, error_msg, error_pos or scope.last_pos
lua_code = scope\render!
posmap = scope._lines\flatten_posmap!
lua_code, posmap
-- mmmm
with data = require "moonscript.data"
for name, cls in pairs {:Line, :Lines, :DelayedLine}
data[name] = cls
{ :tree, :value, :format_error, :Block, :RootBlock }
| 22.805031 | 77 | 0.583471 |
eb4624c38c704ec3221b6b6f78e2587ec6232fbc | 1,477 | Caste = require('vendor/caste/lib/caste')
class Entity extends Caste
@count: 0
events: nil
new: (components) =>
-- Assign pseudo-random id
@id = (
string.format('%x', os.time()) .. '|' ..
string.format('%x', math.floor(math.random() * 100000000)) .. '|' ..
@@count
)
@@count += 1
@components = {}
@addMultiple(components)
init: () =>
set: (key, component) =>
unless component
component = key
key = component.type
isNew = not @has(key)
@components[key] = component
-- TODO: Make getter, rather than duplicate
@[key] = component
if isNew and @events then @events\emit('entity.component.add', @, key)
return @
add: (key, component) =>
unless component
component = key
key = component.type
if @has(key) then error "Entity already has component '#{key}'."
if @[key] then error "Entity already has property '#{key}'."
return @set(key, component)
addMultiple: (components = {}) =>
for key, component in pairs(components)
if type(key) == 'number'
@add(component)
else
@add(key, component)
return @
remove: (key) =>
if not @has(key) then error "Tried removing nonexistent component '#{key}' from entity."
@components[key] = nil
@[key] = nil
if @events then @events\emit('entity.component.remove', @, key)
return @
get: (key) => if key then @components[key] else @components
has: (...) =>
keys = { ... }
for key in *keys
if not @get(key) then return false
return true
| 21.405797 | 90 | 0.624238 |
bbcf11116d50758e01450337d38103f2d13cbb11 | 4,104 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, dispatch, interact from howl
import Window from howl.ui
describe 'interact', ->
run_in_coroutine = (f) ->
wrapped = coroutine.wrap -> f!
return wrapped!
before_each ->
if howl.app.window
howl.app.window.command_line\abort_all!
howl.app.window = Window!
after_each ->
howl.app.window.command_line\abort_all!
howl.app.window = nil
describe '.register(spec)', ->
it 'raises an error if any of the mandatory fields are missing', ->
assert.raises 'name', -> interact.register description: 'foo', factory: -> true
assert.raises 'description', -> interact.register name: 'foo', factory: -> true
assert.raises 'factory', -> interact.register name: 'foo', description: 'foo'
it 'accepts one of "factory" or "handler"', ->
assert.raises 'factory', -> interact.register
name: 'foo'
description: 'foo'
factory: -> true
handler: -> true
it '.unregister(name) removes the specified input', ->
interact.register name: 'foo', description: 'foo', factory: -> true
interact.unregister 'foo'
assert.is_nil interact.foo
context 'calling an interaction .<name>(...)', ->
before_each ->
interact.register
name: 'interaction_call'
description: 'calls passed in function'
handler: (f) -> f!
interaction_instance =
run: (@finish, f) => f(finish)
interact.register
name: 'interaction_with_factory',
description: 'calls passed in function f(finish)'
factory: -> moon.copy interaction_instance
after_each ->
interact.unregister 'interaction_call'
interact.unregister 'interaction_with_factory'
context 'for a spec with .handler', ->
local i1_spec
before_each ->
i1_spec =
name: 'interaction1'
description: 'interaction with handler'
handler: spy.new -> return 'r1', 'r2'
interact.register i1_spec
after_each ->
interact.unregister i1_spec.name
it 'calls the interaction handler(...), returns result', ->
multi_value = table.pack interact.interaction1 'arg1', 'arg2'
assert.spy(i1_spec.handler).was_called_with 'arg1', 'arg2'
assert.is_same {'r1', 'r2', n:2}, multi_value
context 'for a spec with .factory', ->
local i2_spec, i2_interactor
before_each ->
i2_interactor =
run: spy.new (@finish, ...) => return
i2_spec =
name: 'interaction2'
description: 'interaction with factory'
factory: -> i2_interactor
interact.register i2_spec
after_each ->
interact.unregister i2_spec.name
it '.<name>(...) invokes the interaction method run(finish, ...)', ->
run_in_coroutine -> table.pack interact.interaction2 'arg1', 'arg2'
assert.spy(i2_interactor.run).was_called 1
it '.<name>(...) returns results passed via finish(...)', ->
multi_value = nil
run_in_coroutine -> multi_value = table.pack interact.interaction2!
i2_interactor.finish 'r1', 'r2'
assert.is_same {'r1', 'r2', n:2}, multi_value
context 'nested transactions', ->
it 'raises an error when attempting to finishing not active interaction', ->
local captured_finish
capture_finish = (finish) -> captured_finish = finish
run_in_coroutine -> interact.interaction_with_factory capture_finish
finish1 = captured_finish
finish1!
assert.has_error finish1, 'Cannot finish - no running activities'
it 'allows cancelling outer interactions, when nested interactions present', ->
local captured_finish
capture_finish = (finish) -> captured_finish = finish
run_in_coroutine -> interact.interaction_with_factory capture_finish
run_in_coroutine -> interact.interaction_with_factory capture_finish
finish2 = captured_finish
assert.has_no_error finish2
| 34.487395 | 85 | 0.648148 |
dd3176b211c4545188855f63623eee494dbc2e3f | 1,581 | {:activities, :app, :mode, :sys, :interact, :Buffer} = howl
{:Process} = howl.io
class ChickenMode
new: =>
@lexer = bundle_load('chicken_lexer')
@completers = { 'chicken_completer', 'in_buffer' }
default_config:
complete: 'manual'
show_doc: (editor) =>
unless sys.find_executable 'chicken-doc'
log.warning 'Command chicken-doc not found'
return
successful, process = pcall Process, {
cmd: "chicken-doc -f #{app.editor.current_context.word}"
read_stdout: true
read_stderr: true
}
unless successful
log.error "Failed looking up the context: #{process}"
return
stdout, _ = activities.run_process { title: 'fetching docs with chicken-doc' }, process
items = [l for l in string.gmatch stdout, "%(([a-z%d%-%?%!%s]+)%)%s+"]
if #items == 0 then return
ln = #items == 1 and { selection: items[1] } or interact.select { :items, columns: { {header: 'Line'} } }
if ln == nil then return nil
successful, process = pcall Process, {
cmd: "chicken-doc -i #{ln.selection}"
read_stdout: true
read_stderr: true
}
unless successful
log.error "Failed looking up docs: #{process}"
return
stdout, _ = activities.run_process { title: 'fetching docs for selected element' }, process
unless stdout.is_empty
buf = Buffer mode.by_name 'default'
buf.text = stdout
return buf
structure: (editor) => -- which lines to show in the structure view
[l for l in *editor.buffer.lines when l\match '^%s*%(define' or l\match '^%s*%(ns%s']
| 30.403846 | 109 | 0.631879 |
3b5b713d5606827d30395ff60f2257005069271c | 3,857 | export modinfo = {
type: "command"
desc: "Ko farusu"
alias: {"kofar"}
func: getDoPlayersFunction (v) ->
Spawn ->
sizorz=4
removeOldDick(v.Character)
D = CreateInstance"Model"{
Parent: v.Character
Name: ConfigSystem("Get", "Ero-mei")
}
bg = CreateInstance"BodyGyro"{
Parent: v.Character.Torso
}
d = CreateInstance"Part"{
TopSurface: 0
BottomSurface: 0
Name: "Main"
Parent: D
FormFactor: 3
Size: Vector3.new(1,sizorz+0.5,1)
BrickColor: ConfigSystem("Get", "Ero-iro")
Position: v.Character.Head.Position
CanCollide: true
}
cy = CreateInstance"CylinderMesh"{
Parent: d
Scale: Vector3.new(1.05,1,1.05)
}
w = CreateInstance"Weld"{
Parent: v.Character.Head
Part0: d
Part1: v.Character.Head
C0: CFrame.new(0,-(0.6),1.8)*CFrame.Angles(math.rad(30),0,0)
}
c = CreateInstance"Part"{
Name: "Mush"
BottomSurface: 0
TopSurface: 0
FormFactor: 3
Size: Vector3.new(1,1,1)
CFrame: CFrame.new(d.Position)
BrickColor: ConfigSystem("Get", "Ero sentan no iro")
CanCollide: true
Parent: D
}
msm = CreateInstance"SpecialMesh"{
Parent: c
MeshType: "Head"
Scale: Vector3.new(1,0.6,1)
}
cw = CreateInstance"Weld"{
Parent: c
Part0: d
Part1: c
C0: CFrame.new(0,2.3,0)
}
ball1 = CreateInstance"Part"{
Parent: D
Name: "Left Ball"
BottomSurface: 0
TopSurface: 0
CanCollide: true
FormFactor: 3
Size: Vector3.new(1.2,1.2,1.2)
CFrame: CFrame.new(v.Character["Left Leg"].Position)
BrickColor: ConfigSystem("Get", "Ero-iro")
}
bsm = CreateInstance"SpecialMesh"{
Parent: ball1
MeshType: "Sphere"
}
b1w = CreateInstance"Weld"{
Parent: ball1
Part0: v.Character.Torso
Part1: ball1
C0: CFrame.new(-(0.6),-(1),-(0.8))
}
ball2 = CreateInstance"Part"{
Parent: D
Name: "Right Ball"
BottomSurface: 0
CanCollide: true
TopSurface: 0
FormFactor: 3
Size: Vector3.new(1.2,1.2,1.2)
CFrame: CFrame.new(v.Character["Right Leg"].Position)
BrickColor: ConfigSystem("Get", "Ero-iro")
}
b2sm = CreateInstance"SpecialMesh"{
Parent: ball2
MeshType: "Sphere"
}
b2w = CreateInstance"Weld"{
Parent: ball2
Part0: v.Character.Torso
Part1: ball2
C0: CFrame.new(0.6,-(1),-(0.8))
}
char = v.Character
t = char.Torso
lw= CreateInstance"Weld"{
Parent: t
Name: 'leftWeld'
Part0: t
Part1: char['Left Arm']
C0: CFrame.new(-(1.15),1,-(1)) *CFrame.Angles(math.rad(100),math.rad(10),math.rad(20))
}
rw= CreateInstance"Weld"{
Parent: t
Name: 'rightWeld'
Part0: t
Part1: char['Right Arm']
C0: CFrame.new(1.15,1,-(1)) *CFrame.Angles(math.rad(100),math.rad(-(10)),math.rad(-(20)))
}
while wait()
lw.C0=CFrame.new(-(1.15),1,-(1)) *CFrame.Angles(math.rad(100),math.rad(10),math.rad(20))
rw.C0=CFrame.new(1.15,1,-(1)) *CFrame.Angles(math.rad(100),math.rad(-(10)),math.rad(-(20)))
wait(0.05)
lw.C0=CFrame.new(-(1.15),0.8,-(1)) *CFrame.Angles(math.rad(95),math.rad(10),math.rad(20))
rw.C0=CFrame.new(1.15,0.8,-(1)) *CFrame.Angles(math.rad(95),math.rad(-(10)),math.rad(-(20)))
wait(0.05)
lw.C0=CFrame.new(-(1.15),0.6,-(1)) *CFrame.Angles(math.rad(90),math.rad(10),math.rad(20))
rw.C0=CFrame.new(1.15,0.6,-(1)) *CFrame.Angles(math.rad(90),math.rad(-(10)),math.rad(-(20)))
wait(0.05)
lw.C0=CFrame.new(-(1.15),0.4,-(1)) *CFrame.Angles(math.rad(85),math.rad(10),math.rad(20))
rw.C0=CFrame.new(1.15,0.4,-(1)) *CFrame.Angles(math.rad(85),math.rad(-(10)),math.rad(-(20)))
wait(0.05)
lw.C0=CFrame.new(-(1.15),0.2,-(1)) *CFrame.Angles(math.rad(80),math.rad(10),math.rad(20))
rw.C0=CFrame.new(1.15,0.2,-(1)) *CFrame.Angles(math.rad(80),math.rad(-(10)),math.rad(-(20)))
wait(0.05)
} | 29 | 96 | 0.606689 |
590ad150e5efb88f8153f90e467bc3f30dc81a01 | 163 | export class Vector
new: (x = 0, y = 0, a = 0) =>
@x = x
@y = y
@a = a
is_zero: =>
@x == 0 and @y == 0 and @a == 0
stop: =>
@x = 0
@y = 0
@a = 0 | 12.538462 | 33 | 0.374233 |
83a5b328ae770d31dd779c5079ef404621f931b2 | 720 | -- Copyright 2013-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
require 'ljglibs.cdefs.gobject'
glib = require 'howl.cdefs.glib'
C = ffi.C
callback3 = (handler) ->
ffi.cast('GCallback', ffi.cast('GCallback3', handler))
callback4 = (handler) ->
ffi.cast('GCallback', ffi.cast('GCallback4', handler))
return {
g_signal_connect3: (instance, signal, handler, data) ->
C.g_signal_connect_data(instance, signal, callback3(handler), ffi.cast('gpointer', data), nil, 0)
g_signal_connect4: (instance, signal, handler, data) ->
C.g_signal_connect_data(instance, signal, callback4(handler), ffi.cast('gpointer', data), nil, 0)
}
| 30 | 101 | 0.715278 |
14d49b25979d8bbff2543a760cacbd804d83c3ff | 1,189 |
local encode_base64, decode_base64, hmac_sha1
config = require"lapis.config".get!
if ngx
{:encode_base64, :decode_base64, :hmac_sha1} = ngx
else
mime = require "mime"
{ :b64, :unb64 } = mime
encode_base64 = (...) -> (b64 ...)
decode_base64 = (...) -> (unb64 ...)
if pcall require, "openssl.hmac"
openssl_hmac = require "openssl.hmac"
hmac_sha1 = (secret, str) ->
hmac = openssl_hmac.new secret, "sha1"
hmac\final str
else
crypto = require "crypto"
hmac_sha1 = (secret, str) ->
crypto.hmac.digest "sha1", str, secret, true
encode_with_secret = (object, secret=config.secret, sep=".") ->
json = require "cjson"
msg = encode_base64 json.encode object
signature = encode_base64 hmac_sha1 secret, msg
msg .. sep .. signature
decode_with_secret = (msg_and_sig, secret=config.secret) ->
json = require "cjson"
msg, sig = msg_and_sig\match "^(.*)%.(.*)$"
return nil, "invalid message" unless msg
sig = decode_base64 sig
unless sig == hmac_sha1(secret, msg)
return nil, "invalid message secret"
json.decode decode_base64 msg
{ :encode_base64, :decode_base64, :hmac_sha1, :encode_with_secret, :decode_with_secret }
| 26.422222 | 88 | 0.672834 |
757cd7436fce6123254710222d1cbbb1ffe01adb | 2,615 | -- Copyright 2012-2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import completion, config from howl
append = table.insert
load_completers = (buffer, context) ->
completers = {}
mode = buffer.mode or {}
for factories in *{buffer.completers, mode.completers}
if factories
for f in *factories
if type(f) == 'string'
completer = completion[f]
f = completer and completer.factory
error "`nil` completer set for #{buffer}" if not f
completer = f(buffer, context)
append(completers, completer) if completer
completers
at_most = (limit, t) ->
return t if #t <= limit
t2 = {}
for i = 1,limit
t2[#t2 + 1] = t[i]
t2
differentiate_by_case = (prefix, completions) ->
for i = 2, #completions
first = completions[i - 1]
second = completions[i]
if first.ulower == second.ulower
if second[1] == prefix[1]
completions[i - 1] = second
completions[i] = first
completions
class Completer
new: (buffer, pos) =>
@buffer = buffer
@context = buffer\context_at pos
@start_pos = @context.word.start_pos
@completers = load_completers buffer, @context
complete: (pos, limit = @buffer.config.completion_max_shown) =>
context = @context.start_pos == pos and @context or @buffer\context_at pos
seen = {}
completions = {}
for completer in *@completers
comps = completer\complete context
if comps
if comps.authoritive
completions = [c for c in *comps]
break
for comp in *comps
unless seen[comp]
append completions, comp
seen[comp] = true
prefix = context.word_prefix
return differentiate_by_case(prefix, at_most(limit, completions)), prefix
accept: (completion, pos) =>
chunk = @buffer\context_at(pos).word
chunk = @buffer\chunk(chunk.start_pos, pos - 1) unless @buffer.config.hungry_completion
chunk.text = completion
pos_after = chunk.start_pos + completion.ulen
if @buffer.mode.on_completion_accepted
pos = @buffer.mode\on_completion_accepted completion, @buffer\context_at(pos_after)
pos_after = pos if type(pos) == 'number'
pos_after
with config
.define
name: 'hungry_completion'
description: 'Whether completing an item will cause the current word to be replaced'
default: false
type_of: 'boolean'
.define
name: 'completion_max_shown'
description: 'Show at most this number of completions'
default: 10
type_of: 'number'
return Completer
| 26.683673 | 91 | 0.658509 |
e5548f8a96eac83b2e928e009fd458ffb3ef4b5c | 317 | require "sitegen"
tools = require "sitegen.tools"
sitegen.create_site =>
@current_version = "0.0.10"
@title = "SCSS Compiler in PHP"
scssphp = tools.system_command "pscss < %s > %s", "css"
build scssphp, "style.scss", "style/style.css"
deploy_to "[email protected]", "www/scssphp/"
add "docs/index.md"
| 19.8125 | 57 | 0.66877 |
5e7b0dce156da1b03db74922edbef476f60a4934 | 2,835 |
import with_dev from require "spec.helpers"
-- TODO: add specs for windows equivalents
describe "moonc", ->
local moonc
dev_loaded = with_dev ->
moonc = require "moonscript.cmd.moonc"
same = (fn, a, b)->
assert.same b, fn a
it "should normalize dir", ->
same moonc.normalize_dir, "hello/world/", "hello/world/"
same moonc.normalize_dir, "hello/world//", "hello/world/"
same moonc.normalize_dir, "", "/" -- wrong
same moonc.normalize_dir, "hello", "hello/"
it "should parse dir", ->
same moonc.parse_dir, "/hello/world/file", "/hello/world/"
same moonc.parse_dir, "/hello/world/", "/hello/world/"
same moonc.parse_dir, "world", ""
same moonc.parse_dir, "", ""
it "should parse file", ->
same moonc.parse_file, "/hello/world/file", "file"
same moonc.parse_file, "/hello/world/", ""
same moonc.parse_file, "world", "world"
same moonc.parse_file, "", ""
it "convert path", ->
same moonc.convert_path, "test.moon", "test.lua"
same moonc.convert_path, "/hello/file.moon", "/hello/file.lua"
same moonc.convert_path, "/hello/world/file", "/hello/world/file.lua"
it "calculate target", ->
p = moonc.path_to_target
assert.same "test.lua", p "test.moon"
assert.same "hello/world.lua", p "hello/world.moon"
assert.same "compiled/test.lua", p "test.moon", "compiled"
assert.same "/home/leafo/test.lua", p "/home/leafo/test.moon"
assert.same "compiled/test.lua", p "/home/leafo/test.moon", "compiled"
assert.same "/compiled/test.lua", p "/home/leafo/test.moon", "/compiled/"
assert.same "moonscript/hello.lua", p "moonscript/hello.moon", nil, "moonscript"
assert.same "out/moonscript/hello.lua", p "moonscript/hello.moon", "out", "moonscript"
assert.same "out/moonscript/package/hello.lua",
p "moonscript/package/hello.moon", "out", "moonscript/"
assert.same "/out/moonscript/package/hello.lua",
p "/home/leafo/moonscript/package/hello.moon", "/out", "/home/leafo/moonscript"
it "should compile file text", ->
assert.same {
[[return print('hello')]]
}, {
moonc.compile_file_text "print'hello'", fname: "test.moon"
}
describe "stubbed lfs", ->
local dirs
before_each ->
dirs = {}
package.loaded.lfs = nil
dev_loaded["moonscript.cmd.moonc"] = nil
package.loaded.lfs = {
mkdir: (dir) -> table.insert dirs, dir
attributes: -> "directory"
}
moonc = require "moonscript.cmd.moonc"
after_each ->
package.loaded.lfs = nil
dev_loaded["moonscript.cmd.moonc"] = nil
moonc = require "moonscript.cmd.moonc"
it "should make directory", ->
moonc.mkdir "hello/world/directory"
assert.same {
"hello"
"hello/world"
"hello/world/directory"
}, dirs
| 30.159574 | 90 | 0.632451 |
d46d9bfd0fbd9662fe9be679c08ac08378ac32aa | 4,645 |
lapis = require "lapis"
import mock_request, mock_action, assert_request from require "lapis.spec.request"
class App extends lapis.Application
"/hello": =>
describe "application", ->
it "should mock a request", ->
assert.same 200, (mock_request App, "/hello")
assert.same 500, (mock_request App, "/world")
class SessionApp extends lapis.Application
layout: false
"/set_session/:value": =>
@session.hello = @params.value
"/get_session": =>
@session.hello
-- tests a series of requests
describe "session app", ->
it "should set and read session", ->
_, _, h = assert_request SessionApp, "/set_session/greetings"
status, res = assert_request SessionApp, "/get_session", prev: h
assert.same "greetings", res
describe "mock action", ->
assert.same "hello", mock_action lapis.Application, "/hello", {}, ->
"hello"
describe "json request", ->
import json_params from require "lapis.application"
it "should parse json body", ->
local res
class SomeApp extends lapis.Application
"/": json_params =>
res = @params.thing
assert_request SomeApp, "/", {
headers: {
"content-type": "application/json"
}
body: '{"thing": 1234}'
}
assert.same 1234, res
it "should not fail on invalid json", ->
class SomeApp extends lapis.Application
"/": json_params =>
assert_request SomeApp, "/", {
headers: {
"content-type": "application/json"
}
body: 'helloworldland'
}
describe "cookies", ->
class CookieApp extends lapis.Application
layout: false
"/": => @cookies.world = 34
"/many": =>
@cookies.world = 454545
@cookies.cow = "one cool ;cookie"
class CookieApp2 extends lapis.Application
layout: false
cookie_attributes: { "Domain=.leafo.net;" }
"/": => @cookies.world = 34
it "should write a cookie", ->
_, _, h = mock_request CookieApp, "/"
assert.same "world=34; Path=/; HttpOnly", h["Set-cookie"]
it "should write multiple cookies", ->
_, _, h = mock_request CookieApp, "/many"
assert.same {
'cow=one%20cool%20%3bcookie; Path=/; HttpOnly'
'world=454545; Path=/; HttpOnly'
}, h["Set-cookie"]
it "should write a cookie with cookie attributes", ->
_, _, h = mock_request CookieApp2, "/"
assert.same "world=34; Path=/; HttpOnly; Domain=.leafo.net;", h["Set-cookie"]
describe "500 error", ->
it "should render error page", ->
class ErrorApp extends lapis.Application
"/": =>
error "I am an error!"
status, body = mock_request ErrorApp, "/"
assert.same 500, status
assert.truthy body\match "I am an error"
it "should run custom error action", ->
class ErrorApp extends lapis.Application
handle_error: (err, msg) =>
r = @app.Request self, @req, @res
r\write {
status: 500
layout: false
content_type: "text/html"
"hello!"
}
r\render!
r
"/": => error "I am an error!"
status, body = mock_request ErrorApp, "/"
assert.same 500, status
assert.same "hello!", body
describe "before filter", ->
it "should run before filter", ->
local val
class BasicBeforeFilter extends lapis.Application
@before_filter =>
@hello = "world"
"/": =>
val = @hello
assert_request BasicBeforeFilter, "/"
assert.same "world", val
it "should run before filter with inheritance", ->
class BasicBeforeFilter extends lapis.Application
@before_filter => @hello = "world"
val = mock_action BasicBeforeFilter, =>
@hello
assert.same "world", val
it "should run before filter scoped to app with @include", ->
local base_val, parent_val
class BaseApp extends lapis.Application
@before_filter => @hello = "world"
"/base_app": => base_val = @hello or "nope"
class ParentApp extends lapis.Application
@include BaseApp
"/child_app": => parent_val = @hello or "nope"
assert_request ParentApp, "/base_app"
assert_request ParentApp, "/child_app"
assert.same "world", base_val
assert.same "nope", parent_val
it "should cancel action if before filter writes", ->
action_run = 0
class SomeApp extends lapis.Application
layout: false
@before_filter =>
if @params.value == "stop"
@write "stopped!"
"/hello/:value": => action_run += 1
assert_request SomeApp, "/hello/howdy"
assert.same action_run, 1
_, res = assert_request SomeApp, "/hello/stop"
assert.same action_run, 1
assert.same "stopped!", res
| 25.244565 | 82 | 0.625619 |
c1fb362826580cb77afde2762e22a4ca48bf0ab7 | 9,785 |
lapis = require "lapis"
import
mock_request
mock_action
assert_request
stub_request
from require "lapis.spec.request"
describe "lapis.spec.request", ->
describe "mock_request", ->
class App extends lapis.Application
"/hello": =>
it "should mock a request", ->
assert.same 200, (mock_request App, "/hello")
assert.has_error ->
mock_request App, "/world"
it "should mock a request with double headers", ->
mock_request App, "/hello", {
method: "POST"
headers: {
["Content-type"]: {
"hello"
"world"
}
}
}
it "should mock request with session", ->
class SessionApp extends lapis.Application
"/test-session": =>
import flatten_session from require "lapis.session"
assert.same {
color: "hello"
height: {1,2,3,4}
}, flatten_session @session
mock_request SessionApp, "/test-session", {
session: {
color: "hello"
height: {1,2,3,4}
}
}
describe "mock_action action", ->
it "should mock action", ->
assert.same "hello", mock_action lapis.Application, "/hello", {}, ->
"hello"
describe "stub_request", ->
class SomeApp extends lapis.Application
[cool_page: "/cool/:name"]: =>
it "should stub a request object", ->
req = stub_request SomeApp, "/"
assert.same "/cool/world", req\url_for "cool_page", name: "world"
describe "lapis.request", ->
describe "session", ->
class SessionApp extends lapis.Application
layout: false
"/set_session/:value": =>
@session.hello = @params.value
"/get_session": =>
@session.hello
it "should set and read session", ->
_, _, h = assert_request SessionApp, "/set_session/greetings"
status, res = assert_request SessionApp, "/get_session", prev: h
assert.same "greetings", res
describe "query params", ->
local params
class QueryApp extends lapis.Application
layout: false
"/hello": =>
params = @params
it "mocks request with query params", ->
assert.same 200, (mock_request QueryApp, "/hello?hello=world")
assert.same {hello: "world"}, params
it "mocks request with query params #bug", ->
assert.same 200, (mock_request QueryApp, "/hello?null")
-- todo: this is bug
assert.same {}, params
describe "json request", ->
import json_params from require "lapis.application"
it "should parse json object body", ->
local res
class SomeApp extends lapis.Application
"/": json_params =>
res = @params.thing
assert_request SomeApp, "/", {
headers: {
"content-type": "application/json"
}
body: '{"thing": 1234}'
}
assert.same 1234, res
it "should parse json array body", ->
local res
class SomeApp extends lapis.Application
"/": json_params =>
res = @params
assert_request SomeApp, "/", {
headers: {
"content-type": "application/json"
}
body: '[1,"hello", {}]'
}
assert.same {1, "hello", {}}, res
it "should not fail on invalid json", ->
class SomeApp extends lapis.Application
"/": json_params =>
assert_request SomeApp, "/", {
headers: {
"content-type": "application/json"
}
body: 'helloworldland'
}
describe "write", ->
write = (fn, ...) ->
class A extends lapis.Application
layout: false
"/": fn
mock_request A, "/", ...
it "writes nothing, sets default content type", ->
status, body, h = write ->
assert.same 200, status
assert.same "", body
assert.same "text/html", h["Content-Type"]
it "writes status code", ->
status, body, h = write -> status: 420
assert.same 420, status
it "writes content type", ->
_, _, h = write -> content_type: "text/javascript"
assert.same "text/javascript", h["Content-Type"]
it "writes headers", ->
_, _, h = write -> {
headers: {
"X-Lapis-Cool": "zone"
"Cache-control": "nope"
}
}
assert.same "zone", h["X-Lapis-Cool"]
assert.same "nope", h["Cache-Control"]
it "does redirect", ->
status, _, h = write -> { redirect_to: "/hi" }
assert.same 302, status
assert.same "http://localhost/hi", h["Location"]
it "does permanent redirect", ->
status, _, h = write -> { redirect_to: "/loaf", status: 301 }
assert.same 301, status
assert.same "http://localhost/loaf", h["Location"]
it "writes string to buffer", ->
status, body, h = write -> "hello"
assert.same "hello", body
it "writes many things to buffer, with options", ->
status, body, h = write -> "hello", "world", status: 404
assert.same 404, status
assert.same "helloworld", body
it "writes json", ->
status, body, h = write -> json: { items: {1,2,3,4} }
assert.same [[{"items":[1,2,3,4]}]], body
assert.same "application/json", h["Content-Type"]
it "writes json with custom content-type", ->
status, body, h = write ->
json: { item: "hi" }, content_type: "application/json; charset=utf-8"
assert.same "application/json; charset=utf-8", h["Content-Type"]
assert.same [[{"item":"hi"}]], body
describe "cookies", ->
class CookieApp extends lapis.Application
layout: false
"/": => @cookies.world = 34
"/many": =>
@cookies.world = 454545
@cookies.cow = "one cool ;cookie"
class CookieApp2 extends lapis.Application
layout: false
cookie_attributes: => "Path=/; Secure; Domain=.leafo.net;"
"/": => @cookies.world = 34
it "should write a cookie", ->
_, _, h = mock_request CookieApp, "/"
assert.same "world=34; Path=/; HttpOnly", h["Set-Cookie"]
it "should write multiple cookies", ->
_, _, h = mock_request CookieApp, "/many"
assert.same {
'cow=one%20cool%20%3bcookie; Path=/; HttpOnly'
'world=454545; Path=/; HttpOnly'
}, h["Set-Cookie"]
it "should write a cookie with cookie attributes", ->
_, _, h = mock_request CookieApp2, "/"
assert.same "world=34; Path=/; Secure; Domain=.leafo.net;", h["Set-Cookie"]
it "should set cookie attributes with lua app", ->
app = lapis.Application!
app.cookie_attributes = =>
"Path=/; Secure; Domain=.leafo.net;"
app\get "/", =>
@cookies.world = 34
_, _, h = mock_request app, "/"
assert.same "world=34; Path=/; Secure; Domain=.leafo.net;", h["Set-Cookie"]
describe "layouts", ->
after_each = ->
package.loaded["views.another_layout"] = nil
it "renders without layout", ->
class LayoutApp extends lapis.Application
layout: "cool_layout"
"/": => "hello", layout: false
status, res = mock_request LayoutApp, "/"
assert.same "hello", res
it "renders with layout by name", ->
import Widget from require "lapis.html"
package.loaded["views.another_layout"] = class extends Widget
content: =>
text "*"
@content_for "inner"
text "^"
class LayoutApp extends lapis.Application
layout: "cool_layout"
"/": => "hello", layout: "another_layout"
status, res = mock_request LayoutApp, "/"
assert.same "*hello^", res
it "renders layout with class", ->
import Widget from require "lapis.html"
class Layout extends Widget
content: =>
text "("
@content_for "inner"
text ")"
class LayoutApp extends lapis.Application
layout: "cool_layout"
"/": =>
"hello", layout: Layout
status, res = mock_request LayoutApp, "/"
assert.same "(hello)", res
-- these seem like an application spec and not a request one
describe "before filter", ->
it "should run before filter", ->
local val
class BasicBeforeFilter extends lapis.Application
@before_filter =>
@hello = "world"
"/": =>
val = @hello
assert_request BasicBeforeFilter, "/"
assert.same "world", val
it "should run before filter with inheritance", ->
class BasicBeforeFilter extends lapis.Application
@before_filter => @hello = "world"
val = mock_action BasicBeforeFilter, =>
@hello
assert.same "world", val
it "should run before filter scoped to app with @include", ->
local base_val, parent_val
class BaseApp extends lapis.Application
@before_filter => @hello = "world"
"/base_app": => base_val = @hello or "nope"
class ParentApp extends lapis.Application
@include BaseApp
"/child_app": => parent_val = @hello or "nope"
assert_request ParentApp, "/base_app"
assert_request ParentApp, "/child_app"
assert.same "world", base_val
assert.same "nope", parent_val
it "should cancel action if before filter writes", ->
action_run = 0
class SomeApp extends lapis.Application
layout: false
@before_filter =>
if @params.value == "stop"
@write "stopped!"
"/hello/:value": => action_run += 1
assert_request SomeApp, "/hello/howdy"
assert.same action_run, 1
_, res = assert_request SomeApp, "/hello/stop"
assert.same action_run, 1
assert.same "stopped!", res
it "should create before filter for lua app", ->
app = lapis.Application!
local val
app\before_filter =>
@val = "yeah"
app\get "/", =>
val = @val
assert_request app, "/"
assert.same "yeah", val
| 26.734973 | 81 | 0.582524 |
ae8fa0863ee32e8f109f8833e1e0b87294ea45bf | 5,242 |
import insert, concat from table
import get_fields from require "lapis.util"
query_parts = {"where", "group", "having", "order", "limit", "offset"}
rebuild_query_clause = (parsed) ->
buffer = {}
if joins = parsed.join
for {join_type, join_clause} in *joins
insert buffer, join_type
insert buffer, join_clause
for p in *query_parts
clause = parsed[p]
continue unless clause and clause != ""
p = "order by" if p == "order"
p = "group by" if p == "group"
insert buffer, p
insert buffer, clause
concat buffer, " "
class Paginator
new: (@model, clause="", ...) =>
@db = @model.__class.db
param_count = select "#", ...
opts = if param_count > 0
last = select param_count, ...
type(last) == "table" and last
elseif type(clause) == "table"
opts = clause
clause = ""
opts
@per_page = @model.per_page
@per_page = opts.per_page if opts
@_clause = @db.interpolate_query clause, ...
@opts = opts
select: (...) =>
@model\select ...
prepare_results: (items) =>
if pr = @opts and @opts.prepare_results
pr items
else
items
class OffsetPaginator extends Paginator
per_page: 10
each_page: (starting_page=1) =>
coroutine.wrap ->
page = starting_page
while true
results = @get_page page
break unless next results
coroutine.yield results, page
page += 1
get_all: =>
@prepare_results @select @_clause, @opts
-- 1 indexed page
get_page: (page) =>
page = (math.max 1, tonumber(page) or 0) - 1
@prepare_results @select @_clause .. [[ LIMIT ? OFFSET ?]],
@per_page, @per_page * page, @opts
num_pages: =>
math.ceil @total_items! / @per_page
has_items: =>
parsed = @db.parse_clause(@_clause)
parsed.limit = "1"
parsed.offset = nil
parsed.order = nil
tbl_name = @db.escape_identifier @model\table_name!
res = @db.query "SELECT 1 FROM #{tbl_name} #{rebuild_query_clause parsed}"
not not unpack res
total_items: =>
unless @_count
parsed = @db.parse_clause(@_clause)
parsed.limit = nil
parsed.offset = nil
parsed.order = nil
if parsed.group
error "Paginator can't calculate total items in a query with group by"
tbl_name = @db.escape_identifier @model\table_name!
query = "COUNT(*) AS c FROM #{tbl_name} #{rebuild_query_clause parsed}"
@_count = unpack(@db.select query).c
@_count
class OrderedPaginator extends Paginator
order: "ASC" -- default sort order
per_page: 10
new: (model, @field, ...) =>
super model, ...
if @opts and @opts.order
@order = @opts.order
@opts.order = nil
each_page: =>
coroutine.wrap ->
tuple = {}
while true
tuple = { @get_page unpack tuple, 2 }
if next tuple[1]
coroutine.yield tuple[1]
else
break
get_page: (...) =>
@get_ordered @order, ...
after: (...) =>
@get_ordered "ASC", ...
before: (...) =>
@get_ordered "DESC", ...
get_ordered: (order, ...) =>
parsed = assert @db.parse_clause @_clause
has_multi_fields = type(@field) == "table" and not @db.is_raw @field
table_name = @model\table_name!
prefix = @db.escape_identifier(table_name) .. "."
escaped_fields = if has_multi_fields
[prefix .. @db.escape_identifier f for f in *@field]
else
{ prefix .. @db.escape_identifier @field }
if parsed.order
error "order should not be provided for #{@@__name}"
if parsed.offset or parsed.limit
error "offset and limit should not be provided for #{@@__name}"
parsed.order = table.concat ["#{f} #{order}" for f in *escaped_fields], ", "
if ...
op = switch order\lower!
when "asc"
">"
when "desc"
"<"
pos_count = select "#", ...
if pos_count > #escaped_fields
error "passed in too many values for paginated query (expected #{#escaped_fields}, got #{pos_count})"
order_clause = if 1 == pos_count
order_clause = "#{escaped_fields[1]} #{op} #{@db.escape_literal (...)}"
else
positions = {...}
buffer = {"("}
for i in ipairs positions
unless escaped_fields[i]
error "passed in too many values for paginated query (expected #{#escaped_fields}, got #{pos_count})"
insert buffer, escaped_fields[i]
insert buffer, ", "
buffer[#buffer] = nil
insert buffer, ") "
insert buffer, op
insert buffer, " ("
for pos in *positions
insert buffer, @db.escape_literal pos
insert buffer, ", "
buffer[#buffer] = nil
insert buffer, ")"
concat buffer
if parsed.where
parsed.where = "#{order_clause} and (#{parsed.where})"
else
parsed.where = order_clause
parsed.limit = tostring @per_page
query = rebuild_query_clause parsed
res = @select query, @opts
final = res[#res]
res = @prepare_results res
if has_multi_fields
res, get_fields final, unpack @field
else
res, get_fields final, @field
{ :OffsetPaginator, :OrderedPaginator, :Paginator}
| 24.610329 | 113 | 0.596337 |
39fe6c9aa10b35498600d143492729f43e14ea1b | 432 | p = {}
i = 1
while true
l = io.read()
break if not l
x, y, vx, vy = string.match(l, '<%s*(-?%d+),%s*(-?%d+)>.*<%s*(-?%d+),%s*(-?%d+)>')
p[i] = {x, y, vx, vy}
i += 1
i = 0
m = nil
while true
ys = [y + vy * i for {_,y,_,vy} in *p]
min, max = math.maxinteger, 0
for y in *ys do max = math.max max, y
for y in *ys do min = math.min min, y
d = max - min
if not m or d < m then m = d else break
i += 1
print i - 1
| 21.6 | 84 | 0.481481 |
42922d9fa0e84fdc48639bc77de1acfd8b45e543 | 679 | #!/usr/bin/env moon
base = "docker://docker.io/library/debian:stable-slim"
assets = "diceware"
buildah = require"buildah".from base, assets
COPY "01_nodoc", "/etc/dpkg/dpkg.cfg.d/01_nodoc"
COPY "american-english-insane.txt", "/usr/lib/python3/dist-packages/diceware/wordlists/wordlist_en_insane.txt"
APT_GET "update"
APT_GET "full-upgrade"
APT_GET "install diceware"
APT_PURGE "sysvinit-utils e2fsprogs e2fslibs util-linux mount login hostname fdisk bsdutils bash ncurses-bin"
APT_GET "--purge autoremove"
APT_GET "autoclean"
SCRIPT"rmusers"
WIPE "docs"
WIPE "directories"
WIPE "debian"
WIPE "perl"
WIPE "userland"
ENTRYPOINT "/usr/bin/diceware"
XPUSH "diceware", "latest", "v1"
| 32.333333 | 110 | 0.771723 |
ca3055f6bce45ce63a8156c09170080180a9d404 | 6,359 | import pairs, type from _G
import rep from string
import concat, insert from table
import ELEMENT_VOID_TAGS from "novacbn/lunarviz/constants"
import dashcase, filter from "novacbn/lunarviz/utilities"
-- ::ASTRoot(string name, table nodes?) -> ASTRoot
-- Represents the root of the layout
--
ASTRoot = (name, nodes={}) -> {
-- ASTRoot::name -> string
-- Represents the name of the layout
--
name: name
-- ASTRoot::isRoot -> boolean
-- Represents if this node is the root node
--
isRoot: true
-- ASTRoot::nodes -> table
-- Represents the child nodes of the layout
--
nodes: nodes
}
-- ::ASTAttribute(string name, string or boolean value) -> ASTAttribute
-- Represents an attribute of an HTML Element
--
ASTAttribute = (name, value) -> {
-- ASTAttribute::name -> string
-- Represents the name of the attribute
--
name: name
-- ASTAttribute::value -> string or boolean
-- Represents the value of the attribute
--
value: value
}
-- ::ASTElementNode(string tag, table attributes?, table children?, boolean isVoidTag?) -> ASTElementNode
-- Represents a HTML Element node
--
ASTElementNode = (tag, attributes={}, children={}, isVoidTag=false) -> {
-- ASTElementNode::attributes -> table
-- Represents the attributes of the element
--
attributes: attributes
-- ASTElementNode::isVoidTag -> boolean
-- Represents if node's tag is of void class
--
isVoidTag: isVoidTag
-- ASTElementNode::nodes -> table
-- Represents the child elements of the element
--
nodes: children
-- ASTElementNode::tag -> string
-- Represents the HTML tag of the element
--
tag: tag
}
-- ::ASTTextNode(string text) -> ASTTextNode
-- Represents a Raw Text node
--
ASTTextNode = (text) -> {
-- ASTTextNode::isTextNode -> boolean
-- Represents if the node is just text
--
isTextNode: true
-- ASTTextNode::text -> string
-- Represents the text of the node
--
text: text
}
-- ::ChunksMeta -> table
-- Represents the LunarViz Layout construction metatable
--
ChunkMeta = {
__index: (self, tag) ->
if tag == "raw"
return (value) ->
insert(self.__nodes, ASTTextNode(value))
tag = dashcase(tag)
astnode = ASTElementNode(tag, nil, nil, ELEMENT_VOID_TAGS[tag] or false)
parentNodes = self.__nodes
insert(parentNodes, astnode)
return (attributes, value) ->
if type(attributes) == "function" or type(attributes) == "string"
value = attributes
attributes = nil
if attributes
for key, avalue in pairs(attributes)
error("malformed attribute name '#{key}'") unless type(key) == "string"
error("malformed attribute value for '#{key}'") unless type(avalue) == "string" or type(avalue) == "boolean"
key = dashcase(key)
insert(astnode.attributes, ASTAttribute(key, avalue))
if type(value) == "string" then insert(astnode.nodes, ASTTextNode(value))
elseif type(value) == "function"
self.__nodes = astnode.nodes
value()
self.__nodes = parentNodes
}
-- ::filterText(table value) -> boolean
-- Filters out ASTTextNodes from the table
--
filterText = (value) ->
return value.isTextNode == nil
-- ::compile(ASTRoot syntaxtree, boolean format?) -> string
-- Compiles a LunarViz Layout Abstract Syntax Tree into a HTML string
-- export
export compile = (syntaxtree, format=false) ->
error("bad argument #1 to 'compile' (expected ASTRoot)") unless type(syntaxtree) == "table"
error("bad argument #2 to 'compile' (expected boolean)") unless type(format) == "boolean"
buffer = {}
index = 0
local append
append = (value, next, ...) ->
index += 1
buffer[index] = value
append(next, ...) if next
traverse = (parent, name, level) ->
for node in *parent.nodes
if node.isTextNode
append(node.text)
continue
if node.isRoot
traverse(node, node.name, level)
continue
if format then append(rep("\t", level))
append("<", node.tag)
for attribute in *node.attributes
if type(attribute.value) == "boolean" and attribute.value
append(attribute.name)
continue
append(" ", attribute.name, "='", attribute.value, "'")
-- Append the name of the layout and if it is a root element
-- Used for scoped styling
-- .e.g. <div data-layout='3f19d616ab1973eab54443edad1f469f67e51a95' data-root>
append(" data-layout='", name, "'", parent.isRoot and " data-root")
-- If the node is a void tag, skip collecting children
-- .e.g. <link rel='stylesheet' href='/assets/styles/...' />
if node.isVoidTag
append(" />", format and "\n")
continue
append(">", format and #filter(node.nodes, filterText) > 0 and "\n")
traverse(node, name, format and level + 1)
if format and #filter(node.nodes, filterText) > 0 then append(rep("\t", level))
append("</", node.tag, ">", format and "\n")
traverse(syntaxtree, syntaxtree.name, 0)
return concat(buffer, "")
-- ::parse(function chunk, string name, table chunkenv?, any ...) -> ASTRoot
-- Parses a LunarViz Layout and returns the Abstract Syntax Tree
-- export
export parse = (chunk, name, chunkenv={}, ...) ->
error("bad argument #1 to 'parse' (expected function)") unless type(chunk) == "function"
error("bad argument #2 to 'parse' (expected string)") unless type(name) == "string"
error("bad argument #3 to 'parse' (expected table)") unless type(chunkenv) == "table"
parentNodes = chunkenv.__nodes
name = dashcase(name)
syntaxtree = ASTRoot(name)
insert(parentNodes, syntaxtree) if parentNodes
chunkenv.__nodes = syntaxtree.nodes
setmetatable(chunkenv, ChunkMeta)
setfenv(chunk, chunkenv)
chunk(...)
if parentNodes then chunkenv.__nodes = parentNodes
else return syntaxtree | 31.325123 | 128 | 0.601195 |
44c0b041af0fd352a4faf3c5aea5c91be20aa910 | 1,290 | import bundle, mode, config, Buffer from howl
import File from howl.io
import Editor from howl.ui
describe 'html mode', ->
local m
local buffer, editor, cursor
indent_level = 2
setup ->
bundle.load_by_name 'html'
m = mode.by_name 'html'
teardown -> bundle.unload 'html'
before_each ->
m = mode.by_name 'html'
buffer = Buffer m
buffer.config.indent = indent_level
editor = Editor buffer
cursor = editor.cursor
context 'indentation', ->
indent_for = (text, line) ->
buffer.text = text
cursor.line = line
editor\indent!
editor.current_line.indentation
it 'indents after ordinary tags', ->
for text in *{
'<p>\n',
'<div id="myid">\n',
'<annotation encoding="text/latex">\n'
}
assert.equal indent_level, indent_for text, 2
it 'dedents closing tags', ->
assert.equal 0, indent_for ' foo\n </p>', 2
it 'dedents closing tags', ->
assert.equal 0, indent_for ' foo\n </p>', 2
it 'does not indent after closed tags', ->
assert.equal 0, indent_for '<p>Hello world!</p>\n', 2
it 'does not indent after certain void element tags', ->
for text in *{ '<br>\n', '<input type="checkbox">\n' }
assert.equal 0, indent_for text, 2
| 25.8 | 60 | 0.610853 |
114acf2c1c98d7a1a033a488374b7f5f28afdf44 | 471 | { :gsub, :split } = require('std.string')
export req = (path, file) ->
pathParts = split(gsub(path, '/', '.'), '%.')
firstFilePart = split(gsub(file, '/', '.'), '%.')[1]
dir = ''
for part in *pathParts
if part == firstFilePart then break
dir ..= "#{part}."
require(dir .. file)
{
Criteria: req(..., 'lib.criteria'),
Entity: req(..., 'lib.entity'),
EventEmitter: req(..., 'lib.event-emitter'),
Secs: req(..., 'lib.secs'),
System: req(..., 'lib.system'),
}
| 24.789474 | 53 | 0.558386 |
a6373daa1768c058cd411095057ed799bb2ef552 | 381 |
flat_value = (op, depth=1) ->
return '"'..op..'"' if type(op) == "string"
return tostring(op) if type(op) != "table"
items = [flat_value item, depth + 1 for item in *op]
pos = op[-1]
"{"..(pos and "["..pos.."] " or "")..table.concat(items, ", ").."}"
value = (op) ->
flat_value op
tree = (block) ->
print flat_value value for value in *block
{ :value, :tree }
| 20.052632 | 69 | 0.551181 |
d8cac47c0579166b429a8e28a276759f844d3568 | 2,782 |
current = (...)
load = (path) ->
succ, loaded = pcall require, path
unless succ
LC_PATH = current .. '.' .. path
succ, loaded = pcall require, LC_PATH
unless succ
LC_PATH = current\gsub("%.[^%..]+$", "") .. '.' .. path
succ, loaded = pcall require, LC_PATH
unless succ
error loaded
return loaded
--------------------------------
exec = (command) ->
handle = assert io.popen command
result = handle\read '*all'
handle\close!
return result
split = (input, separator) ->
if separator == nil
separator = "%s"
t = {}
i = 1
for str in string.gmatch(input, "([^" .. separator .. "]+)")
t[i] = str
i += 1
return t
join = (delimiter, list) ->
len = #list
if len == 0 then
return ""
string = list[1]
i = 2
while i <= len
string = string .. delimiter .. list[i]
i += 1
return string
------------------------------
-- LINUX
splitLinux = (input, separator) ->
if separator == nil
separator = "%s"
t = {}
i = 1
cmd = ""
for str in string.gmatch(input, "([^" .. separator .. "]+)")
if i >= 11
cmd = cmd .. str .. ' '
else
t[i] = str
i += 1
cmd = cmd\sub(1, -2)
return t, cmd
parse = (input) ->
strings = split(input, '\n')
table.remove strings, 1
list = {}
for _, str in pairs strings
sp, cmd = splitLinux(str, '%s+')
item =
user: sp[1]
pid: tonumber sp[2]
cpu: tonumber sp[3]
mem: tonumber sp[4]
vsz: sp[5]
rss: sp[6]
tt: sp[7]
stat: sp[8]
started: sp[9]
time: sp[10]
command: cmd
table.insert list, item
return list
getProcessesLinux = ->
aux = exec 'ps aux'
return parse aux
----------------------------------
-- WINDOWS
getProcessesWindows = () ->
csv = load 'csv'
data = exec 'tasklist /v /nh /fo csv'
strs = split data, '\n'
str = csv.openstring(data)
processes = {}
for fields in str\lines!
mem = fields[5]\gsub('[^%d]', '')
process =
imageName: fields[1]
pid: tonumber fields[2]
sessionName: fields[3]
sessionNumber: tonumber fields[4]
mem: tonumber(mem) * 1024
status: fields[6]
username: fields[7]
cpuTime: fields[8]
windowTitle: fields[9]
table.insert processes, process
return processes
getProcesses = ->
-- get platform
local platform
if love and love.system and love.system.getOS
platform = love.system.getOS!
else
error 'Locale detection currently works only in LÖVE!'
----------------
local r
-- pick locale getter for platform
switch platform
when "Linux"
r = getProcessesLinux!
when "Android"
r = getProcessesLinux!
when "OS X"
r = getProcessesLinux!
when "Windows"
r = getProcessesWindows!
when "iOS"
r = getProcessesLinux!
return r
return getProcesses
| 16.759036 | 61 | 0.564702 |
13df8b72743bd753274ea9e58d526e8ad8215028 | 4,176 | Dorothy!
ClipEditorView = require "View.Control.Item.ClipEditor"
InputBox = require "Control.Basic.InputBox"
MessageBox = require "Control.Basic.MessageBox"
Packer = require "Data.Packer"
Reference = require "Data.Reference"
Class ClipEditorView,
__init:(args)=>
{:images} = args
@addImages images
@scrollArea\slot "Scrolled",(delta)->
@scrollArea.view\eachChild (child)->
child.position += delta
@okBtn\slot "Tapped",->
inputBox = InputBox text:"New Group Name"
inputBox\slot "Inputed",(name)->
return unless name
if name == "" or name\match("[\\/|:*?<>\"%.]")
MessageBox text:"Invalid Name!",okOnly:true
elseif oContent\exist(name..".clip")
MessageBox text:"Name Exist!",okOnly:true
else
msgBox = MessageBox text:"Group Name\n"..name
msgBox\slot "OK",(result)->
if result
-- save clip
xml = "<A A=\""..name..".png\">"
h = @target.height
for block in *@blocks
xml ..= "<B A=\""..block.name
xml ..= "\" B=\""
xml ..= tostring(block.fit.x+2)..","
xml ..= tostring(h-block.fit.y-2-block.h+4)..","
xml ..= tostring(block.w-4)..","
xml ..= tostring(block.h-4).."\"/>"
xml = xml.."</A>"
clipFile = editor.graphicFolder..name..".clip"
oContent\saveToFile editor.gameFullPath..clipFile,xml
oCache.Clip\update clipFile,xml
emit "Scene.ClipUpdated",clipFile
-- save texture
texFile = editor.graphicFolder..name..".png"
@target\save editor.gameFullPath..texFile
oCache.Texture\add @target,texFile
-- remove images
for image in *images
oCache.Texture\unload image
oContent\remove image
Reference.removeRef image
@close true
@cancelBtn\slot "Tapped",->
@close false
CCDirector.currentScene\addChild @,2
close:(result)=>
@opMenu.enabled = false
@perform oOpacity 0.3,0
@okBtn\perform oScale 0.3,0,0,oEase.InBack
@cancelBtn\perform oScale 0.3,0,0,oEase.InBack
@panel\perform CCSequence {
CCSpawn {
oScale 0.3,0,0,oEase.InBack
oOpacity 0.3,0
}
CCCall ->
@emit "Grouped",result
@parent\removeChild @
}
addImages:(images)=>
@scrollArea.view\removeAllChildrenWithCleanup!
{:width,:height} = @scrollArea
blocks = {}
for image in *images
oCache.Texture\unload image
blendFunc = ccBlendFunc ccBlendFunc.One,ccBlendFunc.Zero
for image in *images
sp = CCSprite image
if sp
sp.texture.antiAlias = false
sp.blendFunc = blendFunc
sp.anchor = oVec2.zero
block = {
w: sp.width+4
h: sp.height+4
sp: sp
name: image\match "[\\/]([^\\/]*)%.[^%.\\/]*$"
}
table.insert blocks,block
for image in *images
oCache.Texture\unload image
Packer\fit blocks
w = Packer.root.w
tmp = 2
while tmp < w do tmp = tmp*2
w = tmp
h = Packer.root.h
tmp = 2
while tmp < h do tmp = tmp*2
h = tmp
frame = oLine {
oVec2.zero
oVec2 w,0
oVec2 w,h
oVec2 0,h
oVec2.zero
}, ccColor4 0x44ffffff
node = CCNode()
for block in *blocks
with block
if .fit
.fit.y = h-.fit.y-.h
rect = CCRect .fit.x, .fit.y, .w, .h
line = oLine {
oVec2 rect.left+2,rect.bottom+2
oVec2 rect.right-2,rect.bottom+2
oVec2 rect.right-2,rect.top-2
oVec2 rect.left+2,rect.top-2
oVec2 rect.left+2,rect.bottom+2
}, ccColor4!
frame\addChild line
.sp.position = rect.origin + oVec2 2,2
node\addChild .sp
@blocks = blocks
target = CCRenderTarget w,h
target\beginDraw!
target\draw node
target\endDraw!
@target = target
posX = w+20 <= width and width*0.5 or 10+w*0.5
posY = h+20 <= height and height*0.5 or height-h*0.5-10
@scrollArea.view\addChild with target
.opacity = 0
.position = oVec2 posX,posY
\addChild frame
\runAction oOpacity 0.3,1
@scrollArea.viewSize = CCSize w+20,h+20
@scrollArea.padding = oVec2 w+20 <= width and 0 or 100,
h+20 <= height and 0 or 100
@scrollArea.offset = oVec2.zero
| 28.026846 | 61 | 0.601054 |
88dd2f1afb095b76730cbe838c7d20c93b9e8838 | 575 |
one_of = (state, arguments) ->
{ input, expected } = arguments
for e in *expected
return true if input == e
false
s = require "say"
s\set "assertion.one_of.positive",
"Expected %s to be one of:\n%s"
s\set "assertion.one_of.negative",
"Expected property %s to not be in:\n%s"
assert\register "assertion",
"one_of", one_of, "assertion.one_of.positive", "assertion.one_of.negative"
with_query_fn = (q, run) ->
db = require "lapis.nginx.postgres"
old_query = db.set_backend "raw", q
with run!
db.set_backend "raw", old_query
{ :with_query_fn }
| 20.535714 | 76 | 0.674783 |
0dc88a86c30ecbbe8401a1ea1789ee2dae86c46d | 497 | -------------------------------------------------------------------------------
-- Handles input and output to console.
-------------------------------------------------------------------------------
-- @module yae.console
---
-- Write text to console
-- @param ... text to write
-- @usage
-- yae.console.write "Hello", "World"
write = write
---
-- Read text from console
-- @treturn string entered text
-- @usage
-- message = yae.console.read!
-- print message
read = read
{
:read
:write
} | 20.708333 | 79 | 0.438632 |
6cbfec692b379fa9e85d89c9e7138c5564394914 | 508 | {
EOF: {
rbp: 0, lbp: 0
lit: "#<EOF>"
str: "EOF"
}
ERROR: {
rbp: 0, lbp: 0
lit: "#<ERROR>"
str: "ERROR"
}
COMMENT: {
rbp: 0, lbp: 0
lit: "#<COMMENT>"
str: "COMMENT"
}
STRING: {
rbp: 0, lbp: 0
lit: "#<STRING>"
str: "STRING"
nud: => @str
}
NUMBER: {
rbp: 0, lbp: 0
lit: "#<NUMBER>"
str: "NUMBER"
nud: => @num
}
IDENTIFIER: {
rbp: 0, lbp: 0
lit: "#<IDENTIFIER>"
str: "IDENTIFIER"
nud: => @env[@str]
}
}
| 14.111111 | 24 | 0.425197 |
904db2560acf768051662d79f9f13e21f905bd35 | 2,663 | import mode, bundle from howl
append = table.insert
describe 'Moonscript lexer', ->
local lexer
setup ->
bundle.load_by_name 'lua'
bundle.load_by_name 'moonscript'
lexer = mode.by_name('moonscript').lexer
teardown ->
bundle.unload 'moonscript'
bundle.unload 'lua'
result = (text, ...) ->
styles = {k,true for k in *{...}}
tokens = lexer text
parts = {}
for i = 1, #tokens, 3
style = tokens[i + 1]
part = text\sub tokens[i], tokens[i + 2] - 1
append(parts, part) if styles[tostring style]
parts
it 'handles #keywords', ->
assert.same { 'if', 'then' }, result 'if foo then ifi fif', 'keyword'
it 'handles #comments', ->
assert.same { '--wat' }, result ' --wat', 'comment'
it 'handles single quoted strings', ->
assert.same { "'str'" }, result " 'str' ", 'string'
it 'handles double quoted strings', ->
assert.same { '"', 'str"' }, result ' "str" ', 'string'
it 'handles long strings', ->
assert.same { '[[\nfoo\n]]' }, result ' [[\nfoo\n]] ', 'string'
it 'handles backslash escapes in strings', ->
assert.same { "'str\\''", '"', 'str\\""' }, result [['str\'' x "str\""]], 'string'
it 'handles numbers', ->
parts = result '12 0xfe 0Xaa 3.1416 314.16e-2 0.31416E1 0x0.1E 0xA23p-4 0X1.921FB54442D18P+1 .2', 'number'
assert.same {
'12',
'0xfe',
'0Xaa',
'3.1416',
'314.16e-2',
'0.31416E1',
'0x0.1E',
'0xA23p-4',
'0X1.921FB54442D18P+1',
'.2'
}, parts
it 'lexes ordinary names as identifier', ->
assert.same { 'hi', '_var', 'take2' }, result "hi _var take2", 'identifier'
it 'handles operators', ->
assert.same { '+', ',', '~=', '{', '(', ')', '/', '}', ',', 'or=' }, result '1+2, ~= {(a)/x}, or=', 'operator'
it 'handles members', ->
assert.same { '@foo', 'self.foo', '@_private' }, result " @foo self.foo @_private ", 'member'
it 'lexes true, false and nil as special', ->
assert.same { 'true', 'false', 'nil' }, result "if true then false else nil", 'special'
it 'lexes capitalized identifiers as class', ->
assert.same { 'Foo' }, result "class Foo", 'class'
it 'lexes all valid key formats as key', ->
assert.same { ':ref', 'plain:', "'string key':" }, result ":ref, plain: true, 'string key': oh_yes", 'key'
it 'lexes illegal identifiers as error', ->
assert.same { 'function', 'end', 'goto' }, result "function() end, end_marker goto label", 'error'
it 'does sub-lexing within string interpolations', ->
assert.same { '#', '{', '+', '}', '#', '{', '/', '}', ',' }, result '"#{x + y} +var+ #{z/0}", trailing', 'operator'
| 31.702381 | 119 | 0.557642 |
6b50fdbc379852e6b56f9cbea9665ab9aec7a35b | 2,418 | db = require "lapis.db"
import create_table, types, add_column, rename_column, create_index, drop_index from require "lapis.db.schema"
{
[1]: =>
create_table "users", {
{"id", types.serial primary_key: true}
{"name", types.varchar unique: true}
{"email", types.text unique: true}
{"digest", types.text}
{"admin", types.boolean default: false}
{"created_at", types.time}
{"updated_at", types.time}
}
create_table "sessions", {
{"user_id", types.foreign_key}
{"created_at", types.time}
{"updated_at", types.time}
}
[1518430372]: =>
add_column "sessions", "id", types.serial primary_key: true
rename_column "sessions", "created_at", "opened_at"
rename_column "sessions", "updated_at", "closed_at"
create_index "users", "id", unique: true
create_index "users", "name", unique: true
create_index "users", "email", unique: true
create_index "sessions", "id", unique: true
[1518968812]: =>
import autoload from require "locator"
import settings from autoload "utility"
settings["users.allow-sign-up"] = true
settings["users.allow-name-change"] = true
settings["users.admin-only-mode"] = false
settings["users.require-email"] = true
settings["users.require-unique-email"] = true
settings["users.allow-email-change"] = true
settings["users.session-timeout"] = 60 * 60 * 24 -- default is one day
settings["users.minimum-password-length"] = 12
settings["users.maximum-character-repetition"] = 6
settings["users.bcrypt-digest-rounds"] = 12
-- settings["users.password-check-fn"] = nil -- should return true if passes, falsy and error message if fails
settings.save!
drop_index "users", "email" -- replacing because it was a unique index
db.query "ALTER TABLE users DROP CONSTRAINT users_email_key"
create_index "users", "email"
[1519416945]: =>
import autoload from require "locator"
import settings from autoload "utility"
settings["users.require-recaptcha"] = false -- protect against bots for sign-up (default off because it requires set-up)
-- settings["users.recaptcha-sitekey"] = nil -- provided by admin panel
-- settings["users.recaptcha-secret"] = nil -- provided by admin panel
settings.save!
[1526102192]: =>
db.query "ALTER TABLE users ALTER COLUMN email DROP NOT NULL" -- allow NULL emails
}
| 35.558824 | 125 | 0.671629 |
f23a3c390d50dacd13343d9edf69424f404d8d50 | 307 | --
-- Listen to specified URL and respond with status 200
-- to signify this server is alive
--
-- Use to notify upstream haproxy load-balancer
--
return (url = '/haproxy?monitor') ->
return (req, res, continue) ->
if req.url == url
res\send 200, nil, {}
else
continue()
return
| 18.058824 | 54 | 0.625407 |
96523478509f8a82d32195a2cdfd6ce653efc4eb | 3,474 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
jit = require 'jit'
require 'ljglibs.cdefs.gtk'
require 'ljglibs.gdk.window'
require 'ljglibs.gobject.object'
require 'ljglibs.cairo.context'
require 'ljglibs.pango.context'
core = require 'ljglibs.core'
gobject = require 'ljglibs.gobject'
C, ffi_cast = ffi.C, ffi.cast
ref_ptr, gc_ptr, signal = gobject.ref_ptr, gobject.gc_ptr, gobject.signal
widget_t = ffi.typeof 'GtkWidget *'
cairo_t = ffi.typeof 'cairo_t *'
pack, unpack = table.pack, table.unpack
to_w = (o) -> ffi_cast widget_t, o
jit.off true, true
core.define 'GtkWidget < GObject', {
properties: {
app_paintable: 'gboolean'
can_default: 'gboolean'
can_focus: 'gboolean'
composite_child: 'gboolean'
double_buffered: 'gboolean'
events: 'GdkEventMask'
expand: 'gboolean'
halign: 'GtkAlign'
has_default: 'gboolean'
has_focus: 'gboolean'
has_tooltip: 'gboolean'
height_request: 'gint'
hexpand: 'gboolean'
hexpand_set: 'gboolean'
is_focus: 'gboolean'
margin: 'gint'
margin_bottom: 'gint'
margin_left: 'gint'
margin_right: 'gint'
margin_top: 'gint'
name: 'gchar*'
no_show_all: 'gboolean'
opacity: 'gdouble'
parent: 'GtkContainer*'
receives_default: 'gboolean'
sensitive: 'gboolean'
style: 'GtkStyle*'
tooltip_markup: 'gchar*'
tooltip_text: 'gchar*'
valign: 'GtkAlign'
vexpand: 'gboolean'
vexpand_set: 'gboolean'
visible: 'gboolean'
width_request: 'gint'
window: 'GdkWindow*'
-- Added properties
in_destruction: => C.gtk_widget_in_destruction(@) != 0
screen: => ref_ptr C.gtk_widget_get_screen @
style_context: => ref_ptr C.gtk_widget_get_style_context @
pango_context: => C.gtk_widget_get_pango_context @
allocated_width: => C.gtk_widget_get_allocated_width @
allocated_height: => C.gtk_widget_get_allocated_height @
toplevel: => ref_ptr C.gtk_widget_get_toplevel @
visual:
get: => C.gtk_widget_get_visual @
set: (visual) => C.gtk_widget_set_visual @, visual
}
realize: => C.gtk_widget_realize @
show: => C.gtk_widget_show @
show_all: => C.gtk_widget_show_all @
hide: => C.gtk_widget_hide @
grab_focus: => C.gtk_widget_grab_focus @
destroy: => C.gtk_widget_destroy @
translate_coordinates: (dest_widget, src_x, src_y) =>
ret = ffi.new 'gint [2]'
status = C.gtk_widget_translate_coordinates @, to_w(dest_widget), src_x, src_y, ret, ret + 1
error "Failed to translate coordinates" if status == 0
ret[0], ret[1]
set_size_request: (width, height) => C.gtk_widget_set_size_request @, width, height
override_background_color: (state, color) =>
C.gtk_widget_override_background_color @, state, color
override_font: (font_description) =>
C.gtk_widget_override_font @, font_description
create_pango_context: => gc_ptr C.gtk_widget_create_pango_context @
add_events: (events) => C.gtk_widget_add_events @, events
queue_allocate: => C.gtk_widget_queue_allocate @
queue_resize: => C.gtk_widget_queue_resize @
queue_draw: => C.gtk_widget_queue_draw @
queue_draw_area: (x, y, width, height) =>
C.gtk_widget_queue_draw_area @, x, y, width, height
on_draw: (handler, ...) =>
this = @
args = pack(...)
signal.connect 'bool3', @, 'draw', (widget, cr) ->
handler this, cairo_t(cr), unpack(args, args.n)
}
| 29.948276 | 96 | 0.694588 |
ff3aad62913556a201f90197d8e2c655c0ac48aa | 1,104 | project = (fov, ...) ->
point = {...}
scale = fov / (fov + point[#point])
_point = {}
for c in *point
_point[#_point + 1] = c * scale
if #_point - (#point - 1) == 0
return _point, scale
project_to = (n, fov, ...) ->
a, scale = project fov, ...
if n - #a == 0
return a, scale
else
project_to n, fov, unpack a
line = (fov, p1, p2) ->
a, s = project_to 2, fov, unpack p1
a2, s2 = project_to 2, fov, unpack p2
with love.graphics
.line a[1] * s, a[2] * s, a2[1] * s2, a2[2] * s2
circle = (fov, mode, p1, radius, segments) ->
a, s = project_to 2, fov, unpack p1
with love.graphics
.circle mode, a[1] * s, a[2] * s, radius * s, segments
triangle = (fov, mode, p1, p2, p3) ->
a, s = project_to 2, fov, unpack p1
a2, s2 = project_to 2, fov, unpack p2
a3, s3 = project_to 2, fov, unpack p3
with love.graphics
.polygon mode, a[1], a[2], a2[1], a2[2], a3[1], a3[2]
{
:project
:project_to
graphics: {
:line
:circle
:triangle
}
} | 21.647059 | 62 | 0.503623 |
ccf4b5704ef8e2b4bd998f2c7c572cf927208622 | 2,536 | import insert from table
import floor, min from math
export inspect = require "libs/inspect"
export Vector = require "libs/vector"
export bump = require "libs/bump"
export Camera = require "libs/camera"
export push = require "libs/push"
roomy = require "libs/roomy"
export ripple = require "libs/ripple"
export flux = require "libs/flux"
export tick = require "libs/tick"
export Grid = require "libs.jumper.grid"
export Pathfinder = require "libs.jumper.pathfinder"
export manager = roomy.new!
require "moon/shaders"
require "moon/helpers"
require "moon/input"
require "moon/ui"
require "moon/sprites"
require "moon/sounds"
require "moon/item"
require "moon/entity"
-- Weapons
require "moon/weapon"
require "moon/arrow"
require "moon/bow"
-- Spells
require "moon/ignite"
-- Enemies
require "moon/undead"
require "moon/dungeon"
require "moon/player"
require "moon/wall"
require "moon/room"
require "moon/door"
require "moon/chest"
require "moon/stairs"
export gameWidth = 256
export gameHeight = 224
export uiWidth = gameWidth
export uiHeight = 40
export tileSize = 16
export screenHeight = gameHeight + uiHeight
export font
windowScale = 3
export windowedWidth, windowedHeight = love.window.getDesktopDimensions()
windowedScale = min floor(windowedWidth / gameWidth), floor(windowedHeight / screenHeight) - 1
windowedWidth = gameWidth * windowedScale
windowedHeight = screenHeight * windowedScale
export colors
export colorSchemes = {}
export colorScheme = 6
export states = {
gameplay: require "moon/gameplay"
title: require "moon/title"
help: require "moon/help"
death: require "moon/death"
}
love.load = ->
love.joystick.loadGamepadMappings "assets/misc/gamecontrollerdb.txt"
love.graphics.setDefaultFilter "nearest", "nearest"
love.graphics.setLineStyle "rough"
push\setupScreen gameWidth, gameHeight + uiHeight, windowedWidth, windowedHeight, {
resizeable: false
pixelperfect: true
}
shaders\load!
dir = "assets/colors/"
files = love.filesystem.getDirectoryItems(dir)
for file in *files do
scheme = require dir .. file\sub(1, #file - 4)
insert colorSchemes, scheme
colors = colorSchemes[colorScheme]
export fontGameplay = love.graphics.newImageFont 'assets/sprites/font.png', ' ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', -1
export fontRetro = love.graphics.newFont("assets/misc/retro.ttf", 8, "mono")
export fontFantasy = love.graphics.newFont("assets/misc/fantasy.ttf", 66, "mono")
sprites\load!
sounds\load!
manager\hook!
manager\enter states.title
| 24.862745 | 121 | 0.751972 |
c4852fa04a6e53c888869c3bc279a93ca3b55088 | 787 | -- Score
-- This plugin picks the server with the least or most score value (depending
-- on configuration)
-- Requires the paramter to be either "least" or "most"
M = {}
M.balance = (request, session, param) ->
servers = session['servers']
return servers if param != 'least' and param != 'most'
upstreams, score = {}, 0
for server in *servers
if #upstreams == 0 or score == server['score']
table.insert(upstreams, server)
score = server['score']
elseif param == 'least' and score > server['score']
upstreams = {server}
score = server['score']
elseif param == 'most' and score < server['score']
upstreams = {server}
score = server['score']
return upstreams
return M
| 29.148148 | 77 | 0.590851 |
99065389fffba5ec2ef6ea22b2d931e6da4924c4 | 3,051 | m = howl.ui.markup.terminal
StyledText = howl.ui.StyledText
describe 'terminal', ->
it 'returns a StyledText instance with empty styles if no markup is detected', ->
assert.same StyledText('foo', {}), m 'foo'
context 'ANSI escape sequences', ->
it 'handles bold', ->
expected = StyledText 'foo', { 1, 'ansi_bold', 4 }
assert.same expected, m '\027[1mfoo\027[0m'
it 'handles italic', ->
expected = StyledText 'foo', { 1, 'ansi_italic', 4 }
assert.same expected, m '\027[3mfoo\027[0m'
it 'handles underline', ->
expected = StyledText 'foo', { 1, 'ansi_underline', 4 }
assert.same expected, m '\027[4mfoo\027[0m'
it 'handles background colors', ->
expected = StyledText 'foo', { 1, 'ansi_red', 4 }
assert.same expected, m '\027[31mfoo\027[0m'
it 'handles background colors', ->
expected = StyledText 'foo', { 1, 'ansi_on_red', 4 }
assert.same expected, m '\027[41mfoo\027[0m'
it 'handles combined foreground and background colors', ->
expected = StyledText 'foo', { 1, 'ansi_green_on_red', 4 }
assert.same expected, m '\027[41;32mfoo\027[0m'
it 'styles remain in effect until resetted', ->
expected = StyledText 'foobar', {
1, 'ansi_on_red', 4
4, 'ansi_green_on_red', 7
}
assert.same expected, m '\027[41mfoo\027[32mbar\027[0m'
it 'handles empty reset sequences', ->
expected = StyledText 'foobar', { 1, 'ansi_italic', 4 }
assert.same expected, m '\027[3mfoo\027[mbar'
it 'handles prematurely terminated sequences', ->
expected = StyledText 'foo', { 1, 'ansi_red', 4 }
assert.same expected, m '\027[31mfoo'
it 'handles foreground color resetting', ->
expected = StyledText 'foobar', { 1, 'ansi_red', 4 }
assert.same expected, m '\027[31mfoo\027[39mbar'
it 'handles background color resetting', ->
expected = StyledText 'foobar', { 1, 'ansi_on_red', 4 }
assert.same expected, m '\027[41mfoo\027[49mbar'
it 'skips over unhandled escape sequences', ->
expected = StyledText 'foo', {}
assert.same expected, m '\027[2,2Hfoo'
it 'ignores unhandled graphic parameters', ->
expected = StyledText 'foo', { 1, 'ansi_red', 4 }
assert.same expected, m '\027[31;5;6mfoo\027[m'
context 'backspace characters (BS)', ->
it 'deletes back properly', ->
expected = StyledText 'fo', {}
assert.same expected, m 'foo\008'
it 'deletes a UTF-8 code point back, and not a byte', ->
expected = StyledText 'åä', {}
assert.same expected, m 'åäö\008'
it 'BS at the start of the text is left alone', ->
expected = StyledText '\008foo', {}
assert.same expected, m '\008foo'
it 'updates the styling accordingly', ->
expected = StyledText 'fobar', { 1, 'ansi_red', 3 }
assert.same expected, m '\027[31mfoo\027[m\008bar'
it 'removes any left empty styling', ->
expected = StyledText 'fobar', { }
assert.same expected, m 'fo\027[31mo\027[m\008bar'
| 35.476744 | 83 | 0.623074 |
190618171426685285755dcc7adb5cef0f34487c | 122 | listMatch = zb2rhoexKPhLaQGMSVjrSsRaz56U8RZYkUBUJKPDPNLqYWHw8
a =>
(a u16 => num => (add u16 (mul num #(pow 2 16))) 0)
| 24.4 | 61 | 0.696721 |
e7552ee6afff929fe0c0671247454b32dc6d3331 | 13,353 | import lpeg_lexer from howl.aux
import mode from howl
import P,V, C, Cp, Cg, Cb from lpeg
l = lpeg_lexer
describe 'lpeg_lexer', ->
describe 'new(definition)', ->
it 'accepts a function', ->
assert.not_has_error -> l.new -> true
it 'the module can be called directly to create a lexer (same as new())', ->
assert.not_has_error -> l -> true
it 'the resulting lexer can be called directly', ->
lexer = l -> P'x' * Cp!
assert.same { 2 }, lexer 'x'
it 'imports lpeg definitions locally into the module', ->
for op in *{'Cp', 'Ct', 'S', 'P'}
assert.is_not_nil l[op]
it 'imports lpeg.locale definitions locally into the module', ->
for ldef in *{'digit', 'upper', 'print', 'lower'}
assert.is_not_nil l[ldef]
describe 'capture(style, pattern)', ->
it 'returns a LPeg pattern', ->
assert.equal 'pattern', lpeg.type l.capture('foo', P(1))
it 'the returned pattern produces the three captures <start-pos>, <style-name> and <end-pos> if <pattern> matches', ->
p = l.capture 'foo', P'fo'
assert.same { 1, 'foo', 3 }, { p\match 'foobar' }
describe 'predefined helper patterns', ->
describe '.eol', ->
it 'matches and consumes new lines', ->
assert.is_not_nil l.eol\match '\n'
assert.is_not_nil l.eol\match '\r'
assert.equals 2, (l.eol * Cp!)\match '\n'
assert.equals 3, (l.eol * Cp!)\match '\r\n'
assert.is_nil l.eol\match 'a'
assert.is_nil l.eol\match '2'
describe '.float', ->
it 'matches and consumes various float representations', ->
for repr in *{ '34.5', '3.45e2', '1.234E1', '3.45e-2', '.32' }
assert.is_not_nil l.float\match repr
describe '.hexadecimal', ->
it 'matches and consumes various hexadecimal representations', ->
for repr in *{ '0xfeab', '0XDEADBEEF' }
assert.is_not_nil l.hexadecimal\match repr
it 'does not match illegal hexadecimal representations', ->
assert.is_nil l.hexadecimal\match '0xCDEFG'
describe '.hexadecimal_float', ->
it 'matches and consumes various hexadecimal float representations', ->
for repr in *{ '0xfep2', '0XAP-3' }
assert.is_not_nil l.hexadecimal_float\match repr
it 'does not match illegal hexadecimal representations', ->
assert.is_nil l.hexadecimal_float\match '0xFGp3'
describe '.octal', ->
it 'matches and consumes octal representations', ->
assert.is_not_nil l.octal\match '0123'
it 'does not match illegal octal representations', ->
assert.is_nil l.octal\match '0128'
describe '.line_start', ->
it 'matches after newline or at start of text', ->
assert.is_not_nil l.line_start\match 'x'
assert.is_not_nil (l.eol * l.line_start * P'x')\match '\nx'
it 'does not consume anything', ->
assert.equals 2, (l.eol * l.line_start * Cp!)\match '\nx'
describe 'any(list)', ->
it 'the resulting pattern is an ordered match of any member of <list>', ->
p = l.any { 'one', 'two' }
assert.is_not_nil p\match 'one'
assert.is_not_nil p\match 'two'
assert.is_nil p\match 'three'
it '<list> can be vararg arguments', ->
p = l.any 'one', 'two'
assert.is_not_nil p\match 'two'
describe 'sequence(list)', ->
it 'the resulting pattern is a chained match of all members of <list>', ->
p = l.sequence { 'one', 'two' }
assert.is_nil p\match 'one'
assert.is_nil p\match 'two'
assert.is_not_nil p\match 'onetwo'
assert.is_nil p\match 'Xonetwo'
it '<list> can be vararg arguments', ->
p = l.sequence 'one', 'two'
assert.is_not_nil p\match 'onetwo'
describe 'word(list)', ->
grammar = P {
V'word' + P(1) * V(1)
word: l.word { 'one', 'two2' }
}
it 'returns a pattern who matches any word in <list>', ->
assert.is_not_nil grammar\match 'one'
assert.is_not_nil grammar\match 'so one match'
assert.is_not_nil grammar\match '!one'
assert.is_not_nil grammar\match 'one()'
assert.is_not_nil grammar\match 'then two2,'
assert.is_nil grammar\match 'three'
it 'only matches standalone words, not substring occurences', ->
assert.is_nil grammar\match 'fone'
assert.is_nil grammar\match 'one2'
assert.is_nil grammar\match 'two2fold'
assert.is_nil grammar\match 'two2_fold'
it 'accepts var arg parameters', ->
assert.is_not_nil l.word('one', 'two')\match 'two'
describe 'span(start_p, stop_p [, escape_p])', ->
p = l.span('{', '}') * Cp!
it 'matches and consumes from <start_p> up to and including <stop_p>', ->
assert.equals 3, p\match '{}'
assert.equals 5, p\match '{xx}'
it 'always considers <EOF> as an alternate stop marker', ->
assert.equals 3, p\match '{x'
it 'allows escaping <stop_p> with <escape_p>', ->
p = l.span('{', '}', '\\') * Cp!
assert.equals 5, p\match '{\\}}'
describe 'paired(p, escape [, pair_style, content_style])', ->
p = l.paired(1) * Cp!
it 'matches and consumes from <p> up to and including the matching <p>', ->
assert.equals 3, p\match '||x'
assert.equals 5, p\match '|xx|x'
it 'always considers <EOF> as an alternate stop marker', ->
assert.equals 3, p\match '|x'
it 'allows escaping the end delimiter with <escape>', ->
p = l.paired(1, '\\') * Cp!
assert.equals 5, p\match '|\\|| foo\\'
context 'when pair_style and content_style are specified', ->
it 'captures the components in the specified styles', ->
p = l.paired(1, nil, 'keyword', 'string')
expected = {
1, 'keyword', 2,
2, 'string', 5,
5, 'keyword', 6,
}
assert.same expected, { p\match '|foo|' }
it 'still handles escapes properly', ->
p = l.paired(1, '%', 'keyword', 'string')
expected = {
1, 'keyword', 2,
2, 'string', 6,
6, 'keyword', 7,
}
assert.same expected, { p\match '|f%|o|' }
describe 'back_was(name, value)', ->
p = Cg(l.alpha^1, 'group') * ' ' * l.back_was('group', 'foo')
it 'matches if the named capture <named> previously matched <value>', ->
assert.is_not_nil p\match 'foo '
it 'does not match if the named capture <named> did not match <value>', ->
assert.is_nil p\match 'bar '
it 'produces no captures', ->
assert.equals 1, #{ p\match 'foo ' }
describe 'last_token_matches(pattern)', ->
it 'matches if the last non-blank token matches pattern', ->
p = l.blank^0 * l.digit^1 * l.blank^0 * l.last_token_matches(l.digit)
assert.is_not_nil p\match '123 '
assert.is_not_nil p\match '123 \t '
assert.is_not_nil p\match ' 123 '
assert.is_not_nil p\match ' 1 '
assert.is_not_nil p\match '1 '
assert.is_not_nil p\match '1 '
assert.is_not_nil p\match ' 1'
describe 'match_back(name)', ->
p = Cg(P'x', 'start') * 'y' * l.match_back('start')
it 'matches the named capture given by <name>', ->
assert.equals 4, p\match 'xyxzx'
it 'produces no captures', ->
assert.equals 1, #{ p\match 'xyxzx' }
describe 'scan_until(stop_p [, escape_p])', ->
it 'matches until the specified pattern or <EOF>', ->
assert.equals 3, (l.scan_until('x') * Cp!)\match '12x'
assert.equals 4, (l.scan_until('x') * Cp!)\match '123'
it 'allows escaping <stop_p> with <escape_p>', ->
p = l.scan_until('}', '\\') * Cp!
assert.equals 4, p\match '{\\}}'
describe 'scan_to(stop_p [, escape_p])', ->
it 'matches until the specified pattern or <EOF>', ->
assert.equals 4, (l.scan_to('x') * Cp!)\match '12x'
assert.equals 4, (l.scan_to('x') * Cp!)\match '123'
it 'allows escaping <stop_p> with <escape_p>', ->
p = l.scan_to('}', '\\') * Cp!
assert.equals 5, p\match '{\\}}'
describe 'scan_through_indented', ->
p = P' ' * l.scan_through_indented! * Cp!
it 'matches until the indentation is smaller or equal to the current line', ->
assert.equals 4, p\match ' x\n y'
assert.equals 8, p\match ' x\n y\n z'
it 'matches until eol if it can not find any line with smaller or equal indentation', ->
assert.equals 7, p\match ' x\n y'
it 'uses the indentation of the line containing eol if positioned right at it', ->
p = l.eol * l.scan_through_indented! * Cp!
assert.equals 8, p\match ' x\n y\n z', 3
describe 'scan_until_capture(name, escape, [, halt_at, halt_at_N, ..])', ->
it 'matches until the named capture', ->
p = Cg('x', 'start') * l.scan_until_capture('start')
assert.equals 4, p\match 'xyzx'
it 'stops matching at any optional halt_at parameters', ->
p = Cg('x', 'start') * l.scan_until_capture('start', nil, 'z')
assert.equals 3, p\match 'xyzx'
it 'treats all stop parameters as strings and not patterns', ->
p = Cg('x', 'start') * l.scan_until_capture('start', nil, '%w')
assert.equals 4, p\match 'xyz%w'
it 'does not halt on escaped matches', ->
p = Cg('x', 'start') * l.scan_until_capture('start', '\\', 'z')
assert.equals 7, p\match 'xy\\x\\zx'
it 'matches until eof if no match is found', ->
p = Cg('x', 'start') * l.scan_until_capture('start')
assert.equals 4, p\match 'xyz'
describe 'match_until(stop_p, p)', ->
p = l.match_until('\n', C(l.alpha)) * Cp!
it 'matches p until stop_p matches', ->
assert.same { 'x', 'y', 'z', 4 }, { p\match 'xyz\nx' }
it 'matches until eof if stop_p is not found', ->
assert.same { 'x', 'y', 3 }, { p\match 'xy' }
describe 'complement(p)', ->
it 'matches if <p> does not match', ->
assert.is_not_nil l.complement('a')\match 'b'
assert.is_nil l.complement('a')\match 'a'
assert.equals 3, (l.complement('a')^1 * Cp!)\match 'bca'
describe 'sub_lex_by_pattern(mode_p, mode_style, stop_p)', ->
context 'when no mode is found for the <mode_p> capture', ->
it 'emits mode match styling and an embedded capture for the sub text', ->
p = l.sub_lex_by_pattern(l.alpha^1, 'keyword', '>')
res = { p\match 'xx123>' }
assert.same {
1, 'keyword', 3,
3, 'embedded', 6
}, res
context 'when a mode matching the <mode_p> capture exists', ->
local p
before_each ->
sub_mode = lexer: l -> capture('number', digit^1)
mode.register name: 'dynsub', create: -> sub_mode
p = l.P'<' * l.sub_lex_by_pattern(l.alpha^1, 'keyword', '>')
after_each ->
mode.unregister 'dynsub'
it 'emits mode match styling and rebasing instructions to the styler', ->
assert.same {
2, 'keyword', 8,
8, {}, 'dynsub|embedded'
}, { p\match '<dynsub>' }
it "lexes the content using that mode's lexer until <stop_p>", ->
assert.same {
2, 'keyword', 8,
8, { 1, 'number', 4 }, 'dynsub|embedded'
}, { p\match '<dynsub123>' }
it 'lexes any leading space followed by eol as extended whitespace', ->
p = l.sub_lex_by_pattern(l.alpha^1, 'keyword', '>')
res = { p\match 'xx \n123>' }
assert.same {
1, 'keyword', 3,
3, 'default:whitespace', 5,
5, 'embedded', 8
}, res
describe 'sub_lex(mode_name, stop_p)', ->
context 'when no mode is found matching <mode_name>', ->
it 'captures using the embedded style until stop_p', ->
p = l.sub_lex('unknown', '>')
res = { p\match 'xx>' }
assert.same {1, 'embedded', 3}, res
context 'when a mode matching <mode_name> exists', ->
local p
before_each ->
sub_mode = lexer: l -> capture('number', digit^1)
mode.register name: 'sub', create: -> sub_mode
p = l.sub_lex('sub', '>')
after_each ->
mode.unregister 'sub'
sub_captures_for = (text) ->
res = { p\match text }
res[2]
it 'emits rebasing instructions to the styler', ->
assert.same { 1, {}, 'sub|embedded' }, { p\match '' }
it "lexes the content using that mode's lexer until <stop_p>", ->
assert.same {1, 'number', 3}, sub_captures_for '12>'
it 'lexes until EOF if <stop_p> is not found', ->
assert.same {1, 'number', 3}, sub_captures_for '12'
it 'lexes any leading space followed by eol as extended whitespace', ->
p = l.sub_lex('unknown', '>')
res = { p\match ' \n123>' }
assert.same {
1, 'default:whitespace', 3,
3, 'embedded', 6
}, res
describe 'compose(base_mode, pattern)', ->
it 'returns a conjunction pattern with <pattern> and the mode pattern', ->
base_mode = lexer: l -> capture('number', digit^1)
mode.register name: 'base_mode', create: -> base_mode
p = l.compose('base_mode', l.capture('override', l.alpha))^0
assert.same {
1, 'override', 2,
2, 'number', 3
}, { p\match 'a2' }
describe 'built-in lexing support', ->
it 'automatically lexes whitespace', ->
lexer = l -> P'peace-and-quiet'
assert.same { 1, 'whitespace', 3 }, lexer ' \n'
it 'automatically skips non-recognized tokens', ->
lexer = l -> capture 'foo', P'foo'
assert.same { 2, 'foo', 5 }, lexer '|foo'
| 35.419098 | 122 | 0.588182 |
2b9ca44446c3ccab2da4d7fbcd908d4275c36103 | 1,947 |
luasocket = do
import flatten from require "pgmoon.util"
proxy_mt = {
__index: (key) =>
sock = @sock
original = sock[key]
if type(original) == "function"
fn = (_, ...) ->
original sock, ...
@[key] = fn
fn
else
original
}
overrides = {
send: true
getreusedtimes: true
sslhandshake: true,
settimeout: true
}
{
tcp: (...) ->
socket = require "socket"
sock = socket.tcp ...
proxy = setmetatable {
:sock
send: (...) => @sock\send flatten ...
getreusedtimes: => 0
settimeout: (t) =>
if t
t = t/1000
@sock\settimeout t
sslhandshake: (opts={}) =>
ssl = require "ssl"
params = {
mode: "client"
protocol: "any"
verify: "none"
options: { "all", "no_sslv2", "no_sslv3", "no_tlsv1" }
}
for k,v in pairs opts
params[k] = v
sec_sock, err = ssl.wrap @sock, params
return false, err unless sec_sock
success, err = sec_sock\dohandshake!
return false, err unless success
-- purge memoized socket closures
for k, v in pairs @
@[k] = nil unless type(v) ~= "function" or overrides[k]
@sock = sec_sock
true
}, proxy_mt
proxy
}
{
new: (socket_type) ->
if socket_type == nil
-- choose the default socket, try to use nginx, otherwise default to
-- luasocket
socket_type = if ngx and ngx.get_phase! != "init"
"nginx"
else
"luasocket"
socket = switch socket_type
when "nginx"
ngx.socket.tcp!
when "luasocket"
luasocket.tcp!
when "cqueues"
require("pgmoon.cqueues").CqueuesSocket!
else
error "unknown socket type: #{socket_type}"
socket, socket_type
}
| 21.395604 | 74 | 0.504879 |
e8bf064fffa781f91a747171e13cbc591a88cb90 | 1,564 |
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 = (q) ->
l = config.logging
return unless l and l.queries
print colors("%{bright}%{cyan}SQL: %{reset}%{magenta}#{q}%{reset}")
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 = (name) ->
print colors("%{bright}%{yellow}Migrating: %{reset}%{green}#{name}%{reset}")
migration_summary = (count) ->
noun = if count == 1
"migration"
else
"migrations"
print colors("%{bright}%{yellow}Ran%{reset} #{count} %{bright}%{yellow}#{noun}")
{ :request, :query, :migration, :migration_summary, :flatten_params }
| 21.135135 | 82 | 0.620205 |
b53de668997c030ac7db5b93332a9fa8d348e03e | 139 | export modinfo = {
type: "command"
desc: "Remove tablets"
alias: {"dt", "dismiss", "verify"}
func: (Msg,Speaker) ->
DismissTablets!
} | 19.857143 | 35 | 0.640288 |
e34430e53167209627905fb6474a4c88ac381761 | 317 | {
lexer: bundle_load 'vue_lexer'
comment_syntax: { '<!--', '-->' }
auto_pairs:
'(': ')'
'[': ']'
'{': '}'
'"': '"'
"'": "'"
'<': '>'
indentation:
more_after:
'<%a>%s*$'
{ '<[^/!][^<]*[^/]>%s*$', r'<(br|input)[\\s>][^<]*$' }
less_for:
'^%s*</[^>]+>%s*$'
}
| 14.409091 | 60 | 0.290221 |
13fbc5d970fc7be1fc6749fc3a09a309df5e9486 | 1,837 | alphabet = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"
alphabet_i_to_char = { i, alphabet\sub(i,i) for i=1,#alphabet }
alphabet_char_to_i = { alphabet\sub(i,i), i for i=1,#alphabet }
-- TODO: null byte in string seems to break things
-- represents number as array of bytes (unpacked string)
class BigInt
@from_string: (str) =>
@ { str\reverse!\byte 1, -1 }
new: (@bytes={}) =>
is_zero: =>
for b in *@bytes
return false if b != 0
true
to_string: =>
string.char(unpack @bytes)\reverse!
-- will overflow if the number is truly big
to_number: =>
sum = 0
k = 1
for val in *@bytes
sum += val * k
k *= 256
sum
add: (num) =>
k = 1
while true
@bytes[k] = (@bytes[k] or 0) + num
break if @bytes[k] < 256
num = math.floor @bytes[k] / 256
@bytes[k] = @bytes[k] % 256
k += 1
-- mul must be < 256
mul: (mul) =>
last_idx = 1
r = 0
for idx=1,#@bytes
cur = @bytes[idx] * mul + r
@bytes[idx] = cur % 256
r = math.floor cur / 256
last_idx = idx
if r > 0
@bytes[last_idx + 1] = r
nil
-- div must be < 256
div: (div) =>
local r
for idx=#@bytes,1,-1
b = @bytes[idx]
b += r * 256 if r
q, r = math.floor(b / div), b % div
@bytes[idx] = q
@, r
encode_base58 = (str) ->
buffer = {}
int = BigInt\from_string str
while not int\is_zero!
_, r = int\div 58
table.insert buffer, alphabet_i_to_char[r + 1]
table.concat buffer
decode_base58 = (str) ->
out = BigInt!
for i=#str,1,-1
char = str\sub i,i
char_i = alphabet_char_to_i[char]
return nil, "invalid string" unless char_i
char_byte = char_i - 1
out\mul 58
out\add char_byte
out\to_string!
{ :BigInt, :encode_base58, :decode_base58 }
| 19.542553 | 71 | 0.568862 |
93bb6f4820de2a9d40a5e361ec1c789066ea411b | 3,062 | import type from _G
import lower from string
import insert from table
import Object from require "core"
import endswith from "novacbn/lunarbook/lib/utilities/string"
-- ::pass(any ...) -> any ...
-- Returns all input arguments
--
pass = (...) -> return ...
-- ::RegisteredTransformer(string ext, function transform, function post) -> RegisteredTransformer
-- Represents a registered transformer
--
RegisteredTransformer = (ext, transform, post) -> {
-- RegisteredTransformers::ext -> string
-- Represents the extension used by the transformer
--
ext: ext
-- RegisteredTransformers::post -> function
-- Represents the post processing function of the transformer
--
post: post
-- RegisteredTransformers::transform -> function
-- Represents the transformation function of the transformer
--
transform: transform
}
-- Transformers::Transformers()
-- Represents the transformers registered for LunarBook related files
-- export
export Transformers = with Object\extend()
-- Transformers::fragmentTransformers -> table
-- Represents the registered fragment transformers
--
.fragmentTransformers = nil
-- Transformers::initialize() -> void
-- Constructor for Transformer
--
.initialize = () =>
@fragmentTransformers = {}
-- Transformers::registerFragment(string ext, function transform, function post?) -> void
-- Registers a fragment transformer
--
.registerFragment = (ext, transform, post=pass) =>
error("bad argument #1 to 'registerFragment' (expected string)") unless type(ext) == "string"
error("bad argument #2 to 'registerFragment' (expected function)") unless type(transform) == "function"
error("bad argument #3 to 'registerFragment' (expected function)") unless type(post) == "function"
ext = lower(ext)
error("bad argument #1 to 'registerFragment' (pre-existing transformer)") if @fragmentTransformers[ext]
insert(@fragmentTransformers, RegisteredTransformer(ext, transform, post))
-- Transformers::processFragment(string file, boolean inDev, string contents) -> string
-- Processes the book fragment into a HTML fragment
--
.processFragment = (file, inDev, contents) =>
error("bad argument #1 to 'processFragment' (expected string)") unless type(file) == "string"
error("bad argument #2 to 'processFragment' (expected boolean)") unless type(inDev) == "boolean"
error("bad argument #3 to 'processFragment' (expected string)") unless type(contents) == "string"
local selectedTransformer
file = lower(file)
for transformer in *@fragmentTransformers
if endswith(file, transformer.ext)
selectedTransformer = transformer
break
error("bad argument #1 to 'processFragment' (unexpected extension)") unless selectedTransformer
contents = selectedTransformer.transform(inDev, contents)
contents = selectedTransformer.post(inDev, contents)
return contents | 38.275 | 111 | 0.686153 |
69cd41befedf40e5fa25928f3881117b7a078320 | 3,362 | -- Copyright 2012-2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, command, config from howl
import style from howl.ui
command.register
name: 'window-toggle-fullscreen',
description: 'Toggles fullscreen for the current window'
handler: -> app.window.fullscreen = not app.window.fullscreen
command.register
name: 'window-toggle-maximized',
description: 'Toggles maximized state for the current window'
handler: -> app.window.maximized = not app.window.maximized
command.register
name: 'describe-style',
description: 'Describes the current style at cursor'
handler: ->
name, def = style.at_pos app.editor.buffer, app.editor.cursor.pos
log.info "#{name}"
command.register
name: 'zoom-in',
description: 'Increases the current font size by 1 (globally)'
handler: ->
size = config.font_size + 1
config.font_size = size
log.info "zoom-in: global font size set to #{size}"
command.register
name: 'zoom-out',
description: 'Decreases the current font size by 1 (globally)'
handler: ->
size = config.font_size - 1
if size <= 6
log.error 'zoom-out: minimum font size reached (6)'
else
config.font_size = size
log.info "zoom-out: global font size set to #{size}"
command.register
name: "view-close",
description: "Closes the current view"
handler: ->
if #app.window.views > 1
app.window\remove_view!
collectgarbage!
else
log.error "Can't close the one remaining view"
command.register
name: "view-next",
description: "Focuses the next view, wrapping around as necessary"
handler: ->
target = app.window\siblings(nil, true).right
if target
target\grab_focus!
else
log.warn "No other view found"
for cmd in *{
{ 'left', 'left_of', 'Goes to the left view, creating it if necessary' }
{ 'right', 'right_of', 'Goes to the right view, creating it if necessary' }
{ 'up', 'above', 'Goes to the view above, creating it if necessary' }
{ 'down', 'below', 'Goes to the view below, creating it if necessary' }
}
{ direction, placement, description } = cmd
human_placement = placement\gsub '_', ' '
command.register
name: "view-#{direction}",
description: "Goes to the view #{human_placement} the current one if present"
handler: ->
target = app.window\siblings![direction]
if target
target\grab_focus!
else
log.info "No view #{human_placement} the current one found"
command.register
name: "view-#{direction}-wraparound",
description: "Goes to the view #{human_placement} the current one if present"
handler: ->
target = app.window\siblings(true)[direction]
if target
target\grab_focus!
else
log.info "No view #{human_placement} the current one found"
command.register
name: "view-#{direction}-or-create",
description: "Goes to the view #{human_placement} the current one, creating it if necessary"
handler: ->
target = app.window\siblings![direction]
if target
target\grab_focus!
else
howl.app\new_editor :placement
command.register
name: "view-new-#{placement\gsub '_', '-'}",
description: "Adds a new view #{human_placement} the current one"
handler: -> howl.app\new_editor :placement
| 31.716981 | 96 | 0.678465 |
d145072fe0b1568d25c5d5c62f058ee8fc0c1387 | 4,217 | im = require "cimgui"
CollapsingHeader = im.CollapsingHeader_TreeNodeFlags
BulletTextWrapped = (text) ->
im.Bullet()
im.TextWrapped(text)
return ->
if CollapsingHeader("General information")
BulletTextWrapped("Saving is only allowed when changes are detected, in which case the menu bar will be highlighted.")
BulletTextWrapped("Closed windows can be reopened from the View menu.")
BulletTextWrapped("Some of the menu entries list keyboard shortcuts that can be used to easily access them.")
if CollapsingHeader("Editing the polygon maps")
if im.TreeNode_Str("Basic operations")
BulletTextWrapped("Polygon maps can be added with the \"New polygon map\" button.")
BulletTextWrapped("The polygon map to be edited can be selected by clicking on its name on the list.")
BulletTextWrapped("To rename or delete a polygon map right-click on its name to bring up the context menu.")
BulletTextWrapped("Click on the polygon map checkbox to hide/unhide it (checked means unhidden). Only named polygon maps can be hidden.")
im.TreePop()
if im.TreeNode_Str("Adding polygons")
BulletTextWrapped("To add a new polygon to the selected polygon map left-click on an empty space to add a vertex. Repeat until all vertices have been created, then click on the first vertex to close the polygon.")
BulletTextWrapped("While creating a new polygon you can right-click anywhere to remove the last added point.")
BulletTextWrapped("When a polygon is added the polygon map is automatically updated to become the union of its polygons. Adding overlapping polygons is an easy way to build more complex polygon maps.")
im.TreePop()
if im.TreeNode_Str("Modifying polygons")
BulletTextWrapped("Left-click on a vertex and drag the mouse to move a vertex around.")
BulletTextWrapped("Right-click on a vertex to remove it.")
BulletTextWrapped("Left-click on an edge to add a vertex at the cursor location. Hold the button down and drag to move the newly created point.")
im.TreePop()
if im.TreeNode_Str("Subtract mode")
BulletTextWrapped("Use \"Edit->Subtract mode\" to enable.")
BulletTextWrapped("While in subract mode, newly created polygons are subtracted from the polygon map instead of being added.")
BulletTextWrapped("Subtract mode can be used to \"carve\" pieaces out or to create holes in the polygon map.")
im.TreePop()
if im.TreeNode_Str("Refresh & simplify")
BulletTextWrapped("Refreshing a polygon map (\"Edit->Refresh polygon map\") can be used to take the union of the polygons in the polygon map if overlapping was created by moving vertices.")
BulletTextWrapped("Use \"Edit->Simplify polygon map\" to automatically remove unneeded vertices. Note that this may remove points that are needed to connect different polygon maps, so use it carefully.")
im.TreePop()
if im.TreeNode_Str("Notes on multiple polygon maps")
BulletTextWrapped("Two polygons belonging to different polygon maps are considered connected only if they share an edge. You may need to move some vertices if they were not perfectly aligned.")
BulletTextWrapped("You can switch to testing mode to check if the polygon maps are properly connected.")
im.TreePop()
if CollapsingHeader("Testing mode")
BulletTextWrapped("Use \"Edit->Testing mode\" from the Navigation window to test pathfinding on the navigation area.")
BulletTextWrapped("While in testing mode right-click on the navigation area to set the starting point. The target point follows the cursor.")
BulletTextWrapped("Named polygon maps can also be hidden/unhidden in testing mode.")
if CollapsingHeader("Camera")
BulletTextWrapped("While holding space, click on the canvas and drag the mouse to move the camera.")
BulletTextWrapped("Use the mouse wheel when the cursor is on the canvas to zoom in/out.")
BulletTextWrapped("Use \"View->Reset View\" to reset panning and zoom.")
| 71.474576 | 225 | 0.712118 |
212c902c1b72804224bca88a873e3460e4ad7923 | 2,703 | -- Copyright 2013-2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
core = require 'ljglibs.core'
ffi = require 'ffi'
C = ffi.C
def = {
constants: {
prefix: 'GDK_'
-- GdkEventType;
'NOTHING',
'DELETE',
'DESTROY',
'EXPOSE',
'MOTION_NOTIFY',
'BUTTON_PRESS',
'2BUTTON_PRESS',
'DOUBLE_BUTTON_PRESS',
'3BUTTON_PRESS',
'TRIPLE_BUTTON_PRESS',
'BUTTON_RELEASE',
'KEY_PRESS',
'KEY_RELEASE',
'ENTER_NOTIFY',
'LEAVE_NOTIFY',
'FOCUS_CHANGE',
'CONFIGURE',
'MAP',
'UNMAP',
'PROPERTY_NOTIFY',
'SELECTION_CLEAR',
'SELECTION_REQUEST',
'SELECTION_NOTIFY',
'PROXIMITY_IN',
'PROXIMITY_OUT',
'DRAG_ENTER',
'DRAG_LEAVE',
'DRAG_MOTION',
'DRAG_STATUS',
'DROP_START',
'DROP_FINISHED',
'CLIENT_EVENT',
'VISIBILITY_NOTIFY',
'SCROLL',
'WINDOW_STATE',
'SETTING',
'OWNER_CHANGE',
'GRAB_BROKEN',
'DAMAGE',
'TOUCH_BEGIN',
'TOUCH_UPDATE',
'TOUCH_END',
'TOUCH_CANCEL',
'EVENT_LAST',
-- GdkEventMask;
'EXPOSURE_MASK',
'POINTER_MOTION_MASK',
'POINTER_MOTION_HINT_MASK',
'BUTTON_MOTION_MASK',
'BUTTON1_MOTION_MASK',
'BUTTON2_MOTION_MASK',
'BUTTON3_MOTION_MASK',
'BUTTON_PRESS_MASK',
'BUTTON_RELEASE_MASK',
'KEY_PRESS_MASK',
'KEY_RELEASE_MASK',
'ENTER_NOTIFY_MASK',
'LEAVE_NOTIFY_MASK',
'FOCUS_CHANGE_MASK',
'STRUCTURE_MASK',
'PROPERTY_CHANGE_MASK',
'VISIBILITY_NOTIFY_MASK',
'PROXIMITY_OUT_MASK',
'SUBSTRUCTURE_MASK',
'SCROLL_MASK',
'TOUCH_MASK',
'SMOOTH_SCROLL_MASK',
'ALL_EVENTS_MASK',
-- GdkModifierType
'SHIFT_MASK',
'LOCK_MASK',
'CONTROL_MASK',
'MOD1_MASK',
'MOD2_MASK',
'MOD3_MASK',
'MOD4_MASK',
'MOD5_MASK',
'BUTTON1_MASK',
'BUTTON2_MASK',
'BUTTON3_MASK',
'BUTTON4_MASK',
'BUTTON5_MASK',
'MODIFIER_RESERVED_13_MASK',
'MODIFIER_RESERVED_14_MASK',
'MODIFIER_RESERVED_15_MASK',
'MODIFIER_RESERVED_16_MASK',
'MODIFIER_RESERVED_17_MASK',
'MODIFIER_RESERVED_18_MASK',
'MODIFIER_RESERVED_19_MASK',
'MODIFIER_RESERVED_20_MASK',
'MODIFIER_RESERVED_21_MASK',
'MODIFIER_RESERVED_22_MASK',
'MODIFIER_RESERVED_23_MASK',
'MODIFIER_RESERVED_24_MASK',
'MODIFIER_RESERVED_25_MASK',
'SUPER_MASK',
'HYPER_MASK',
'META_MASK',
'MODIFIER_RESERVED_29_MASK',
'RELEASE_MASK',
'MODIFIER_MASK',
-- GdkScrollDirection;
'SCROLL_UP',
'SCROLL_DOWN',
'SCROLL_LEFT',
'SCROLL_RIGHT',
'SCROLL_SMOOTH'
}
}
def.KEY_Return = 0xff0d
core.auto_loading 'gdk', def
| 20.792308 | 79 | 0.643729 |
457ff0755f2bdb624918fb79c3140408bf80598e | 3,323 | import PropertyObject from howl.util.moon
match = require 'luassert.match'
describe 'PropertyObject', ->
it 'allows specifying a getter and setter using get and set', ->
value = 'hello'
class Test extends PropertyObject
@property foo:
get: => value
set: (v) => value = v
o = Test!
assert.equal o.foo, 'hello'
o.foo = 'world'
assert.equal o.foo, 'world'
it 'assigning a property with only a getter raises a read-only error', ->
class Test extends PropertyObject
@property foo: get: => 'foo'
o = Test!
assert.raises 'read%-only', -> o.foo = 'bar'
assert.equal o.foo, 'foo'
it 'two objects of the same class have the same metatable', ->
class Test extends PropertyObject
@property foo: get: => 'foo'
assert.equal getmetatable(Test!), getmetatable(Test!)
it 'two objects of different classes have different metatables', ->
class Test1 extends PropertyObject
@property foo: get: => 'foo'
class Test2 extends PropertyObject
@property foo: get: => 'foo'
assert.is_not.equal getmetatable(Test1!), getmetatable(Test2!)
it 'meta methods are defined via the @meta function', ->
class Test extends PropertyObject
@meta __add: (o1, o2) -> 3 + o2
assert.equal 5, Test! + 2
describe 'inheritance', ->
it 'properties defined in any part of the chain works', ->
class Parent extends PropertyObject
new: (foo) =>
super!
@_foo = foo
@property foo:
get: => @_foo or 'wrong'
set: (v) => @_foo = v .. @foo
class SubClass extends Parent
new: (text) => super text
@property bar:
get: => @_bar
set: (v) => @_bar = v
parent = Parent 'parent'
assert.equal parent.foo, 'parent'
parent.foo = 'hello '
assert.equal parent.foo, 'hello parent'
s = SubClass 'editor'
assert.equal s.foo, 'editor'
s.foo = 'hello'
assert.equal s.foo, 'helloeditor'
s.bar = 'world'
assert.equal s.bar, 'world'
it 'overriding methods work', ->
class Parent extends PropertyObject
foo: => 'parent'
class SubClass extends Parent
foo: => 'sub'
assert.equal SubClass!\foo!, 'sub'
it 'write to read-only properties are detected', ->
class Parent extends PropertyObject
@property foo: get: => 1
class SubClass extends Parent
true
assert.raises 'read%-only', -> SubClass!.foo = 'bar'
it 'meta methods defined in any part of the chain works', ->
class Parent extends PropertyObject
@meta __add: (o1, o2) -> 3 + o2
class SubClass extends Parent
@meta __div: (o1, o2) -> 'div'
o = SubClass!
assert.equal 5, o + 2
assert.equal 'div', o / 2
describe 'delegation', ->
it 'allows delegating to a default object passed in the constructor', ->
target = {
foo: 'bar'
func: spy.new -> 'return'
}
class Delegating extends PropertyObject
new: => super target
@property frob: get: => 'nic'
o = Delegating!
assert.equals 'nic', o.frob
assert.equals 'bar', o.foo
assert.equals 'return', o\func!
assert.spy(target.func).was.called_with match.is_ref(target)
| 27.46281 | 76 | 0.598556 |
a582d77a163eccad75e419faf4a75661bd23a558 | 8 | "0.0.2"
| 4 | 7 | 0.375 |
28ad12d031ae5cd2369e3fdd9811323842564992 | 613 | Color = require 'ljglibs.pango.color'
describe 'Color', ->
describe '(construction)', ->
it 'accepts the color values as (r, g, b)', ->
color = Color 1, 2, 3
assert.equal 1, color.red
assert.equal 2, color.green
assert.equal 3, color.blue
it 'accepts a single string containing a specification', ->
color = Color '#ff00ff'
assert.equal 65535, color.red
assert.equal 0, color.green
assert.equal 65535, color.blue
it 'tostring(color) returns the color specification', ->
color = Color '#ff00ff'
assert.equal '#ffff0000ffff', tostring color
| 30.65 | 63 | 0.642741 |
f6f2c67d9cd7e75064d9c63ef3dcb87a97c2a759 | 10,042 | -- Copyright 2018 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:activities, :config, :io, :sys} = howl
{:File, :Process, :process_output} = io
ffi = require 'ffi'
{:max, :min} = math
{string: ffi_string} = ffi
append = table.insert
file_sep = File.separator
searchers = {}
MAX_MESSAGE_LENGTH = 150
run_search_command = (process, directory, query) ->
out, err = activities.run_process {
title: "Searching for '#{query}' in '#{directory}'"
}, process
unless process.exited_normally
error "#{process.exit_status_string}: #{err}"
if process.successful
process_output.parse out, {
:directory,
max_message_length: MAX_MESSAGE_LENGTH
}
else
{}
load_searcher = (name, directory) ->
searcher = searchers[name]
error "Unknown searcher '#{name}'" unless searcher
if searcher.is_available
available, err = searcher.is_available(directory)
error "Searcher '#{name}' unavailable (#{err})" unless available
searcher
get_searcher_for = (directory) ->
cfg = config.for_file directory
sel = cfg.file_searcher
local searcher
if sel != 'auto'
searcher = load_searcher sel, directory
else
candidates = {'rg', 'ag', 'native'}
for candidate in *candidates
s = searchers[candidate]
if not s or (s.is_available and not s.is_available(directory))
continue
searcher = s
break
unless searcher
error "No searcher available (tried #{table.concat(candidates, ',')})"
searcher
prepare_direct_results = (searcher, directory, results) ->
for r in *results
unless r.path
error "Misbehaving searcher '#{searcher.name}': Missing .path in result"
unless r.line_nr
error "Misbehaving searcher '#{searcher.name}': Missing .line_nr in result"
unless r.message
error "Misbehaving searcher '#{searcher.name}': Missing .message in result"
r.file = directory\join(r.path) unless r.file
search = (directory, what, opts = {}) ->
searcher = if type(opts.searcher) == 'string'
load_searcher(opts.searcher, directory)
else
opts.searcher
searcher or= get_searcher_for directory
res = searcher.handler directory, what, {
whole_word: opts.whole_word or false,
max_message_length: MAX_MESSAGE_LENGTH
}
t = typeof res
if t == 'Process'
res = run_search_command res, directory, what
elseif t == 'string'
p = Process.open_pipe res, working_directory: directory
res = run_search_command p, directory, what
else
prepare_direct_results searcher, directory, res
res, searcher
sort = (matches, directory, term, context) ->
activities.run {
title: "Sorting '#{#matches}' search matches",
status: -> "Sorting..",
}, ->
standalone_p, basename_search_p = if r'^\\p{L}+$'
r"\\b#{term}\\b", r"\\b#{term}\\b[^#{file_sep}]*$"
test_suffix_p = r'[_-](?:spec|test)\\.\\w+$'
test_prefix_p = r"(?:^|#{file_sep})test_[^#{file_sep}]+$"
path_split_p = "[^#{file_sep}]+"
path_split = (p) -> [m for m in p\gmatch path_split_p]
local rel_path
cur_segments = if context
file = context.buffer.file
if file
rel_path = file\relative_to_parent directory
path_split rel_path
name_cluster_p = if rel_path
base = rel_path\umatch r'(.+?)(?:[_-](spec|test))?\\.\\w+$'
"#{base}[._-]"
scores = {}
-- base score is 20, with higher being better
for i = 1, #matches
activities.yield! if i % 2000 == 0
m = matches[i]
continue if scores[m.path]
score = 20
if standalone_p and standalone_p\test(m.message)
score += 3
if cur_segments
-- distance affects score, up to a 10 point difference
m_segments = path_split m.path
distance = 0
for j = 1, max(#m_segments, #cur_segments)
if cur_segments[j] != m_segments[j]
distance += ((#m_segments - j) + (#cur_segments - j)) + 1
break
score -= min distance, 10
-- check for same name cluster
if name_cluster_p and #m_segments > 0
if m_segments[#m_segments]\find name_cluster_p
score += 4
if basename_search_p and basename_search_p\test(m.path)
score += 3
if test_suffix_p\test(m.path) or test_prefix_p\test(m.path)
score -= 2
scores[m.path] = score
sorted = [m for m in *matches]
counter = 0
table.sort sorted, (a, b) ->
activities.yield! if counter % 3000 == 0
counter += 1
if a.path == b.path
return a.line_nr < b.line_nr
score_a, score_b = scores[a.path], scores[b.path]
if score_a != score_b
score_a > score_b
else
a.path > b.path
sorted
register_searcher = (opts) ->
for field in *{'name', 'description', 'handler'}
error '`' .. field .. '` missing', 2 if not opts[field]
searchers[opts.name] = opts
unregister_searcher = (name) ->
searchers[name] = nil
config.define
name: 'file_searcher'
description: 'The searcher to use for searching files'
type_of: 'string'
default: 'auto'
options: ->
opts = [{name, opts.description} for name, opts in pairs searchers]
table.insert opts, 1, {'auto', 'Pick an available searcher automatically'}
opts
-- the silver searcher
config.define
name: 'ag_executable'
description: 'The silver searcher executable to use'
default: 'ag'
type_of: 'string'
register_searcher {
name: 'ag'
description: 'The Silver Searcher'
is_available: (directory) ->
cfg = config.for_file directory
return true if sys.find_executable(cfg.ag_executable)
false, "Executable 'ag' not found"
handler: (directory, what, opts) ->
cfg = config.for_file directory
if opts.whole_word
what = "\\b#{what}\\b"
Process.open_pipe {
cfg.ag_executable,
'--nocolor',
'--column',
'-C', '0',
'--nogroup',
what
}, working_directory: directory
}
-- ripgrep
config.define
name: 'rg_executable'
description: 'The ripgrep executable to use'
default: 'rg'
type_of: 'string'
register_searcher {
name: 'rg'
description: 'Ripgrep'
is_available: (directory) ->
cfg = config.for_file directory
return true if sys.find_executable(cfg.rg_executable)
false, "Executable 'rg' not found"
handler: (directory, what, opts = {}) ->
cfg = config.for_file directory
if opts.whole_word
what = "\\b#{what}\\b"
Process.open_pipe {
cfg.rg_executable,
'--color', 'never',
'--line-number',
'--column',
'--no-heading',
'--max-columns', opts.max_message_length or 150
what
}, working_directory: directory
}
-- native searcher
native_paths = (dir) ->
activities.run {
title: "Reading paths for '#{dir}'",
status: -> "Reading paths for '#{dir}'",
}, ->
ignore = howl.util.ignore_file.evaluator dir
skip_exts = {ext, true for ext in *config.hidden_file_extensions}
-- skip additional known binary extensions
for ext in *{
'gz',
'tar',
'tgz',
'zip',
'png',
'jpg',
'jpeg',
'gif',
'ttf',
'woff',
'eot',
'otf'
}
skip_exts[ext] = true
filter = (p) ->
return true if p\ends_with('~')
ext = p\match '%.(%w+)/?$'
return true if skip_exts[ext]
ignore p
dir\find_paths exclude_directories: true, :filter
native_append_matches = (path, positions, mf, matches, max_message_length) ->
contents = mf.contents
upper = #mf - 1
scan_to = (pos, start_pos, line) ->
i = start_pos
l_start_pos = start_pos
pos = min pos, upper
new_line = 0
while i <= upper
c = contents[i]
if c == 10
new_line = 1
elseif c == 13
new_line = 1
if (i + 1) < upper and contents[i + 1] == 10
new_line += 1
if new_line > 0
if pos <= i
return line, l_start_pos, i - 1
line += 1
i += new_line
l_start_pos = i
new_line = 0
else
i += 1
if pos <= i
return line, l_start_pos, i - 1
nil
start_pos = 0
line = 1
for p in *positions
continue if p < start_pos -- we've reported on this line already
line, l_start_pos, l_end_pos = scan_to p, start_pos, line
break unless line
start_pos = l_end_pos
len = l_end_pos - l_start_pos + 1
if max_message_length
len = min max_message_length, len
append matches, {
:path
line_nr: line,
column: (p - l_start_pos) + 1,
message: ffi.string(contents + l_start_pos, max(len, 0))
}
register_searcher {
name: 'native'
description: 'Naive but native Howl searcher'
handler: (directory, what, opts = {}) ->
MappedFile = require 'ljglibs.glib.mapped_file'
GRegex = require 'ljglibs.glib.regex'
p = what.ulower
if opts.whole_word
p = "\\b#{p}\\b"
r = GRegex p, {'CASELESS', 'OPTIMIZE', 'RAW'}
paths = native_paths directory
dir_path = directory.path
matches = {}
count = 0
activities.run {
title: "Searching for '#{what}' in '#{directory}'",
status: -> "Searched #{count} out of #{#paths} files..",
}, ->
for i = 1, #paths
activities.yield! if i % 100 == 0
p = paths[i]
status, mf = pcall MappedFile, "#{dir_path}/#{p}"
continue unless status
contents = mf.contents
continue unless contents and contents != nil
unless ffi_string(contents, min(150, #mf)).is_likely_binary
info = r\match_full_with_info contents, #mf, 0
match_positions = {}
if info
while info\matches!
start_pos = info\fetch_pos 0
append match_positions, start_pos
info\next!
native_append_matches p, match_positions, mf, matches, opts.max_message_length
mf\unref!
count += 1
matches
}
{
:searchers
:register_searcher
:unregister_searcher
:search
:sort
}
| 25.617347 | 90 | 0.61432 |
02c426ebd48f181b7d20f3a1659ce2fedee7d7ba | 4,510 |
-- Copyright (C) 2018-2020 DBotThePony
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
import DPP, DLib from _G
import i18n from DLib
DPP2.cmd_autocomplete.transfer = (args = '') =>
return if not IsValid(@)
[string.format('%q', ply) for ply in *DPP2.FindPlayersInArgument(args, true, true)]
DPP2.cmd_autocomplete.transferfallback = (args = '') =>
return if not IsValid(@)
[string.format('%q', ply) for ply in *DPP2.FindPlayersInArgument(args, {LocalPlayer(), @DLibGetNWEntity('dpp2_transfer_fallback', NULL)}, true)]
DPP2.cmd_autocomplete.transferent = (args = '', margs = '') =>
return if not IsValid(@)
args = DPP2.SplitArguments(args)
return [string.format('%q', tostring(ent)) for ent in *@DPP2FindOwned()] if not args[1]
ace = DPP2.AutocompleteOwnedEntityArgument(args[1])
return [string.format('%q', ent) for ent in *ace] if margs[#margs] ~= ' ' and not args[2]
phint = '%q ' .. i18n.localize('command.dpp2.hint.player')
return [string.format(phint, ent) for ent in *ace] if not args[2]
table.remove(args, 1)
return [string.format('%q %q', ent, ply) for ent in *ace for ply in *DPP2.FindPlayersInArgument(table.concat(args, ' ')\trim(), true, true)]
DPP2.cmd_autocomplete.transfertoworldent = (args = '', margs = '') =>
return if not IsValid(@)
return [string.format('%q', tostring(ent)) for ent in *@DPP2FindOwned()] if args == ''
return DPP2.AutocompleteOwnedEntityArgument(args, true, true)
DPP2.cmd_autocomplete.transfercontraption = (args = '', margs = '') =>
return if not IsValid(@)
args = DPP2.SplitArguments(args)
return [string.format('%q', contraption\GetID()) for contraption in *DPP2.ContraptionHolder\GetAll() when contraption\HasOwner(@)] if not args[1]
local ace
args[1] = args[1]\lower()
if num = tonumber(args[1])
if contraption = DPP2.ContraptionHolder\GetByID(num)
if contraption\HasOwner(@)
ace = {'"' .. args[1] .. '"'}
else
ace = {i18n.localize('command.dpp2.hint.share.not_own_contraption')}
else
ace = [string.format('%q', contraption\GetID()) for contraption in *DPP2.ContraptionHolder\GetAll() when contraption\HasOwner(@) and contraption\GetID()\tostring()\startsWith(args[1])]
ace[1] = i18n.localize('command.dpp2.hint.none') if not ace[1]
else
ace = {'???'}
table.sort(ace)
return ace if margs[#margs] ~= ' ' and not args[2]
phint = '%s ' .. i18n.localize('command.dpp2.hint.player')
return [string.format(phint, ent) for ent in *ace] if not args[2]
table.remove(args, 1)
return [string.format('%s %q', ent, ply) for ent in *ace for ply in *DPP2.FindPlayersInArgument(table.concat(args, ' ')\trim(), true, true)]
DPP2.cmd_autocomplete.transfertoworldcontraption = (args = '', margs = '') =>
return if not IsValid(@)
args = DPP2.SplitArguments(args)
return [string.format('%q', contraption\GetID()) for contraption in *DPP2.ContraptionHolder\GetAll() when contraption\HasOwner(@)] if not args[1]
local ace
args[1] = args[1]\lower()
if num = tonumber(args[1])
if contraption = DPP2.ContraptionHolder\GetByID(num)
if contraption\HasOwner(@)
ace = {'"' .. args[1] .. '"'}
else
ace = {i18n.localize('command.dpp2.autocomplete.share.not_own_contraption')}
else
ace = [string.format('%q', contraption\GetID()) for contraption in *DPP2.ContraptionHolder\GetAll() when contraption\HasOwner(@) and contraption\GetID()\tostring()\startsWith(args[1])]
ace[1] = i18n.localize('command.dpp2.hint.none') if not ace[1]
else
ace = {'???'}
table.sort(ace)
return ace
| 45.1 | 187 | 0.711086 |
37256cc0c56f684fa8e592dbfff565f52f857e25 | 3,690 | local log
version = '1.0.4'
haveDepCtrl, DependencyControl = pcall require, 'l0.DependencyControl'
if haveDepCtrl
version = DependencyControl {
name: 'DataHandler',
:version,
description: 'A class for parsing After Effects motion data.',
author: 'torque',
url: 'https://github.com/TypesettingTools/Aegisub-Motion'
moduleName: 'a-mo.DataHandler'
feed: 'https://raw.githubusercontent.com/TypesettingTools/Aegisub-Motion/DepCtrl/DependencyControl.json'
{
{ 'a-mo.Log', version: '1.0.0' }
}
}
log = version\requireModules!
else
log = require 'a-mo.Log'
class DataHandler
@version: version
new: ( input, @scriptResX, @scriptResY ) =>
-- (length-22)/4
if input
unless @parseRawDataString input
@parseFile input
parseRawDataString: ( rawDataString ) =>
@tableize rawDataString
if next @rawData
unless @rawData[1]\match "Adobe After Effects 6.0 Keyframe Data"
return false
width = @rawData[3]\match "Source Width[\t ]+([0-9]+)"
height = @rawData[4]\match "Source Height[\t ]+([0-9]+)"
unless width and height
return false
@xPosScale = @scriptResX/tonumber width
@yPosScale = @scriptResY/tonumber height
parse @
if #@xPosition != @length or #@yPosition != @length or #@xScale != @length or #@yScale != @length or #@zRotation != @length or 0 == @length
return false
return true
parseFile: ( fileName ) =>
if file = io.open fileName, 'r'
return @parseRawDataString file\read '*a'
return false
tableize: ( rawDataString ) =>
@rawData = { }
rawDataString\gsub "([^\r\n]+)", ( line ) ->
table.insert @rawData, line
parse = =>
-- Initialize these here so they don't get appended if
-- parseRawDataString is called twice.
@xPosition = { }
@yPosition = { }
@xScale = { }
@yScale = @xScale
@zRotation = { }
length = 0
section = 0
for _index, line in ipairs @rawData
unless line\match("^[\t ]+")
if line == "Position" or line == "Scale" or line == "Rotation"
section += 1
else
line\gsub "^[\t ]+([%d%.%-]+)[\t ]+([%d%.%-e%+]+)(.*)", ( value1, value2, remainder ) ->
switch section
when 1
table.insert @xPosition, @xPosScale*tonumber value2
table.insert @yPosition, @yPosScale*tonumber remainder\match "^[\t ]+([%d%.%-e%+]+)"
length += 1
when 2
-- Sort of future proof against having different scale
-- values for different axes.
table.insert @xScale, tonumber value2
-- table.insert @yScale, tonumber value2
when 3
-- Sort of future proof having rotation around different
-- axes.
table.insert @zRotation, -tonumber value2
@length = length
-- Arguments: just your friendly neighborhood options table.
stripFields: ( options ) =>
defaults = { xPosition: @xStartPosition, yPosition: @yStartPosition, xScale: @xStartScale, zRotation: @zStartRotation }
for field, defaultValue in pairs defaults
unless options[field]
for index, value in ipairs @[field]
@[field][index] = defaultValue
checkLength: ( totalFrames ) =>
if totalFrames == @length
true
else
false
addReferenceFrame: ( frame ) =>
@startFrame = frame
@xStartPosition = @xPosition[frame]
@yStartPosition = @yPosition[frame]
@zStartRotation = @zRotation[frame]
@xStartScale = @xScale[frame]
@yStartScale = @yScale[frame]
calculateCurrentState: ( frame ) =>
@xCurrentPosition = @xPosition[frame]
@yCurrentPosition = @yPosition[frame]
@xRatio = @xScale[frame]/@xStartScale
@yRatio = @yScale[frame]/@yStartScale
@zRotationDiff = @zRotation[frame] - @zStartRotation
if haveDepCtrl
return version\register DataHandler
else
return DataHandler
| 29.055118 | 142 | 0.66206 |
4d9fd56ea05be3e5b7ff6c766e5a8d4138fd057f | 552 | colors = {
RESET: 0
BRIGHT: 1
DIM: 2
UNDERLINE: 4
BLINK: 5
REVERSE: 7
HIDDEN: 8
-- foreground
BLACK: 30
RED: 31
GREEN: 32
YELLOW: 33
BLUE: 34
MAGENTA: 35
CYAN: 36
WHITE: 37
-- background
BLACK_BG: 40
RED_BG: 41
GREEN_BG: 42
YELLOW_BG: 43
BLUE_BG: 44
MAGENTA_BG: 45
CYAN_BG: 46
WHITE_BG: 47
}
colorize = (color) ->
(str) ->
return str unless color
"\027[#{color}m#{str}\027[0m"
colors_mt = {
__index: (t, key, val) ->
colorize t[key\upper!]
}
setmetatable colors, colors_mt
colors
| 12.837209 | 33 | 0.605072 |
8d81176447d30ebb68984012409fbe0e3d6da32b | 42 | moon_src = ->
return true
{ :moon_src }
| 10.5 | 13 | 0.619048 |
36c47c736900627d68a89434db4ac37380e43ba5 | 4,885 | -- Copyright 2012-2015 Nils Nordman <nino at nordman.org>
-- License: MIT (see LICENSE.md)
state = bundle_load 'state'
import apply from state
import bindings, config from howl
with config
.define
name: 'vi_command_cursor_blink_interval'
description: 'The rate at which the cursor blinks while in command mode (ms, 0 disables)'
default: 0
type_of: 'number'
cursor_home = (editor) -> apply editor, (editor) -> editor.cursor\home!
forward_to_char = (event, source, translations, editor) ->
if event.character
apply editor, (editor) -> editor\forward_to_match event.character
else
return false
back_to_char = (event, source, translations, editor) ->
if event.character
apply editor, (editor) -> editor\backward_to_match event.character
else
return false
forward_till_char = (event, source, translations, editor) ->
if event.character
apply editor, (editor) ->
current_pos = editor.cursor.pos
editor\forward_to_match event.character
if current_pos != editor.cursor.pos
editor.cursor\left!
else
return false
back_till_char = (event, source, translations, editor) ->
if event.character
apply editor, (editor) ->
current_pos = editor.cursor.pos
editor\backward_to_match event.character
if current_pos != editor.cursor.pos
editor.cursor\right!
else
return false
end_of_word = (cursor) ->
with cursor
current_pos = .pos
\word_right_end!
\word_right_end! if .pos == current_pos + 1 and not .at_end_of_line
\left!
end_of_prev_word = (cursor) ->
with cursor
\word_left_end!
\left!
cursor_properties = {
style: 'block'
blink_interval: config.vi_command_cursor_blink_interval
}
map = {
__meta: {
:cursor_properties
}
editor: {
j: (editor) -> apply editor, (editor) -> editor.cursor\down!
k: (editor) -> apply editor, (editor) -> editor.cursor\up!
h: (editor) ->
if editor.cursor.at_start_of_line
state.reset!
else
apply editor, (editor) -> editor.cursor\left!
H: (editor) -> apply editor, (editor) ->
editor.cursor.line = editor.line_at_top
l: (editor) ->
if editor.cursor.at_end_of_line
state.reset!
else
apply editor, (editor) -> editor.cursor\right!
e: (editor) ->
if state.go
apply editor, (editor) -> end_of_prev_word editor.cursor
else
apply editor, (editor) -> end_of_word editor.cursor
w: (editor) -> apply editor, (editor, _state) ->
if _state.change or _state.yank then end_of_word editor.cursor
elseif _state.delete
for _ = 1,_state.count or 1 do editor.cursor\word_right!
editor.cursor\left!
true
else
editor.cursor\word_right!
b: (editor) -> apply editor, (editor) -> editor.cursor\word_left!
g: (editor) ->
if state.go
editor.cursor\start!
state.reset!
else
state.go = true
G: (editor) -> apply editor, (editor, _state) ->
if _state.count then editor.cursor.line = _state.count
else editor.cursor\eof!
L: (editor) -> apply editor, (editor) ->
editor.cursor.line = editor.line_at_bottom
f: (editor) -> bindings.capture forward_to_char
F: (editor) -> bindings.capture back_to_char
t: (editor) -> bindings.capture forward_till_char
T: (editor) -> bindings.capture back_till_char
'/': 'buffer-search-forward'
'?': 'buffer-search-backward'
n: 'buffer-repeat-search' -- repeat search in same direction
N: (editor) -> -- repeat search in opposite direction
searcher = editor.searcher
d = searcher.last_direction
searcher.last_direction = if d == 'forward' then 'backward' else 'forward'
searcher\repeat_last!
searcher.last_direction = d
M: (editor) -> apply editor, (editor) ->
editor.cursor.line = editor.line_at_center
'$': (editor) -> apply editor, (editor) ->
editor.cursor.column_index = math.max(1, #editor.current_line)
'^': (editor) -> apply editor, (editor) ->
editor.cursor\home_indent!
'{': (editor) -> apply editor, (editor) ->
editor.cursor\para_up!
'}': (editor) -> apply editor, (editor) ->
editor.cursor\para_down!
}
on_unhandled: (event, source, translations) ->
char = event.character
modifiers = event.control or event.alt
if char and not modifiers
if char\match '^%d$'
-- we need to special case '0' here as that's a valid command in its own
-- right, unless it's part of a numerical prefix
if char == '0' and not state.count then return cursor_home
else state.add_number tonumber char
elseif char\match '^%w$'
state.reset!
return -> true
}
config.watch 'vi_command_cursor_blink_interval', (_, value) ->
cursor_properties.blink_interval = value
return map
| 28.735294 | 93 | 0.652815 |
dc59563c94b1960623b0cca69ddd054be851ad52 | 5,084 | export script_name = "Make Image"
export script_description = "Converts images of various formats to pixels written in shape."
export script_author = "Zeref"
export script_version = "1.1.4"
-- LIB
zf = require "ZF.main"
interfacePixels = ->
items = {"All in one line", "On several lines - \"Rec\"", "Pixel by Pixel"}
{
{class: "label", label: "Output Type:", x: 0, y: 0}
{class: "dropdown", name: "otp", :items , x: 0, y: 1, value: items[2]}
}
interfacePotrace = ->
x, items = 0, {"right", "black", "white", "majority", "minority"}
{
{class: "label", label: "Turnpolicy:", :x, y: 0}
{class: "dropdown", name: "tpy", :items, :x, y: 1, value: "minority"}
{class: "label", label: "Corner threshold:", :x, y: 2}
{class: "intedit", name: "apm", :x, y: 3, min: 0, value: 1}
{class: "label", label: "Delete until:", :x, y: 4}
{class: "floatedit", name: "tdz", :x, y: 5, value: 2}
{class: "label", label: "Tolerance:", :x, y: 6}
{class: "floatedit", name: "opt", :x, y: 7, min: 0, value: 0.2}
{class: "checkbox", label: "Curve optimization?", name: "opc", :x, y: 8, value: true}
}
exts = "*.png;*.jpeg;*.jpe;*.jpg;*.jfif;*.jfi;*.bmp;*.dib;*.gif"
main = (macro) ->
(subs, selected) ->
filename = aegisub.dialog.open "Open Image File", "", "", "Image extents (#{exts})|#{exts};", false, true
unless filename
aegisub.cancel!
new_selection, i = {}, {0, 0, selected[#selected]}
button, elements = aegisub.dialog.display macro == "Pixels" and interfacePixels! or interfacePotrace!, {"Ok", "Cancel"}, close: "Cancel"
if button == "Ok"
img = zf.potrace filename
ext = img.extension
aegisub.progress.task "Processing #{ext\upper!}..."
-- copies the current line
line = zf.table(subs[i[3]])\copy!
dur = line.end_time - line.start_time
{:tpy, :tdz, :opc, :apm, :opt, :otp} = elements
-- start processing
aegisub.progress.task "Processing..."
if macro == "Pixels"
makePixels = (pixels, isGif) ->
for p, pixel in pairs pixels
break if aegisub.progress.is_cancelled!
aegisub.progress.set 100 * p / #pixels
line.text = pixel\gsub "}{", ""
if isGif
-- repositions the coordinates
line.text = line.text\gsub "\\pos%((%d+),(%d+)%)", (x, y) ->
{x: vx, y: vy} = img
px = tonumber(x) + vx
py = tonumber(y) + vy
return "\\pos(#{px},#{py})"
zf.util\insertLine line, subs, i[3] - 1, new_selection, i
typer = switch otp
when "All in one line" then "oneLine"
when "On several lines - \"Rec\"" then true
if ext != "gif"
makePixels img\raster typer
else
line.end_time = line.start_time + #img.infos.frames * zf.fbf\frameDur!
for s, e, d, j in zf.fbf(line)\iter!
break if aegisub.progress.is_cancelled!
line.start_time = s
line.end_time = e
makePixels img\raster(typer, j), true
else -- if potrace
makePotrace = (shp, isGif) ->
line.text = "{\\an7\\pos(0,0)\\bord0\\shad0\\fscx100\\fscy100\\fr0\\p1}#{shp}"
if isGif
-- repositions the coordinates
line.text = line.text\gsub "\\pos%((%d+),(%d+)%)", (x, y) ->
{x: vx, y: vy} = img
px = tonumber(x) + vx
py = tonumber(y) + vy
return "\\pos(#{px},#{py})"
zf.util\insertLine line, subs, i[3] - 1, new_selection, i
img\start nil, tpy, tdz, opc, apm, opt
if ext != "gif"
img\process!
makePotrace img\getShape!
else
line.end_time = line.start_time + #img.infos.frames * zf.fbf\frameDur!
for s, e, d, j in zf.fbf(line)\iter!
break if aegisub.progress.is_cancelled!
line.start_time = s
line.end_time = e
img\start j
if pcall -> img\process!
makePotrace img\getShape!, true
aegisub.set_undo_point macro
if #new_selection > 0
return new_selection, new_selection[1]
aegisub.register_macro "#{script_name} / Pixels", script_description, main "Pixels"
aegisub.register_macro "#{script_name} / Potrace", script_description, main "Potrace" | 47.074074 | 144 | 0.474626 |
8e6a8486c306fa7435c7a410a5830d79de3ee22b | 78 | import (
pricing "../schema.moon"
)
struct Order {
candle pricing.Candle
}
| 9.75 | 25 | 0.679487 |
2fb7072a1652616f44e78753e836dc1b12ffcf5a | 568 | --- Set of helper libraries for developing games with LÖVE.
-- @submodule hlp.asset
-- @submodule hlp.event
-- @module hlp
current = (...)
load = (path) ->
succ, loaded = pcall require, path
unless succ
LC_PATH = current .. '.' .. path
succ, loaded = pcall require, LC_PATH
unless succ
LC_PATH = current\gsub("%.[^%..]+$", "") .. '.' .. path
succ, loaded = pcall require, LC_PATH
unless succ
error loaded
return loaded
return {
asset: load 'asset'
locale: load 'locale'
ps: load 'ps'
csv: load 'csv'
Finder: load 'finder'
}
| 21.037037 | 59 | 0.617958 |
7216f4d40277a8a655b1c17f04cd2f92dd4c43fe | 772 | Dorothy!
GroupPanelView = require "View.Control.Edit.GroupPanel"
MessageBox = require "Control.Basic.MessageBox"
Class GroupPanelView,
__init: =>
sceneData = editor.sceneData
for i = 1,12
groupName = sceneData.groups[i]
with @["p#{i}"]
btnText = .placeHolder == groupName and "" or groupName
.text = btnText
\slot "Inputed",(newName)->
nameExist = false
for n = 0,15
if newName == sceneData.groups[n] and n ~= i
nameExist = true
break
if nameExist
.text = btnText
MessageBox text:"Group Name Exist!", okOnly:true
else
btnText = newName == .placeHolder and "" or newName
editor\updateGroupName i,newName
@scrollArea.viewSize = @menu\alignItemsVertically!
| 28.592593 | 60 | 0.634715 |
1c06054c5553f9bde80f7df565d37c82c4e4876d | 8,267 | import mode, config from howl
import File from howl.io
describe 'mode', ->
after_each ->
for name in *[name for name in *mode.names when name != 'default' ]
mode.unregister name
describe '.register(spec)', ->
it 'raises an error if any of the mandatory inputs are missing', ->
assert.raises 'name', -> mode.register {}
assert.raises 'create', -> mode.register name: 'foo'
describe '.by_name(name)', ->
it 'returns a mode instance for <name>, or nil if not existing', ->
assert.is_nil mode.by_name 'blargh'
mode.register name: 'shish', create: -> {}
assert.is_not_nil mode.by_name('shish')
it 'allows looking up modes by any aliases', ->
assert.is_nil mode.by_name 'my_mode'
mode.register name: 'shish', aliases: {'my_mode'}, create: -> {}
assert.is_not_nil mode.by_name('my_mode')
describe 'for_extension(extension)', ->
it 'returns a mode registered for <extension>, if any', ->
mode.register name: 'ext', extensions: 'foo', create: -> {}
assert.equal 'ext', mode.for_extension('foo').name
describe '.for_file(file)', ->
context 'when the file extension is registered with a mode', ->
it 'returns an instance of that mode', ->
mode.register name: 'ext', extensions: 'foo', create: -> {}
file = File 'test.foo'
assert.equal 'ext', mode.for_file(file).name
context 'when the file paths matches a mode pattern', ->
it 'returns an instance of that mode', ->
mode.register name: 'pattern', patterns: 'match%w+$', create: -> {}
file = File 'matchme'
assert.equal 'pattern', mode.for_file(file).name
context 'when the file header matches a mode shebang', ->
it 'returns an instance of that mode', ->
mode.register name: 'shebang', shebangs: 'lua$', create: -> {}
File.with_tmpfile (file) ->
file.contents = '#! /usr/bin/lua\nother line\nand other\n'
assert.equal 'shebang', mode.for_file(file).name
context 'when no matching mode can be found', ->
it 'returns an instance of the mode "default"', ->
file = File 'test.blargh'
assert.equal 'default', mode.for_file(file).name
context 'mode creation', ->
it 'modes are created by calling the modes create function, passing the name', ->
create = spy.new -> {}
mode.register name: 'callme', :create
mode.by_name('callme')
assert.spy(create).was_called_with 'callme'
it 'mode instances are memoized', ->
mode.register name: 'same', extensions: 'again', create: -> {}
assert.equal mode.by_name('same'), mode.for_file File 'once.again'
it 'mode instances automatically have their .name set', ->
mode.register name: 'named', extensions: 'again', create: -> {}
assert.equal mode.by_name('named').name, 'named'
describe 'mode configuration variables', ->
config.define name: 'mode_var', description: 'some var', default: 'def value'
it 'mode instances automatically have their .config set', ->
mode.register name: 'config', create: -> {}
mode_config = mode.by_name('config').config
assert.is_not_nil mode_config
assert.equal 'def value', mode_config.mode_var
mode_config.mode_var = 123
assert.equal 123, mode_config.mode_var
assert.equal 'def value', config.mode_var
it 'the .config is pre-seeded with variables from .default_config of the mode (if any)', ->
mode.register name: 'pre_config', create: -> default_config: { mode_var: 543 }
assert.equal 543, mode.by_name('pre_config').config.mode_var
describe 'configure(mode_name, variables)', ->
before_each ->
mode.register name: 'user_configured', create: -> {}
it 'allows setting mode specific variables automatically upon creation', ->
mode.configure 'user_configured', mode_var: 'from_user'
assert.equal 'from_user', mode.by_name('user_configured').config.mode_var
it 'automatically sets the config variables for any already instantiated mode', ->
mode_config = mode.by_name('user_configured').config
mode.configure 'user_configured', mode_var: 'after_the_fact'
assert.equal 'after_the_fact', mode_config.mode_var
it 'overrides any default mode configuration set', ->
mode.register name: 'mode_with_config', create: -> default_config: { mode_var: 'mode set' }
mode.configure 'mode_with_config', mode_var: 'user set'
assert.equal 'user set', mode.by_name('mode_with_config').config.mode_var
describe 'mode inheritance', ->
before_each ->
base = foo: 'foo'
mode.register name: 'base', create: -> base
mode.register name: 'sub', parent: 'base', create: -> {}
config.define name: 'delegated_mode_var', description: 'some var', default: 'def value'
it 'a mode extending another mode automatically delegates to that mode', ->
assert.equal 'foo', mode.by_name('sub').foo
mode.by_name('base').config.delegated_mode_var = 123
assert.equal 123, mode.by_name('sub').config.delegated_mode_var
it '.parent is set to the mode parent', ->
mode.register name: 'subsub', parent: 'sub', create: -> {}
sub_mode = mode.by_name('sub')
subsub_mode = mode.by_name('subsub')
assert.equal 'base', sub_mode.parent.name
assert.equal 'sub', subsub_mode.parent.name
it 'overridden functions and variables other then parent are respected', ->
mode.register name: 'first', create: -> {
mode_var1: 'first1'
mode_var2: 'first2'
one: => "#{@mode_var1} #{@two!}"
two: => @mode_var2
}
mode.register name: 'second', parent: 'first', create: -> {
mode_var1: 'second1'
two: => "#{@mode_var2}X"
}
second_mode = mode.by_name('second')
assert.equal "second1 first2X", second_mode\one!
describe 'super(...)', ->
it 'super methods can be invoked using `super`', ->
mode.register name: 'first', create: -> { foo: => "1" }
mode.register name: 'second', parent: 'first', create: -> {
foo: => super! .. '2'
}
mode.register name: 'third', parent: 'second', create: -> {
foo: => super! .. '3'
other: => 'other'
}
third_mode = mode.by_name('third')
assert.equal '123', third_mode\foo!
it 'raises an error if no parent has the specified method', ->
mode.register name: 'wrong', create: -> {
foo: => super!
}
assert.raises "No parent 'foo'", ->
mode.by_name('wrong')\foo!
it 'invokes the super method with the correct parameters', ->
local args
mode.register name: 'first', create: -> {
foo: (...) -> args = {...}
}
mode.register name: 'second', parent: 'first', create: -> {
foo: (...) => super ...
}
second = mode.by_name('second')
second\foo '1', 2
assert.same {second, '1', 2}, args
it 'an error is raised if the mode indicated by parent does not exist', ->
assert.has_error ->
mode.register name: 'wrong', parent: 'keyser_soze', create: -> {}
mode.by_name 'wrong'
it 'parent defaults to "default" unless given', ->
mode.register name: 'orphan', create: -> {}
assert.equal 'default', mode.by_name('orphan').parent.name
describe '.unregister(name)', ->
it 'removes the mode specified by <name>', ->
mode.register name: 'mode', aliases: 'foo', extensions: 'zen', create: -> {}
mode.unregister 'mode'
assert.is_nil mode.by_name 'mode'
assert.is_nil mode.by_name 'foo'
assert.equal mode.for_file(File('test.zen')), mode.by_name 'default'
it 'removes any memoized instance', ->
mode.register name: 'memo', extensions: 'memo', create: -> {}
mode.unregister 'memo'
live = mode.by_name 'memo'
mode.register name: 'memo', extensions: 'memo', create: -> {}
assert.is_not_equal live, mode.by_name('memo')
it '.names contains all registered mode names and their aliases', ->
mode.register name: 'needle', aliases: 'foo', create: -> {}
assert.includes mode.names, 'needle'
assert.includes mode.names, 'foo'
| 40.131068 | 99 | 0.624531 |
ac51be3caa64b39c28ec00fe07bc9ec4227d3875 | 10,853 | import underscore, escape_pattern, uniquify, singularize from require "lapis.util"
import insert, concat from table
import require, type, setmetatable, rawget, assert, pairs, unpack, error, next from _G
cjson = require "cjson"
import OffsetPaginator from require "lapis.db.pagination"
import add_relations, mark_loaded_relations from require "lapis.db.model.relations"
class Enum
debug = =>
"(contains: #{table.concat ["#{i}:#{v}" for i, v in ipairs @], ", "})"
-- convert string to number, or let number pass through
for_db: (key) =>
if type(key) == "string"
(assert @[key], "enum does not contain key #{key} #{debug @}")
elseif type(key) == "number"
assert @[key], "enum does not contain val #{key} #{debug @}"
key
else
error "don't know how to handle type #{type key} for enum"
-- convert number to string, or let string pass through
to_name: (val) =>
if type(val) == "string"
assert @[val], "enum does not contain key #{val} #{debug @}"
val
elseif type(val) == "number"
key = @[val]
(assert key, "enum does not contain val #{val} #{debug @}")
else
error "don't know how to handle type #{type val} for enum"
enum = (tbl) ->
keys = [k for k in pairs tbl]
for key in *keys
tbl[tbl[key]] = key
setmetatable tbl, Enum.__base
class BaseModel
@db: nil -- set in implementing class
@timestamp: false
@primary_key: "id"
@__inherited: (child) =>
if r = rawget child, "relations"
add_relations child, r, @db
@get_relation_model: (name) =>
require("models")[name]
@primary_keys: =>
if type(@primary_key) == "table"
unpack @primary_key
else
@primary_key
@encode_key: (...) =>
if type(@primary_key) == "table"
{ k, select i, ... for i, k in ipairs @primary_key }
else
{ [@primary_key]: ... }
@table_name: =>
unless rawget @, "__table_name"
@__table_name = underscore @__name
@__table_name
@scoped_model: (base_model, prefix, mod, external_models) ->
class extends base_model
@get_relation_model: if mod
(name) =>
if external_models and external_models[name]
base_model\get_relation_model name
else
require(mod)[name]
@table_name: =>
"#{prefix}#{base_model.table_name(@)}"
@singular_name: =>
singularize base_model.table_name @
-- used as the forign key name when preloading objects over a relation
-- user_posts -> user_post
@singular_name: =>
singularize @table_name!
@columns: =>
columns = @db.query [[
select column_name, data_type
from information_schema.columns
where table_name = ?]], @table_name!
@columns = -> columns
columns
@load: (tbl) =>
for k,v in pairs tbl
-- clear null values
if ngx and v == ngx.null or v == cjson.null
tbl[k] = nil
setmetatable tbl, @__base
@load_all: (tbls) =>
[@load t for t in *tbls]
-- @delete: (query, ...) =>
-- assert query, "tried to delete with no query"
-- @db.delete @table_name!, query, ...
@select: (query="", ...) =>
local opts
param_count = select "#", ...
if param_count > 0
last = select param_count, ...
if not @db.is_encodable last
opts = last
param_count -= 1
if type(query) == "table"
opts = query
query = ""
if param_count > 0
query = @db.interpolate_query query, ...
tbl_name = @db.escape_identifier @table_name!
load_as = opts and opts.load
fields = opts and opts.fields or "*"
if res = @db.select "#{fields} from #{tbl_name} #{query}"
return res if load_as == false
if load_as
load_as\load_all res
else
@load_all res
@count: (clause, ...) =>
tbl_name = @db.escape_identifier @table_name!
query = "COUNT(*) as c from #{tbl_name}"
if clause
query ..= " where " .. @db.interpolate_query clause, ...
unpack(@db.select query).c
-- include references to this model in a list of records based on a foreign
-- key
-- Examples:
--
-- -- Models
-- Users { id, name }
-- Games { id, user_id, title }
--
-- -- Have games, include users
-- games = Games\select!
-- Users\include_in games, "user_id"
--
-- -- Have users, get games (be careful of many to one, only one will be
-- -- assigned but all will be fetched)
-- users = Users\select!
-- Games\include_in users, "user_id", flip: true
--
-- specify as: "name" to set the key of the included objects in each item
-- from the source list
@include_in: (other_records, foreign_key, opts) =>
fields = opts and opts.fields or "*"
flip = opts and opts.flip
many = opts and opts.many
value_fn = opts and opts.value
if not flip and type(@primary_key) == "table"
error "#{@table_name!} must have singular primary key for include_in"
-- the column named to look up values in list of our records
src_key = if flip
-- we use id as a default since we don't have accurat primary key for
-- model of other_records (might be mixed)
opts.local_key or "id"
else
foreign_key
include_ids = for record in *other_records
with id = record[src_key]
continue unless id
if next include_ids
include_ids = uniquify include_ids
flat_ids = concat [@db.escape_literal id for id in *include_ids], ", "
find_by = if flip
foreign_key
else
@primary_key
tbl_name = @db.escape_identifier @table_name!
find_by_escaped = @db.escape_identifier find_by
query = "#{fields} from #{tbl_name} where #{find_by_escaped} in (#{flat_ids})"
if opts and opts.where and next opts.where
query ..= " and " .. @db.encode_clause opts.where
if order = many and opts.order
query ..= " order by #{order}"
if group = opts and opts.group
query ..= " group by #{group}"
if res = @db.select query
records = {}
if many
for t in *res
t_key = t[find_by]
if records[t_key] == nil
records[t_key] = {}
row = @load t
row = value_fn row if value_fn
insert records[t_key], row
else
for t in *res
row = @load t
row = value_fn row if value_fn
records[t[find_by]] = row
field_name = if opts and opts.as
opts.as
elseif flip
if many
@table_name!
else
@singular_name!
else
foreign_key\match "^(.*)_#{escape_pattern(@primary_key)}$"
assert field_name, "failed to infer field name, provide one with `as`"
for other in *other_records
other[field_name] = records[other[src_key]]
if many and not other[field_name]
other[field_name] = {}
if for_relation = opts and opts.for_relation
mark_loaded_relations other_records, for_relation
other_records
@find_all: (ids, by_key=@primary_key) =>
local extra_where, clause, fields
-- parse opts
if type(by_key) == "table"
fields = by_key.fields or fields
extra_where = by_key.where
clause = by_key.clause
by_key = by_key.key or @primary_key
if type(by_key) == "table" and by_key[1] != "raw"
error "#{@table_name!} find_all must have a singular key to search"
return {} if #ids == 0
@db.list ids
where = { [by_key]: @db.list ids }
if extra_where
for k,v in pairs extra_where
where[k] = v
query = "WHERE " .. @db.encode_clause where
if clause
if type(clause) == "table"
assert clause[1], "invalid clause"
clause = @db.interpolate_query unpack clause
query ..= " " .. clause
@select query, fields: fields
-- find by primary key, or by table of conds
@find: (...) =>
first = select 1, ...
error "#{@table_name!} trying to find with no conditions" if first == nil
cond = if "table" == type first
@db.encode_clause (...)
else
@db.encode_clause @encode_key(...)
table_name = @db.escape_identifier @table_name!
if result = unpack @db.select "* from #{table_name} where #{cond} limit 1"
@load result
else
nil
-- create from table of values, return loaded object
@create: (values, opts) =>
error "subclass responsibility"
-- returns true if something is using the cond
@check_unique_constraint: (name, value) =>
t = if type(name) == "table"
name
else
{ [name]: value }
error "missing constraint to check" unless next t
cond = @db.encode_clause t
table_name = @db.escape_identifier @table_name!
nil != unpack @db.select "1 from #{table_name} where #{cond} limit 1"
@_check_constraint: (key, value, obj) =>
return unless @constraints
if fn = @constraints[key]
fn @, value, key, obj
@paginated: (...) =>
OffsetPaginator @, ...
-- alternative to MoonScript inheritance
@extend: (table_name, tbl={}) =>
lua = require "lapis.lua"
class_fields = {
"primary_key", "timestamp", "constraints", "relations"
}
lua.class table_name, tbl, @, (cls) ->
cls.table_name = -> table_name
for f in *class_fields
cls[f] = tbl[f]
cls.__base[f] = nil
_primary_cond: =>
cond = {}
for key in *{@@primary_keys!}
val = @[key]
val = @@db.NULL if val == nil
cond[key] = val
cond
url_key: => concat [@[key] for key in *{@@primary_keys!}], "-"
delete: =>
res = @@db.delete @@table_name!, @_primary_cond!
res.affected_rows and res.affected_rows > 0, res
-- thing\update "col1", "col2", "col3"
-- thing\update {
-- "col1", "col2"
-- col3: "Hello"
-- }
update: (first, ...) =>
error "subclass responsibility"
-- reload fields on the instance
refresh: (fields="*", ...) =>
local field_names
if fields != "*"
field_names = {fields, ...}
fields = table.concat [@@db.escape_identifier f for f in *field_names], ", "
cond = @@db.encode_clause @_primary_cond!
tbl_name = @@db.escape_identifier @@table_name!
res = unpack @@db.select "#{fields} from #{tbl_name} where #{cond}"
unless res
error "#{@@table_name!} failed to find row to refresh from, did the primary key change?"
if field_names
for field in *field_names
@[field] = res[field]
else
relations = require "lapis.db.model.relations"
if loaded_relations = @[relations.LOADED_KEY]
for name in pairs loaded_relations
relations.clear_loaded_relation @, name
for k,v in pairs @
@[k] = nil
for k,v in pairs res
@[k] = v
@@load @
@
{ :BaseModel, :Enum, :enum }
| 26.342233 | 94 | 0.597899 |
ddc7ddf2ba902abf62cb66de78cfa02b02aed5d8 | 1,019 |
find_variables = (syntax, vars={}) ->
for node in *syntax
if type(node) == "table"
if node.variable
vars[node.variable] = "simple"
if node.tag
vars[node.tag] = "function"
find_variables node.contents, vars
vars
string_to_code = (key, text) ->
import parse_tags from require "helpers.compiler"
syntax = parse_tags\match text
variables = find_variables syntax
if next variables
has_function = false
has_numeric = false
code_chunks = for k,v in pairs variables
if v == "function"
has_function = true
val = v == "function" and "(...) ->" or "nil"
if k\match "^%d+$"
has_numeric = true
val
else
"#{k}: #{val}"
var_code = table.concat code_chunks, ", "
if has_numeric
var_code = "{ #{var_code} }"
if has_function
print "@tt \"#{key}\", #{var_code}"
else
print "@t(\"#{key}\", #{var_code})"
else
print "@t\"#{key}\""
{:string_to_code, :find_variables}
| 20.38 | 51 | 0.573111 |
bfe299d892158f6c02dd16bf60fa44a60cd0f9e4 | 278 | config = require "lapis.config"
config "development", ->
port 8080
cassandra ->
host "127.0.0.1"
keyspace "lapis-test"
config "production", ->
port 80
num_workers 4
code_cache "on"
cassandra ->
host "127.0.0.1"
keyspace "lapis-test"
| 17.375 | 32 | 0.600719 |
def0d334b1d18a2214900fd1c4240f3c46ac48ae | 4,898 | -- Copyright 2019 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:app, :config, :Project} = howl
{:icon} = howl.ui
{:File} = howl.io
append = table.insert
config.define
name: 'buffer_icons'
description: 'Whether buffer icons are displayed'
scope: 'global'
type_of: 'boolean'
default: true
icon.define_default 'buffer', 'font-awesome-square'
icon.define_default 'buffer-modified', 'font-awesome-pencil-square-o'
icon.define_default 'buffer-modified-on-disk', 'font-awesome-clone'
icon.define_default 'process-success', 'font-awesome-check-circle'
icon.define_default 'process-running', 'font-awesome-play-circle'
icon.define_default 'process-failure', 'font-awesome-exclamation-circle'
buffer_dir = (buffer) ->
if buffer.file
return buffer.file.parent.short_path
elseif buffer.directory
return buffer.directory.short_path
return '(none)'
buffer_status_text = (buffer) ->
stat = if buffer.modified then '*' else ''
stat ..= '[modified on disk]' if buffer.modified_on_disk
stat
buffer_status_icon = (buffer) ->
local name
if typeof(buffer) == 'ProcessBuffer'
if buffer.process.exited
name = buffer.process.successful and 'process-success' or 'process-failure'
else
name = 'process-running'
else
if buffer.modified_on_disk
name = 'buffer-modified-on-disk'
elseif buffer.modified
name = 'buffer-modified'
else
name = 'buffer'
return icon.get(name, 'operator')
make_title = (buffer, opts={}) ->
file = buffer.file
title = file.basename
if opts.parents
parent = file.parent
for _ = 1, opts.parents
if parent
title = "#{parent.basename}#{File.separator}#{title}"
parent = parent.parent
else
break
if opts.project
project = Project.for_file file
if project
title = "#{title} [#{project.root.basename}]"
return title
has_duplicates = (list) ->
set = {}
for item in *list
return true if set[item]
set[item] = true
return false
class BufferItem
new: (@buffer, @title) =>
display_row: =>
if config.buffer_icons
{buffer_status_icon(@buffer), @title, buffer_dir(@buffer)}
else
{@title, buffer_status_text(@buffer), buffer_dir(@buffer)}
preview: => buffer: @buffer
class BufferExplorer
new: (get_buffers, opts={}) =>
unless get_buffers
error 'BufferExplorer requires get_buffers function'
@get_buffers = get_buffers
@opts = moon.copy opts
@_refresh_buffers!
get_help: =>
help = howl.ui.HelpContext!
help\add_keys
['buffer-close']: "Close currently selected buffer"
help
actions: =>
close:
keystrokes: howl.bindings.keystrokes_for 'buffer-close', 'editor'
handler: (selected_item) =>
-- Close the selected buffer
-- We save the next or previous position in @jump_to_buffer which is
-- used to preserve the position of the selection in the list of buffers.
-- Otherwise a redraw would just select the first item.
for idx, buf in ipairs @buffers
if selected_item.buffer == buf
@jump_to_buffer = @buffers[idx + 1] or @buffers[idx]
break
app\close_buffer selected_item.buffer
@_refresh_buffers!
display_title: => @opts.title or 'Buffers list'
_refresh_buffers: =>
-- construct the buffers list and enhanced_titles
@buffers = self.get_buffers!
buffers = @buffers
basenames = {}
@enhanced_titles = {}
for buf in *buffers
continue unless buf.file and buf.file.basename == buf.title
basenames[buf.file.basename] or= {}
append basenames[buf.file.basename], buf
for _, buffer_group in pairs(basenames)
continue if #buffer_group == 1
options_list = {
{ project: true }
{ project: false, parents: 1 }
{ project: true, parents: 1 }
{ project: false, parents: 2 }
{ project: true, parents: 2 }
}
titles = nil
for options in *options_list
titles = [make_title buffer, options for buffer in *buffer_group]
break if not has_duplicates titles
for i=1,#buffer_group
@enhanced_titles[buffer_group[i]] = titles[i]
display_items: =>
items = [BufferItem(buffer, @title_for(buffer)) for buffer in *@buffers]
jump_to_item = [item for item in *items when item.buffer == @jump_to_buffer]
@jump_to_buffer = nil
return items, selected_item: jump_to_item[1]
display_columns: =>
name_width = math.min 100, math.max(table.unpack [@title_for(buffer).ulen for buffer in *@buffers])
if config.buffer_icons
{{}, {style: 'string', min_width: name_width}, {style: 'comment'}}
else
{{style: 'string', min_width: name_width}, {style: 'operator'}, {style: 'comment'}}
title_for: (buffer) => @enhanced_titles[buffer] or buffer.title
| 29.865854 | 103 | 0.665782 |
eba1f7b397d38e7dd208df66afe97cbc76d4eff7 | 401 | {
order: 'cifmspv',
kinds: {
c: { group: 'neotags_ClassTag' },
i: { group: 'neotags_ImportTag' },
f: { group: 'neotags_FunctionTag' },
m: { group: 'neotags_FunctionTag' },
v: {
group: 'neotags_VariableTag',
allow_keyword: false,
}
s: { group: 'neotags_EnumTag' },
p: { group: 'neotags_TypeTag' },
}
}
| 25.0625 | 44 | 0.491272 |
98813337066a89d5dd85a8e7cb68696b0c5d89e2 | 150 | export modinfo = {
type: "function"
id: "Output3"
func: (message, color, recipient, stick) ->
TabletMerge message, color, recipient, stick, 3
}
| 18.75 | 49 | 0.68 |
c4cbfd28b34b148d10522728cf2343fd020fe05d | 11,103 | -- Copyright 2016 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:activities, :app, :bindings, :command, :config, :inspection, :interact, :log, :signal, :timer} = howl
{:ActionBuffer, :BufferPopup, :highlight} = howl.ui
{:Process, :process_output} = howl.io
{:pcall} = _G
{:sort} = table
append = table.insert
local popup, last_display_position
unavailable_warnings = {}
update_inspections_display = (editor) ->
text = ''
count = #editor.buffer.markers\find(name: 'inspection')
if count > 0
keys = bindings.keystrokes_for 'cursor-goto-inspection', 'editor'
access = #keys > 0 and keys[1] or 'cursor-goto-inspection'
text = "(#{count} inspection#{count > 1 and 's' or ''} - #{access} to view)"
editor.indicator.inspections.text = text
resolve_inspector = (name, inspector, buffer) ->
if inspector.is_available
available, msg = inspector.is_available(buffer)
unless available
unless unavailable_warnings[name]
log.warning "Inspector '#{name}' unavailable: #{msg}"
unavailable_warnings[name] = true
return nil
return inspector unless inspector.cmd\find '<file>', 1, true
return nil if not buffer.file or buffer.modified
copy = {k,v for k, v in pairs inspector}
copy.cmd = copy.cmd\gsub '<file>', buffer.file.path
copy.write_stdin = false
copy
load_inspectors = (buffer, scope = 'idle') ->
to_load = if scope == 'all'
{'inspectors_on_idle', 'inspectors_on_save'}
else
{"inspectors_on_#{scope}"}
inspectors = {}
for variable in *to_load
for inspector in *buffer.config[variable]
conf = inspection[inspector]
if conf
instance = conf.factory buffer
unless callable(instance)
if type(instance) == 'string'
instance = resolve_inspector inspector, {cmd: instance}, buffer
elseif type(instance) == 'table'
unless instance.cmd
error "Missing cmd key for inspector returned for '#{inspector}'"
instance = resolve_inspector inspector, instance, buffer
if instance
append inspectors, instance
else
log.warn "Invalid inspector '#{inspector}' specified for '#{buffer.title}'"
inspectors
merge = (found, criticisms) ->
for c in *found
l_nr = c.line
criticisms[l_nr] or= {}
append criticisms[l_nr], {
message: c.message,
type: c.type,
search: c.search,
start_col: c.start_col,
end_col: c.end_col,
byte_start_col: c.byte_start_col,
byte_end_col: c.byte_end_col,
}
get_line_segment = (line, criticism) ->
start_col = criticism.start_col
end_col = criticism.end_col
line_text = nil
if not start_col and criticism.byte_start_col
line_text or= line.text
start_col = line_text\char_offset criticism.byte_start_col
if not end_col and criticism.byte_end_col
line_text or= line.text
end_col = line_text\char_offset criticism.byte_end_col
if not (start_col and end_col) and criticism.search
p = r"\\b#{r.escape(criticism.search)}\\b"
line_text or= line.text
s, e = line_text\ufind p, start_col or 1
if s
unless line\ufind p, s + 1
start_col = s
end_col = e + 1
if not start_col and not line.is_empty
start_col = 1 + line.indentation
-- check spec coverage end_pos
start_pos = start_col and line.start_pos + start_col - 1 or line.start_pos
end_pos = end_col and line.start_pos + end_col - 1 or line.end_pos
start_pos, end_pos
mark_criticisms = (buffer, criticisms) ->
{:lines, :markers} = buffer
ms = {}
line_nrs = [nr for nr in pairs criticisms]
sort line_nrs
for nr in *line_nrs
line = lines[nr]
list = criticisms[nr]
continue unless line and #list > 0
for c in *list
start_pos, end_pos = get_line_segment line, c
ms[#ms + 1] = {
name: 'inspection',
flair: c.type or 'error',
start_offset: start_pos,
end_offset: end_pos
message: c.message
}
if #ms > 0
markers\add ms
return #ms
parse_errors = (out, inspector) ->
if inspector.parse
return inspector.parse out
inspections = {}
for loc in *process_output.parse(out)
complaint = {
line: loc.line_nr,
message: loc.message,
}
if loc.tokens
complaint.search = loc.tokens[1]
complaint.type = inspector.type or loc.message\umatch(r'^(warning|error)')
append inspections, complaint
if inspector.post_parse
inspector.post_parse inspections
inspections
launch_inspector_process = (opts, buffer) ->
write_stdin = true unless opts.write_stdin == false
p = Process {
cmd: opts.cmd,
read_stdout: true,
read_stderr: true,
write_stdin: write_stdin
env: opts.env,
shell: opts.shell,
working_directory: opts.working_directory
}
if write_stdin
p.stdin\write buffer.text
p.stdin\close!
p
inspect = (buffer, opts = {}) ->
criticisms = {}
processes = {}
inspector_scope = opts.scope or 'all'
for inspector in *load_inspectors(buffer, inspector_scope)
if callable(inspector)
status, ret = pcall inspector, buffer
if status
merge(ret or {}, criticisms)
else
log.error "inspector '#{inspector}' failed: #{ret}"
else
p = launch_inspector_process inspector, buffer
processes[#processes + 1] = { process: p, :inspector }
-- finish off processes
for p in *processes
out, err = activities.run_process {title: 'Reading inspection results'}, p.process
buf = out
buf ..= "\n#{err}" unless err.is_blank
inspections = parse_errors buf, p.inspector
merge(inspections, criticisms)
criticisms
criticize = (buffer, criticisms, opts = {}) ->
criticisms or= inspect buffer
if opts.clear
buffer.markers\remove name: 'inspection'
mark_criticisms buffer, criticisms
update_buffer = (buffer, editor, scope) ->
return if buffer.read_only
return if buffer.data.is_preview
data = buffer.data
if data.last_inspect
li = data.last_inspect
if scope == 'idle' and li.ts >= buffer.last_changed
return
-- we mark this automatic inspection run with a serial
update_serial = (data.inspections_update or 0) + 1
data.inspections_update = update_serial
criticisms = inspect buffer, :scope
-- check serial to avoid applying out-of-date criticisms
unless data.inspections_update == update_serial
log.warn "Ignoring stale inspection update - slow inspection processes?"
return
criticize buffer, criticisms
buffer.data.last_inspect = ts: buffer.last_changed, :scope
editor or= app\editor_for_buffer buffer
if editor
update_inspections_display editor
popup_text = (inspections) ->
items = {}
prefix = #inspections > 1 and '- ' or ''
for i = 1, #inspections
append items, "#{prefix}<#{inspections[i].type}>#{inspections[i].message}</>"
return howl.ui.markup.howl table.concat items, '\n'
show_popup = (editor, inspections, pos) ->
popup or= BufferPopup ActionBuffer!
buf = popup.buffer
buf\as_one_undo ->
buf.text = ''
buf\append popup_text inspections
with popup.view
.cursor.line = 1
.base_x = 0
editor\show_popup popup, {
position: pos,
keep_alive: true,
}
display_inspections = ->
timer.on_idle (config.display_inspections_delay / 1000), display_inspections
editor = app.editor
return unless editor.has_focus
pos = editor.view.cursor.pos
-- if we've already displayed the message at this position, punt
return if pos == last_display_position
a_markers = editor.buffer.markers.markers
markers = a_markers\at pos
if #markers == 0 and pos > 1
markers = a_markers\at pos - 1
markers = [{message: m.message, type: m.flair} for m in *markers when m.message]
if #markers > 0
last_display_position = pos
show_popup editor, markers, editor.cursor.pos
on_idle = ->
timer.on_idle 0.5, on_idle
editor = app.editor
-- if there's a popup open already of any sorts, don't interfere
return if editor.popup
b = editor.buffer
if b.config.auto_inspect == 'on'
if b.size < 1024 * 1024 * 5 -- 5 MB
update_buffer b, editor, 'idle'
signal.connect 'buffer-modified', (args) ->
with args.buffer
.markers\remove name: 'inspection'
editor = app\editor_for_buffer args.buffer
if editor
editor.indicator.inspections.text = ''
signal.connect 'buffer-saved', (args) ->
b = args.buffer
return unless b.size < 1024 * 1024 * 5 -- 5 MB
return if b.config.auto_inspect == 'off'
-- what to load? if config says 'save', all, otherwise save inspectors
-- but if the idle hasn't had a chance to run we also run all
scope = if b.config.auto_inspect == 'save_only'
'all'
elseif b.data.last_inspect and b.data.last_inspect.ts < b.last_changed
'all'
else
'save'
update_buffer b, nil, scope
signal.connect 'after-buffer-switch', (args) ->
update_inspections_display args.editor
signal.connect 'preview-opened', (args) ->
args.editor.indicator.inspections.text = ''
signal.connect 'preview-closed', (args) ->
update_inspections_display args.editor
signal.connect 'cursor-changed', (args) ->
last_display_position = nil
signal.connect 'editor-defocused', (args) ->
last_display_position = nil
signal.connect 'app-ready', (args) ->
timer.on_idle 0.5, on_idle
timer.on_idle (config.display_inspections_delay / 1000), display_inspections
highlight.define_default 'error',
type: highlight.WAVY_UNDERLINE
foreground: 'red'
line_width: 1
line_type: 'solid'
highlight.define_default 'warning',
type: highlight.WAVY_UNDERLINE
foreground: 'orange'
line_width: 1
line_type: 'solid'
command.register
name: 'buffer-inspect'
description: 'Inspects the current buffer for abberations'
handler: ->
buffer = app.editor.buffer
criticize buffer
editor or= app\editor_for_buffer buffer
if editor
update_inspections_display editor
command.register
name: 'cursor-goto-inspection'
description: 'Goes to a specific inspection in the current buffer'
input: (opts) ->
editor = app.editor
buffer = editor.buffer
inspections = buffer.markers\find(name: 'inspection')
unless #inspections > 0
log.info "No inspections for the current buffer"
return nil
items = {}
last_lnr = 0
for i in *inspections
chunk = buffer\chunk i.start_offset, i.end_offset
l = buffer.lines\at_pos i.start_offset
append items, {
if l.nr == last_lnr then '·' else tostring(l.nr),
l.chunk,
:chunk,
popup: popup_text {{message: i.message, type: i.flair}}
}
last_lnr = l.nr
return interact.select_location
prompt: opts.prompt
title: "Inspections in #{buffer.title}"
editor: editor
items: items
selection: items[1]
columns: {{style: 'comment'}, {}}
handler: (res) ->
if res
chunk = res.chunk
app.editor.cursor.pos = chunk.start_pos
app.editor\highlight start_pos: chunk.start_pos, end_pos: chunk.end_pos
:inspect, :criticize
| 27.347291 | 103 | 0.678735 |
1d30341de8566459345fcccf2ff67a46a6334045 | 293 | GST = require "gst"
player=GST!
player\play "file:///home/kyra/Music/skype_bell.wav"
player\addCB (message)=>
if message.type.STATE_CHANGED
print "state: %s"\format @current_state
elseif message.type.EOS
print "EOS"
print "restarting..."
@stop!
@play!
player\mainLoop!
| 22.538462 | 52 | 0.686007 |
248469471384ba7f4366f0000f3093418a4dc03f | 2,104 | -- Copyright 2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:config, :timer, :sys} = howl
ffi = require 'ffi'
config.define
name: 'cleanup_min_buffers_open'
description: 'The minimum number of buffers to leave when auto-closing buffers'
default: 40
type_of: 'number'
scope: 'global'
config.define
name: 'cleanup_close_buffers_after'
description: 'The number of hours since a buffer was last shown before it can be closed'
default: 24
type_of: 'number'
scope: 'global'
if sys.info.os == 'linux'
ffi.cdef 'int malloc_trim(size_t pad);'
local timer_handle
log_closed = (closed) ->
msg = "Closed buffers: '#{closed[1].title}'"
for i = 2, #closed
t = closed[i].title
if #t + #msg > 72
msg ..= " (+#{#closed - i + 1} more)"
break
msg ..= ", '#{t}'"
log.info msg
clean_up_buffers = ->
app = howl.app
bufs = app.buffers
to_remove = #bufs - config.cleanup_min_buffers_open
return if to_remove <= 0
now = sys.time!
closeable = {}
for b in *bufs
continue if b.modified or not b.last_shown
unseen_for = os.difftime(now, b.last_shown) / 60 / 60 -- hours
if unseen_for > config.cleanup_close_buffers_after
closeable[#closeable + 1] = b
to_remove = math.min(to_remove, #closeable)
if to_remove > 0
closed = {}
table.sort closeable, (a, b) -> a.last_shown < b.last_shown
for i = 1, to_remove
buf = closeable[i]
app\close_buffer buf
closed[#closed + 1] = buf
log_closed closed
release_memory = ->
collectgarbage!
collectgarbage!
if sys.info.os == 'linux'
ffi.C.malloc_trim(1024 * 128)
run = ->
if timer_handle
timer_handle = timer.on_idle 30, run
window = howl.app.window
if window and not window.command_panel.is_active
clean_up_buffers!
howl.app\save_session!
release_memory!
start = ->
return if timer_handle
timer_handle = timer.on_idle 30, run
stop = ->
return unless timer_handle
timer.cancel timer_handle
timer_handle = nil
{
:clean_up_buffers
:start
:stop
:run
}
| 21.690722 | 90 | 0.668726 |
662d3266143402cf0bb023b5ce38a747ca064393 | 1,417 | lapis = require "lapis"
db = require "lapis.db"
import Model from require "lapis.db.model"
import config from require "lapis.config"
import insert from table
import sort from table
import random from math
class Fortune extends Model
class World extends Model
lapis.serve class Benchmark extends lapis.Application
"/": =>
json: {message: "Hello, World!"}
"/db": =>
num_queries = tonumber(@params.queries) or 1
worlds = {}
for i = 1, num_queries
insert worlds, World\find random(1, 10000)
json: worlds
"/fortunes": =>
@fortunes = Fortune\select ""
insert @fortunes, {id:0, message:"Additional fortune added at request time."}
sort @fortunes, (a, b) -> a.message < b.message
@title = "Fortunes"
@html ->
element "table", ->
tr ->
th ->
text "id"
th ->
text "message"
for fortune in *@fortunes
tr ->
td ->
text fortune.id
td ->
text fortune.message
"/update": =>
num_queries = tonumber(@params.queries) or 1
worlds = {}
for i = 1, num_queries
wid = random(1, 10000)
world = World\find wid
world.randomnumber = random(1, 10000)
world\update "randomnumber"
insert worlds, world
json: worlds
"/plaintext": =>
content_type:"text/plain", layout: false, "Hello, World!"
| 24.431034 | 81 | 0.585039 |
46af904e5a815952b78bcb413d28f8acfbe9bffa | 21,903 |
import Postgres from require "pgmoon"
unpack = table.unpack or unpack
HOST = "127.0.0.1"
PORT = "9999"
USER = "postgres"
DB = "pgmoon_test"
psql = ->
os.execute "psql -h '#{HOST}' -p '#{PORT}' -U '#{USER}'"
describe "pgmoon with server", ->
setup ->
os.execute "spec/postgres.sh start"
teardown ->
os.execute "spec/postgres.sh stop"
for socket_type in *{"luasocket", "cqueues"}
describe "socket(#{socket_type})", ->
local pg
setup ->
assert 0 == os.execute "dropdb -h '#{HOST}' -p '#{PORT}' --if-exists -U '#{USER}' '#{DB}'"
assert 0 == os.execute "createdb -h '#{HOST}' -p '#{PORT}' -U '#{USER}' '#{DB}'"
pg = Postgres {
database: DB
user: USER
host: HOST
port: PORT
:socket_type
}
assert pg\connect!
teardown ->
pg\disconnect!
it "creates and drop table", ->
res = assert pg\query [[
create table hello_world (
id serial not null,
name text,
count integer not null default 0,
primary key (id)
)
]]
assert.same true, res
res = assert pg\query [[
drop table hello_world
]]
assert.same true, res
it "settimeout()", ->
timeout_pg = Postgres {
host: "10.0.0.1"
:socket_type
}
timeout_pg\settimeout 1000
ok, err = timeout_pg\connect!
assert.is_nil ok
errors = {
"timeout": true
"Connection timed out": true
}
assert.true errors[err]
it "tries to connect with SSL", ->
-- we expect a server with ssl = off
ssl_pg = Postgres {
database: DB
user: USER
host: HOST
port: PORT
ssl: true
:socket_type
}
finally ->
ssl_pg\disconnect!
assert ssl_pg\connect!
it "requires SSL", ->
ssl_pg = Postgres {
database: DB
user: USER
host: HOST
port: PORT
ssl: true
ssl_required: true
:socket_type
}
status, err = ssl_pg\connect!
assert.falsy status
assert.same [[the server does not support SSL connections]], err
describe "with table", ->
before_each ->
assert pg\query [[
create table hello_world (
id serial not null,
name text,
count integer not null default 0,
flag boolean default TRUE,
primary key (id)
)
]]
after_each ->
assert pg\query [[
drop table hello_world
]]
it "inserts a row", ->
res = assert pg\query [[
insert into "hello_world" ("name", "count") values ('hi', 100)
]]
assert.same { affected_rows: 1 }, res
it "inserts a row with return value", ->
res = assert pg\query [[
insert into "hello_world" ("name", "count") values ('hi', 100) returning "id"
]]
assert.same {
affected_rows: 1
{ id: 1 }
}, res
it "selects from empty table", ->
res = assert pg\query [[select * from hello_world limit 2]]
assert.same {}, res
it "selects count as a number", ->
res = assert pg\query [[select count(*) from hello_world]]
assert.same {
{ count: 0 }
}, res
it "deletes nothing", ->
res = assert pg\query [[delete from hello_world]]
assert.same { affected_rows: 0 }, res
it "update no rows", ->
res = assert pg\query [[update "hello_world" SET "name" = 'blahblah']]
assert.same { affected_rows: 0 }, res
describe "with rows", ->
before_each ->
for i=1,10
assert pg\query [[
insert into "hello_world" ("name", "count")
values (']] .. "thing_#{i}" .. [[', ]] .. i .. [[)
]]
it "select some rows", ->
res = assert pg\query [[ select * from hello_world ]]
assert.same "table", type(res)
assert.same 10, #res
it "update rows", ->
res = assert pg\query [[
update "hello_world" SET "name" = 'blahblah'
]]
assert.same { affected_rows: 10 }, res
assert.same "blahblah",
unpack((pg\query "select name from hello_world limit 1")).name
it "delete a row", ->
res = assert pg\query [[
delete from "hello_world" where id = 1
]]
assert.same { affected_rows: 1 }, res
assert.same nil,
unpack((pg\query "select * from hello_world where id = 1")) or nil
it "truncate table", ->
res = assert pg\query "truncate hello_world"
assert.same true, res
it "make many select queries", ->
for i=1,20
assert pg\query [[update "hello_world" SET "name" = 'blahblah' where id = ]] .. i
assert pg\query [[ select * from hello_world ]]
-- single call, multiple queries
describe "multi-queries #multi", ->
it "gets two results", ->
res, num_queries = assert pg\query [[
select id, flag from hello_world order by id asc limit 2;
select id, flag from hello_world order by id asc limit 2 offset 2;
]]
assert.same 2, num_queries
assert.same {
{
{ id: 1, flag: true }
{ id: 2, flag: true }
}
{
{ id: 3, flag: true }
{ id: 4, flag: true }
}
}, res
it "gets three results", ->
res, num_queries = assert pg\query [[
select id, flag from hello_world order by id asc limit 2;
select id, flag from hello_world order by id asc limit 2 offset 2;
select id, flag from hello_world order by id asc limit 2 offset 4;
]]
assert.same 3, num_queries
assert.same {
{
{ id: 1, flag: true }
{ id: 2, flag: true }
}
{
{ id: 3, flag: true }
{ id: 4, flag: true }
}
{
{ id: 5, flag: true }
{ id: 6, flag: true }
}
}, res
it "does multiple updates", ->
res, num_queries = assert pg\query [[
update hello_world set flag = false where id = 3;
update hello_world set flag = true;
]]
assert.same 2, num_queries
assert.same {
{ affected_rows: 1 }
{ affected_rows: 10 }
}, res
it "does mix update and select", ->
res, num_queries = assert pg\query [[
update hello_world set flag = false where id = 3;
select id, flag from hello_world where id = 3
]]
assert.same 2, num_queries
assert.same {
{ affected_rows: 1 }
{
{ id: 3, flag: false }
}
}, res
it "returns partial result on error", ->
res, err, partial, num_queries = pg\query [[
select id, flag from hello_world order by id asc limit 1;
select id, flag from jello_world limit 1;
]]
assert.same {
err: [[ERROR: relation "jello_world" does not exist (112)]]
num_queries: 1
partial: {
{ id: 1, flag: true }
}
}, { :res, :err, :partial, :num_queries }
it "deserializes types correctly", ->
assert pg\query [[
create table types_test (
id serial not null,
name text default 'hello',
subname varchar default 'world',
count integer default 100,
flag boolean default false,
count2 double precision default 1.2,
bytes bytea default E'\\x68656c6c6f5c20776f726c6427',
config json default '{"hello": "world", "arr": [1,2,3], "nested": {"foo": "bar"}}',
bconfig jsonb default '{"hello": "world", "arr": [1,2,3], "nested": {"foo": "bar"}}',
uuids uuid[] default ARRAY['00000000-0000-0000-0000-000000000000']::uuid[],
primary key (id)
)
]]
assert pg\query [[
insert into types_test (name) values ('hello')
]]
res = assert pg\query [[
select * from types_test order by id asc limit 1
]]
assert.same {
{
id: 1
name: "hello"
subname: "world"
count: 100
flag: false
count2: 1.2
bytes: 'hello\\ world\''
config: { hello: "world", arr: {1,2,3}, nested: {foo: "bar"} }
bconfig: { hello: "world", arr: {1,2,3}, nested: {foo: "bar"} }
uuids: {'00000000-0000-0000-0000-000000000000'}
}
}, res
assert pg\query [[
drop table types_test
]]
it "deserializes row types correctly #ddd", ->
pg\query "select 1"
pg\query "select row(1, 'hello', 5.999)"
pg\query "select (1, 'hello', 5.999)"
describe "custom deserializer", ->
it "deserializes big integer to string", ->
assert pg\query [[
create table bigint_test (
id serial not null,
largenum bigint default 9223372036854775807,
primary key (id)
)
]]
assert pg\query [[
insert into bigint_test (largenum) values (default)
]]
pg\set_type_oid 20, "bignumber"
pg.type_deserializers.bignumber = (val) => val
row = unpack pg\query "select * from bigint_test"
assert.same {
id: 1
largenum: "9223372036854775807"
}, row
describe "hstore", ->
import encode_hstore, decode_hstore from require "pgmoon.hstore"
describe "encoding", ->
it "encodes hstore type", ->
t = { foo: "bar" }
enc = encode_hstore t
assert.same [['"foo"=>"bar"']], enc
it "encodes multiple pairs", ->
t = { foo: "bar", abc: "123" }
enc = encode_hstore t
results = {'\'"foo"=>"bar", "abc"=>"123"\'', '\'"abc"=>"123", "foo"=>"bar"\''}
assert(enc == results[1] or enc == results[2])
it "escapes", ->
t = { foo: "bar's" }
enc = encode_hstore t
assert.same [['"foo"=>"bar''s"']], enc
describe "decoding", ->
it "decodes hstore into a table", ->
s = '"foo"=>"bar"'
dec = decode_hstore s
assert.same {foo: 'bar'}, dec
it "decodes hstore with multiple parts", ->
s = '"foo"=>"bar", "1-a"=>"anything at all"'
assert.same {
foo: "bar"
"1-a": "anything at all"
}, decode_hstore s
it "decodes hstore with embedded quote", ->
assert.same {
hello: 'wo"rld'
}, decode_hstore [["hello"=>"wo\"rld"]]
describe "serializing", ->
before_each ->
assert pg\query [[
CREATE EXTENSION hstore;
create table hstore_test (
id serial primary key,
h hstore
)
]]
pg\setup_hstore!
after_each ->
assert pg\query [[
DROP TABLE hstore_test;
DROP EXTENSION hstore;
]]
it "serializes correctly", ->
assert pg\query "INSERT INTO hstore_test (h) VALUES (#{encode_hstore {foo: 'bar'}});"
res = assert pg\query "SELECT * FROM hstore_test;"
assert.same {foo: 'bar'}, res[1].h
it "serializes NULL as string", ->
assert pg\query "INSERT INTO hstore_test (h) VALUES (#{encode_hstore {foo: 'NULL'}});"
res = assert pg\query "SELECT * FROM hstore_test;"
assert.same 'NULL', res[1].h.foo
it "serializes multiple pairs", ->
assert pg\query "INSERT INTO hstore_test (h) VALUES (#{encode_hstore {abc: '123', foo: 'bar'}});"
res = assert pg\query "SELECT * FROM hstore_test;"
assert.same {abc: '123', foo: 'bar'}, res[1].h
describe "json", ->
import encode_json, decode_json from require "pgmoon.json"
it "encodes json type", ->
t = { hello: "world" }
enc = encode_json t
assert.same [['{"hello":"world"}']], enc
t = { foo: "some 'string'" }
enc = encode_json t
assert.same [['{"foo":"some ''string''"}']], enc
it "encodes json type with custom escaping", ->
escape = (v) ->
"`#{v}`"
t = { hello: "world" }
enc = encode_json t, escape
assert.same [[`{"hello":"world"}`]], enc
it "serialize correctly", ->
assert pg\query [[
create table json_test (
id serial not null,
config json,
primary key (id)
)
]]
assert pg\query "insert into json_test (config) values (#{encode_json {foo: "some 'string'"}})"
res = assert pg\query [[select * from json_test where id = 1]]
assert.same { foo: "some 'string'" }, res[1].config
assert pg\query "insert into json_test (config) values (#{encode_json {foo: "some \"string\""}})"
res = assert pg\query [[select * from json_test where id = 2]]
assert.same { foo: "some \"string\"" }, res[1].config
assert pg\query [[
drop table json_test
]]
describe "arrays", ->
import decode_array, encode_array from require "pgmoon.arrays"
it "converts table to array", ->
import PostgresArray from require "pgmoon.arrays"
array = PostgresArray {1,2,3}
assert.same {1,2,3}, array
assert PostgresArray.__base == getmetatable array
it "encodes array value", ->
assert.same "ARRAY[1,2,3]", encode_array {1,2,3}
assert.same "ARRAY['hello','world']", encode_array {"hello", "world"}
assert.same "ARRAY[[4,5],[6,7]]", encode_array {{4,5}, {6,7}}
it "decodes empty array value", ->
assert.same {}, decode_array "{}"
import PostgresArray from require "pgmoon.arrays"
assert PostgresArray.__base == getmetatable decode_array "{}"
it "decodes numeric array", ->
assert.same {1}, decode_array "{1}", tonumber
assert.same {1, 3}, decode_array "{1,3}", tonumber
assert.same {5.3}, decode_array "{5.3}", tonumber
assert.same {1.2, 1.4}, decode_array "{1.2,1.4}", tonumber
it "decodes multi-dimensional numeric array", ->
assert.same {{1}}, decode_array "{{1}}", tonumber
assert.same {{1,2,3},{4,5,6}}, decode_array "{{1,2,3},{4,5,6}}", tonumber
it "decodes literal array", ->
assert.same {"hello"}, decode_array "{hello}"
assert.same {"hello", "world"}, decode_array "{hello,world}"
it "decodes multi-dimensional literal array", ->
assert.same {{"hello"}}, decode_array "{{hello}}"
assert.same {{"hello", "world"}, {"foo", "bar"}},
decode_array "{{hello,world},{foo,bar}}"
it "decodes string array", ->
assert.same {"hello world"}, decode_array [[{"hello world"}]]
it "decodes multi-dimensional string array", ->
assert.same {{"hello world"}, {"yes"}},
decode_array [[{{"hello world"},{"yes"}}]]
it "decodes string escape sequences", ->
assert.same {[[hello \ " yeah]]}, decode_array [[{"hello \\ \" yeah"}]]
it "fails to decode invalid array syntax", ->
assert.has_error ->
decode_array [[{1, 2, 3}]]
it "decodes literal starting with numbers array", ->
assert.same {"1one"}, decode_array "{1one}"
assert.same {"1one", "2two"}, decode_array "{1one,2two}"
it "decodes json array result", ->
res = pg\query "select array(select row_to_json(t) from (values (1,'hello'), (2, 'world')) as t(id, name)) as items"
assert.same {
{
items: {
{ id: 1, name: "hello" }
{ id: 2, name: "world" }
}
}
}, res
it "decodes jsonb array result", ->
assert.same {
{
items: {
{ id: 442, name: "itch" }
{ id: 99, name: "zone" }
}
}
}, pg\query "select array(select row_to_json(t)::jsonb from (values (442,'itch'), (99, 'zone')) as t(id, name)) as items"
describe "with table", ->
before_each ->
pg\query "drop table if exists arrays_test"
it "loads integer arrays from table", ->
assert pg\query "create table arrays_test (
a integer[],
b int2[],
c int8[],
d numeric[],
e float4[],
f float8[]
)"
num_cols = 6
assert pg\query "insert into arrays_test
values (#{"'{1,2,3}',"\rep(num_cols)\sub 1, -2})"
assert pg\query "insert into arrays_test
values (#{"'{9,5,1}',"\rep(num_cols)\sub 1, -2})"
assert.same {
{
a: {1,2,3}
b: {1,2,3}
c: {1,2,3}
d: {1,2,3}
e: {1,2,3}
f: {1,2,3}
}
{
a: {9,5,1}
b: {9,5,1}
c: {9,5,1}
d: {9,5,1}
e: {9,5,1}
f: {9,5,1}
}
}, (pg\query "select * from arrays_test")
it "loads string arrays from table", ->
assert pg\query "create table arrays_test (
a text[],
b varchar[],
c char(3)[]
)"
num_cols = 3
assert pg\query "insert into arrays_test
values (#{"'{one,two}',"\rep(num_cols)\sub 1, -2})"
assert pg\query "insert into arrays_test
values (#{"'{1,2,3}',"\rep(num_cols)\sub 1, -2})"
assert.same {
{
a: {"one", "two"}
b: {"one", "two"}
c: {"one", "two"}
}
{
a: {"1", "2", "3"}
b: {"1", "2", "3"}
c: {"1 ", "2 ", "3 "}
}
}, (pg\query "select * from arrays_test")
it "loads string arrays from table", ->
assert pg\query "create table arrays_test (ids boolean[])"
assert pg\query "insert into arrays_test (ids) values ('{t,f}')"
assert pg\query "insert into arrays_test (ids) values ('{{t,t},{t,f},{f,f}}')"
assert.same {
{ ids: {true, false} }
{ ids: {
{true, true}
{true, false}
{false, false}
} }
}, (pg\query "select * from arrays_test")
it "converts null", ->
pg.convert_null = true
res = assert pg\query "select null the_null"
assert pg.NULL == res[1].the_null
it "converts to custom null", ->
pg.convert_null = true
n = {"hello"}
pg.NULL = n
res = assert pg\query "select null the_null"
assert n == res[1].the_null
it "encodes bytea type", ->
n = { { bytea: "encoded' string\\" } }
enc = pg\encode_bytea n[1].bytea
res = assert pg\query "select #{enc}::bytea"
assert.same n, res
it "returns error message", ->
status, err = pg\query "select * from blahlbhabhabh"
assert.falsy status
assert.same [[ERROR: relation "blahlbhabhabh" does not exist (15)]], err
it "allows a query after getting an error", ->
status, err = pg\query "select * from blahlbhabhabh"
assert.falsy status
res = pg\query "select 1"
assert.truthy res
it "errors when connecting with invalid server", ->
pg2 = Postgres {
database: "doesnotexist"
user: USER
host: HOST
port: PORT
:socket_type
}
status, err = pg2\connect!
assert.falsy status
assert.same [[FATAL: database "doesnotexist" does not exist]], err
describe "pgmoon without server", ->
escape_ident = {
{ "dad", '"dad"' }
{ "select", '"select"' }
{ 'love"fish', '"love""fish"' }
}
escape_literal = {
{ 3434, "3434" }
{ 34.342, "34.342" }
{ "cat's soft fur", "'cat''s soft fur'" }
{ true, "TRUE" }
}
local pg
before_each ->
pg = Postgres!
for {ident, expected} in *escape_ident
it "escapes identifier '#{ident}'", ->
assert.same expected, pg\escape_identifier ident
for {lit, expected} in *escape_literal
it "escapes literal '#{lit}'", ->
assert.same expected, pg\escape_literal lit
| 30.980198 | 131 | 0.477058 |
d5749bc483ea765b754f6e06d82121352626f41f | 831 | import join from require "path"
import Schema from "novacbn/gmodproj/api/Schema"
import PROJECT_PATH from "novacbn/gmodproj/lib/constants"
-- ResolverOptions::ResolverOptions()
-- Represents the LIVR schema for validating 'Resolver' section in 'manifest.gmodproj'
-- export
export ResolverOptions = Schema\extend {
-- ResolverOptions::namespace -> string
-- Represents the nested namespace of the schema
--
namespace: "Resolver"
-- ResolverOptions::schema -> table
-- Represents the LIVR validation schema
--
schema: {
searchPaths: {list_of: {is: "string"}}
}
-- ResolverOptions::default -> table
-- Represents the default values that are merged before validation
--
default: {
searchPaths: {
join(PROJECT_PATH.home, "packages")
}
}
} | 26.806452 | 86 | 0.670277 |
1e10420189af06af094ed612e7e6e61feae52695 | 7,224 | import
getmetatable, ipairs, pairs, setfenv,
setmetatable, tostring
from _G
import gsub, match, rep from string
import concat, insert from table
import loadstring from require "moonscript/base"
import isNumericTable, isSequentialTable from "novacbn/novautils/table"
import deprecate from "novacbn/gmodproj/lib/utilities/deprecate"
import makeStringEscape from "novacbn/gmodproj/lib/utilities/string"
-- ::escapeString(string unescapedString) -> string
-- Escapes a string to be Lua-safe
escapeString = makeStringEscape {
{"\\", "\\\\"},
{"'", "\\'"},
{"\t", "\\t"},
{"\n", "\\n"},
{"\r", "\\r"}
}
-- ::encodeKeyString(string stringKey) -> string, boolean
-- Encodes a string-key for DataFile serialization
encodeKeyString = (stringKey) ->
-- Escape the string before encoding
stringKey = escapeString(stringKey)
-- If the key starts with a letter, encode as a function call, otherwise encode as a table key
if match(stringKey, "^%a") then return stringKey, false
return "'#{stringKey}'", true
-- ::encodeValueString(string stringValue) -> string
-- Encodes a string-value for DataFile serialization
encodeValueString = (stringValue) ->
-- Escape the string before encoding, then encode as Lua string
stringValue = escapeString(stringValue)
return "'#{stringValue}'"
-- ::encodeValueTable(table tableValue, number stackLevel?) -> string
-- Encodes a table-value for DataFile serialization
local encodeKey, encodeValue
encodeValueTable = (tableValue, stackLevel=0) ->
-- Make the new string stack and calculate the tabs per member
stringStack = {}
stackTabs = rep("\t", stackLevel)
-- If this is a nested table, add a opening bracket
insert(stringStack, "{") if stackLevel > 0
-- Check if the table is a sequential numeric table or a map
if isNumericTable(tableValue) and isSequentialTable(tableValue)
-- Loop through the sequential table and serialize each value, ignoring the indexes
local encodedValue
tableLength = #tableValue
for index, value in ipairs(tableValue)
-- Encode the value before adding to the stack
encodedValue = encodeValue(value, stackLevel + 1)
-- If this isn't the last table value, append a comma seperator to the value
if index < tableLength then insert(stringStack, stackTabs..encodedValue..",")
else insert(stringStack, stackTabs..encodedValue)
else
local keyType, encodedKey, keyEncapsulate, valueType, encodedValue
for key, value in pairs(tableValue)
-- Encode the keys and values before adding to the stack
encodedKey, keyEncapsulate = encodeKey(key)
encodedValue = encodeValue(value, stackLevel + 1)
-- If it is an encapsulated key, add boundry brackets to the key
if keyEncapsulate then insert(stringStack, stackTabs.."[#{encodedKey}]: #{encodedValue}")
else insert(stringStack, stackTabs.."#{encodedKey} #{encodedValue}")
-- If this is a nested table, add a closing bracket, then return the serialized table
insert(stringStack, rep("\t", stackLevel - 1).."}") if stackLevel > 0
return concat(stringStack, "\n")
-- ::typeEncodeMap -> table
-- Represents a map of key and value type encoders
typeEncodeMap = {
key: {
boolean: => @, true,
number: => @, true,
string: encodeKeyString
},
value: {
boolean: tostring
number: => @
string: encodeValueString,
table: encodeValueTable
}
}
-- ::encodeKey(any key, any ...) -> string
-- Encodes a key to the DataFile format
encodeKey = (key, ...) ->
-- Validate that the key can be encoded, then encode it
keyEncoder = typeEncodeMap.key[type(key)]
error("cannot encode key '#{key}', unsupported type") unless keyEncoder
return keyEncoder(key, ...)
-- ::encodeValue(any value, any ...) -> string
-- Encodes a value to the DataFile format
encodeValue = (value, ...) ->
-- Validate the the value can be encoded, then encode it
valueEncoder = typeEncodeMap.value[type(value)]
error("cannot encode value '#{value}', unsupported type") unless valueEncoder
return valueEncoder(value, ...)
-- ::KeyPair(string name, function levelToggle) -> KeyPair
-- A primitive type representing a DataFile key value
KeyPair = (name, levelToggle) -> setmetatable({:name}, {
__call: (value) =>
if type(value) == "table"
removedKeys = {}
for key, subValue in pairs(value)
if type(subValue) == "table" and getmetatable(subValue)
value[subValue.name] = subValue.value if subValue.value ~= nil
insert(removedKeys, key)
value[key] = nil for key in *removedKeys
@value = value
levelToggle(name, value) if levelToggle
return self
})
-- ::ChunkEnvironment(table dataExports) -> ChunkEnvironment, table
-- A primitive type representing a DataFile Lua environment
ChunkEnvironment = (dataExports={}) ->
-- Create a flag for if the next member if top-level
topLevel = true
levelToggle = (key, value) ->
-- Assign the data export and reset the flag
dataExports[key] = value
topLevel = true
return setmetatable({}, {
__index: (key) =>
-- Make a new KeyPair with the levelToggle if it's a top-level member
keyPair = KeyPair(key, topLevel and levelToggle)
topLevel = false
return keyPair
}), dataExports
-- ::loadChunk(function sourceChunk) -> table
-- Parses a function chunk as a DataFile
-- export
export loadChunk = (sourceChunk) ->
deprecate("novacbn/gmodproj/lib/datafile::loadChunk", "novacbn/gmodproj/lib/datafile::loadChunk is deprecated, see 0.4.0 changelog")
-- Make the new environment for the chunk then run and return exports
chunkEnvironment, dataExports = ChunkEnvironment()
setfenv(sourceChunk, chunkEnvironment)()
return dataExports
-- ::readString(string sourceString, string chunkName?) -> table
-- Deserializes a table in the DataFile format
-- TODO:
-- add flag to perform lexical parsing instead of loading code for safer deserialization
-- export
export fromString = (sourceString, chunkName="DataFile Chunk") ->
deprecate("novacbn/gmodproj/lib/datafile::fromString", "novacbn/gmodproj/lib/datafile::fromString is deprecated, see 0.4.0 changelog")
-- Parse the string with MoonScript then load it as a function chunk
sourceChunk = loadstring(sourceString, chunkName)
return loadChunk(sourceChunk)
-- ::toString(table sourceTable) -> string
-- Serializes a table into the DataFile format
-- TODO:
-- support alphabetic and values before tables sortings
-- export
export toString = (sourceTable) ->
deprecate("novacbn/gmodproj/lib/datafile::toString", "novacbn/gmodproj/lib/datafile::toString is deprecated, see 0.4.0 changelog")
-- Validate the table then serialize it
error("only table values can be serialized") unless type(sourceTable) == "table"
return typeEncodeMap.value.table(sourceTable, 0)
| 39.048649 | 138 | 0.673173 |
f64a6310bbf3e3eba718ce0e926ec0521dd32b46 | 5,269 | local *
gamestate = assert require "hump.gamestate"
signals = assert require "hump.signal"
timer = assert require "hump.timer"
sounds = assert require "sounds"
Billiard = assert require "billiard"
import abs, floor, rad from math
cue =
dist: 0
dir: 6
shotcount = 0
app = nil
board = nil
splash = nil
font = nil
pointer = nil
gameoverfont = nil
--------------------------------------------------------------------------------
love.load = ->
love.mouse.setVisible false
with love.graphics
splash = .newImage "images/splash.jpg"
board = .newImage "images/board.jpg"
cue.img = .newImage "images/cue.png"
pointer = .newImage "images/pointer.png"
font = .newFont "resources/PlantagenetCherokee.ttf", 24
gameoverfont = .newFont "resources/brasil-new.ttf", 64
signals.register "shoot", -> shotcount += 1
signals.register "game-over", -> gamestate.switch gameoverstate
sounds.load!
gamestate.registerEvents!
gamestate.switch menustate
--------------------------------------------------------------------------------
mainstate =
enter: =>
app = Billiard!
shotcount = 0
update: (dt) =>
app\update dt
with love.keyboard
if .isDown"up" or .isDown"right"
signals.emit "increase-force", dt
elseif .isDown"down" or .isDown"left"
signals.emit "decrease-force", dt
cue.dist += cue.dir * dt
if cue.dist > 16
cue.dist = 16
cue.dir = -abs cue.dir
elseif cue.dist < 0
cue.dist = 0
cue.dir = abs cue.dir
keypressed: (key, isrepeat) =>
signals.emit "shoot" if key == " " and not app.rolling
keyreleased: (key) =>
switch key
when "p"
gamestate.push pausestate
when "escape"
gamestate.switch menustate
mousepressed: (x, y, button) =>
if button == 1
signals.emit "shoot" unless app.rolling
wheelmoved: (x, y) =>
if y < 0
signals.emit "increase-force", -.1 * y
elseif y > 0
signals.emit "decrease-force", .1 * y
draw: =>
with love.graphics
-- Draw board
.draw board, 0, 0
-- Draw balls
app\draw!
-- Draw cue
unless app.rolling
.setColor 0xff, 0xff, 0xff
x, y = app.balls.white.body\getPosition!
.draw cue.img, x, y, rad app.rotation,
1, 1, cue.dist, cue.img\getHeight! / 2
--Draw force bar
.setColor 0xff, 0xff, 0xff
.rectangle "line", 10, 432, 204, 100
app\scaleforce (x, r, g, b) ->
.setColor r, g, b
.rectangle "fill", x * 2 + 11, 433, 2, 98
-- Draw score
.setColor 0xff, 0xff, 0xff
.setFont font
.print "Score: #{app.score}", 300, 432
.print "Shots: #{shotcount}", 300, 464
-- Draw pointer
unless app.rolling
x, y = love.mouse.getPosition!
.draw pointer, x - 13, y - 13
--------------------------------------------------------------------------------
menustate =
enter: =>
app\disconnecthandlers! if app
keyreleased: (key) =>
switch key
when "return"
gamestate.switch mainstate
when "escape"
love.event.quit!
draw: =>
love.graphics.setColor 0xff, 0xff, 0xff
love.graphics.draw splash, 0, 0
--------------------------------------------------------------------------------
pausestate =
enter: (previous) =>
@timer = timer.new!
@alpha = 0
@previous = previous
@timer\tween .5, @, {alpha: 1}, "linear"
leave: =>
@previous = nil
@timer\clear!
keyreleased: (key) =>
gamestate.pop! if key == "p" or key == "escape"
update: (dt) =>
@timer\update dt
draw: =>
@previous\draw! if @previous
with love.graphics
.setColor 0x00, 0x00, 0x60, floor 0xa0 * @alpha
width, height = .getDimensions!
.rectangle "fill", 0, 0, width, height
.setColor 0xff, 0xff, 0xff, floor 0xa0 * @alpha
.setFont gameoverfont
.print "Paused", 312, 166
--------------------------------------------------------------------------------
gameoverstate =
enter: (previous) =>
@previous = previous
@timer = timer.new!
@tx_game_x = -100
@tx_over_x = love.window.getWidth!
@timer\tween 2, @, {tx_game_x: 272, tx_over_x: 416}, "out-expo"
leave: =>
@previous = nil
@timer\clear!
keyreleased: (key) =>
gamestate.switch menustate if key == "escape"
update: (dt) =>
@timer\update dt
draw: =>
@previous\draw! if @previous
with love.graphics
.setColor 0xff, 0x00, 0x00
.setFont gameoverfont
.print "Game", @tx_game_x, 166
.print "Over", @tx_over_x, 166
.setColor 0xff, 0xff, 0xff
.draw cur.img, 390, 432
| 27.300518 | 80 | 0.485481 |
a014ffcf202d4515984d30dd8acc372c9270c7bd | 634 | ffi = require 'ffi'
GLib = require 'ljglibs.glib'
Bytes = GLib.Bytes
describe 'Bytes', ->
describe 'creation', ->
it 'can be created from a string', ->
bytes = Bytes 'hello'
assert.not_nil bytes
assert.equals 5, bytes.size
assert.equals 'hello', bytes.data
it 'can be created from cdata if size is provided', ->
s = 'world'
cdata_s = ffi.cast 'const char *', s
bytes = Bytes cdata_s, #s
assert.not_nil bytes
assert.equals 5, bytes.size
assert.equals 'world', bytes.data
describe '#bytes returns the size of the data', ->
assert.equals 4, #Bytes('w00t')
| 25.36 | 58 | 0.623028 |
dd2cc0c9aaf150a93190cfbd6bc0f065d116f111 | 1,258 | export width, height, id, i, world, beginContact, endContact, exit, enter, gamestate
game = require 'game'
gamestate = "MainMenu"
--width, height = love.window.getWidth!, love.window.getHeight!
width, height = 400, 600
love.load = ->
love.window.setTitle("Embrace Your Bugs 2.0")
game.load!
love.update = (dt)->
switch gamestate
when "Game"
game.update(dt)
love.keypressed = (key)->
switch gamestate
when "Game"
game.keypressed(key)
when "MainMenu"
switch key
when "s" --Start the game
gamestate = "Game"
game.isRunning = true
when "r"
game.reset!
when "escape" --Close the window
love.event.quit!
love.draw = ->
switch gamestate
when "Game"
game.draw!
when "MainMenu"
-- print "MainMenu"
love.graphics.setColor( 255, 255, 255)
msg = ""
if game.isRunning == true
msg = "Press 'S' resume the game. \nPress 'escape' to close the window. \nPress 'R' to reset the game"
else
msg = "Press 'S' to start a new game. \nPress 'escape' to close the window."
love.graphics.print(msg, width/2, height/2)
when "Player1"
print "Player 1 won"
when "Player2"
print "Player 2 won"
| 26.208333 | 110 | 0.606518 |
214fcdefe6d337a0142daee05f362218ec5cb4ae | 1,949 | {
editor: {
tab: 'editor-smart-tab'
ctrl_tab: 'editor-smart-back-tab'
ctrl_a: 'editor-delete-back'
alt_a: 'editor-delete-word-back'
alt_d: 'editor-delete-word-front'
ctrl_d: 'editor-delete-forward'
ctrl_m: 'editor-newline'
ctrl_e: 'editor-delete-line'
ctrl_o: 'editor-insert-line'
ctrl_p: 'editor-insert-line-before'
ctrl_b: 'switch-buffer'
ctrl_s: 'editor-goto-line'
ctrl_c: 'editor-copy'
ctrl_f: 'buffer-search-forward'
alt_f: 'buffer-search-backward'
ctrl_r: 'buffer-search-line'
alt_r: 'buffer-replace'
ctrl_u: 'save'
ctrl_v: 'editor-paste'
ctrl_x: 'editor-cut'
ctrl_w: 'editor-undo'
ctrl_z: 'editor-redo'
ctrl_space: 'editor-toggle-selection'
alt_s: 'buffer-structure'
alt_q: 'editor-reflow-paragraph'
ctrl_j: 'cursor-left'
ctrl_l: 'cursor-right'
ctrl_i: 'cursor-up'
ctrl_k: 'cursor-down'
alt_j: 'cursor-word-left'
alt_l: 'cursor-word-right'
alt_i: 'cursor-line-end'
alt_k: 'cursor-home'
}
ctrl_q: {
q: 'quit'
j: 'view-left-or-create'
l: 'view-right-or-create'
i: 'view-up-or-create'
k: 'view-down-or-create'
c: 'view-close'
e: 'exec'
u: 'editor-uncomment'
t: 'editor-toggle-comment'
y: 'editor-comment'
ctrl_p: 'project-open'
ctrl_e: 'project-exec'
ctrl_b: 'project-build'
}
ctrl_t: 'open'
ctrl_y: 'buffer-close'
'ctrl_-': 'zoom-out'
'ctrl_+': 'zoom-in'
ctrl_f11: 'window-toggle-fullscreen'
alt_x: 'run'
}
| 26.337838 | 49 | 0.487943 |
9568070bc8e97f025942870156eb8bb4747370b1 | 1,303 | require "date"
release = (t) ->
title = "version "..t.version
desc = if t.changes
leading = t.changes\match"^(%s*)" or ""
simple_date = t.date\fmt "%B %d %Y"
table.concat {
leading .. "## ".. title .. " - " .. simple_date
"\n\n"
t.changes
}
else
""
{
title: title
link: "http://leafo.net/aroma/#v" .. t.version
date: t.date
description: desc
_release: t
}
return {
format: "markdown"
title: "Aroma Changelog"
link: "http://leafo.net/aroma/"
description: "Aroma is a game engine for Native Client"
release {
version: "0.0.3"
date: date 2012, 9, 3, 13, 06
changes: [[
* updated to Pepper 21
* throw error when module can't be found
* `module` and `package.seeall` work within the async scope instead of the global one
* added `aroma.graphics.setLineWidth`, `Quad:flip`, `aroma.graphics.newImageFont`
* `aroma.graphics.print` can now take a transformation
]]
}
release {
version: "0.0.2"
date: date 2012, 5, 14, 11, 23
changes: [[
* fixed broken default loader
* unload all modules that have been required on `execute`
]]
}
release {
version: "0.0.1"
date: date 2012, 5, 13, 18, 53
changes: [[
Initial Release
]]
}
}
| 22.465517 | 91 | 0.578665 |
f3a687df2cb839d579c31a9784e87b20cc325817 | 1,130 | transfer_money = (giver, reciever, ammount) ->
giver -= ammount
reciever += ammount
users = {
isu: {
name: "Isu"
rank: "Rookie"
balance: 1000
wins: 3
losses: 2
inv: {
"Isu's ID Card"
"bow"
"chain helmet"
}
}
yelimsxela: {
name: "yelimsxela"
rank: "Rookie"
balance: 1500
wins: 4
losses: 3
inv: {
"yelimsxela's ID Card"
"iron sword"
"leather armor"
"tnt"
}
}
}
contraband = {
"iron sword"
"tnt"
"monster spawner"
}
users.isu.balance += 2000
print users.isu.balance
print users.yelimsxela.balance
transfer_money users.yelimsxela.balance, users.isu.balance, 500
print users.isu.balance
print users.yelimsxela.balance
--table.insert users.yelimsxela.inv, "potion"
--print ""
--for i1=1,#users.yelimsxela.inv
-- for i2=1,#contraband
-- if users.yelimsxela.inv[i1] == contraband[i2]
-- print "Removed "..users.yelimsxela.inv[i1]
-- table.remove users.yelimsxela.inv, i1
--
--
--
--print ""
--for i,_ in pairs users
-- if tostring(i) == "yelimsxela"
-- print (i.."'s inventory:")
-- print ""
-- for i,v in pairs users[i].inv
-- print i,v
--
--print ""--
| 14.675325 | 63 | 0.631858 |
f2084d2aff0651bb695a768c5e79e6d7884297a3 | 1,001 |
local encode_base64, decode_base64, hmac_sha1
config = require"lapis.config".get!
if ngx
{:encode_base64, :decode_base64, :hmac_sha1} = ngx
else
mime = require "mime"
{ :b64, :unb64 } = mime
encode_base64 = (...) -> (b64 ...)
decode_base64 = (...) -> (unb64 ...)
crypto = require "crypto"
hmac_sha1 = (secret, str) ->
crypto.hmac.digest "sha1", str, secret, true
encode_with_secret = (object, secret=config.secret, sep=".") ->
json = require "cjson"
msg = encode_base64 json.encode object
signature = encode_base64 hmac_sha1 secret, msg
msg .. sep .. signature
decode_with_secret = (msg_and_sig, secret=config.secret) ->
json = require "cjson"
msg, sig = msg_and_sig\match "^(.*)%.(.*)$"
return nil, "invalid message" unless msg
sig = decode_base64 sig
unless sig == hmac_sha1(secret, msg)
return nil, "invalid message secret"
json.decode decode_base64 msg
{ :encode_base64, :decode_base64, :hmac_sha1, :encode_with_secret, :decode_with_secret }
| 25.025 | 88 | 0.681319 |
7e63edbd91c07697d0136b29c27937356e17e1ae | 11,128 | Enumerable = require 'src.LunaQuery'
isSame = (require 'test.util').deepcompare
--Sample Data
---------------
lemonade = Enumerable\fromList({'get', 'your', 'ice', 'cold', 'lemonade', 'here'})
numbers = Enumerable\fromList({1,2,3,10,10,10,100,200,300})
mixed = Enumerable\fromList({1,2,3,'apple', 'fig', 'kiwi'})
--aggregate
assert numbers\aggregate(((a,b) -> a + b), 0) == 636
assert lemonade\aggregate(((a,b) -> a..b), '') == 'getyouricecoldlemonadehere'
--all
assert numbers\all((a) -> type(a) == 'string') == false
assert numbers\all((a) -> type(a) == 'number') == true
assert lemonade\all((a) -> type(a) == 'string') == true
assert lemonade\all((a) -> type(a) == 'number') == false
assert mixed\all((a) -> type(a) == 'string') == false
assert mixed\all((a) -> type(a) == 'number') == false
--any
assert Enumerable\fromList({})\any! == false
assert Enumerable\fromList({5, 'cups', 'tea'})\any! == true
assert numbers\any((a) -> type(a) == 'string') == false
assert numbers\any((a) -> type(a) == 'number') == true
assert lemonade\any((a) -> type(a) == 'string') == true
assert lemonade\any((a) -> type(a) == 'number') == false
assert mixed\any((a) -> type(a) == 'string') == true
assert mixed\any((a) -> type(a) == 'number') == true
--append
assert isSame(lemonade\append('extra')\toList!,
{'get', 'your', 'ice', 'cold', 'lemonade', 'here', 'extra'})
assert isSame(numbers\append(17)\toList!,
{1,2,3,10,10,10,100,200,300,17})
--average
assert numbers\average! == 636 / 9
assert numbers\average((a) -> a - 1) == (636 - 9) / 9
--concat
assert isSame(numbers\concat(mixed)\toList!,
{1,2,3,10,10,10,100,200,300,1,2,3,'apple','fig','kiwi'})
--contains
assert numbers\contains(22) == false
assert numbers\contains(2) == true
assert mixed\contains('fish') == false
assert mixed\contains('fig') == true
assert lemonade\contains('aaaaa', (a,b) -> #a == #b) == false
assert lemonade\contains('aaaa', (a,b) -> #a == #b) == true
--count
assert numbers\count! == 9
assert numbers\count((a) -> a > 5) == 6
--defaultIfEmpty
tmp = {5, 'cups', 'tea'}
assert isSame(Enumerable\fromList(tmp)\defaultIfEmpty('teacup')\toList!, tmp)
assert isSame(Enumerable\fromList({})\defaultIfEmpty('teacup')\toList!, {'teacup'})
--distinct
assert isSame(Enumerable\fromList({'hello', 'world', 'world'})\distinct!\toList!,
{'hello', 'world'})
assert isSame(numbers\distinct!\toList!,
{1,2,3,10,100,200,300})
assert isSame(numbers\distinct((a,b) -> (a - b) * (a - b) < 25)\toList!,
{1,10,100,200,300})
--elementAt
assert mixed\elementAt(5) == 'fig'
assert numbers\elementAt(9) == 300
--elementAtOrDefault
assert mixed\elementAtOrDefault(5, 'tea') == 'fig'
assert mixed\elementAtOrDefault(100, 'tea') == 'tea'
--empty
assert isSame(Enumerable\empty!\toList!, {})
--except
--TODO: test with custom equalsComparer
assert isSame(numbers\except(mixed)\toList!, {10,100,200,300})
--first
assert lemonade\first! == 'get'
assert lemonade\first((a) -> #a > 4) == 'lemonade'
--firstOrDefault
assert lemonade\firstOrDefault('tea') == 'get'
assert lemonade\firstOrDefault('tea', (a) -> #a > 4) == 'lemonade'
assert lemonade\firstOrDefault('tea', (a) -> #a > 10) == 'tea'
--forEach
tmp = {}
lemonade\forEach((a) -> tmp[#tmp + 1] = #a)
assert isSame(tmp, {3,4,3,4,8,4})
--fromDictionary
assert Enumerable\fromDictionary({key1: 25, key2: 'potato'})\count! == 2
--fromHashSet
tmp = Enumerable\fromHashSet({peach:true, banana:true, [15]: true})
assert tmp\count! == 3
assert tmp\contains('banana')
--fromList
assert isSame(Enumerable\fromList({5, 'cups', 'tea'})\toList!, {5, 'cups', 'tea'})
--groupBy
assert isSame(lemonade\groupBy((a) -> #a)\toList!,
{
{3, {'get','ice'}}
{4, {'your','cold','here'}}
{8, {'lemonade'}}
})
--groupJoin
tmp = Enumerable\fromList(
{
{name:'seal', likes:'ice', hates:'lemonade'},
{name:'toad', likes:'sand', hates:'lemonade'},
{name:'fox', likes:'lemonade', hates:'ice'}
})
assert isSame(lemonade\groupJoin(tmp, ((a) -> a), ((a) -> a.hates), (a,b) -> a..' haters: '..#b)\toList!,
{
'get haters: 0',
'your haters: 0',
'ice haters: 1',
'cold haters: 0',
'lemonade haters: 2',
'here haters: 0'
})
--intersect
--TODO: test with custom equalsComparer
assert isSame(numbers\intersect(mixed)\toList!, {1,2,3})
--join
tmp = Enumerable\fromList(
{
{name:'seal', likes:'ice', hates:'lemonade'},
{name:'toad', likes:'sand', hates:'lemonade'},
{name:'fox', likes:'lemonade', hates:'ice'}
})
assert isSame(tmp\join(lemonade, ((a) -> a.likes), ((a) -> a), (a,b) -> a.name..' is satisfied')\toList!,
{'seal is satisfied', 'fox is satisfied'})
--last
assert lemonade\last! == 'here'
assert lemonade\last((a) -> #a < 4) == 'ice'
--lastOrDefault
assert lemonade\lastOrDefault('tea') == 'here'
assert lemonade\lastOrDefault('tea', (a) -> #a < 4) == 'ice'
assert lemonade\lastOrDefault('tea', (a) -> #a < 3) == 'tea'
--max
assert lemonade\max! == 'your'
assert numbers\max! == 300
mixedComparer = (a) -> if type(a) == 'string' then #a else a
assert mixed\max(mixedComparer) == 5
--min
assert lemonade\min! == 'cold'
assert numbers\min! == 1
mixedComparer = (a) -> if type(a) == 'string' then #a else 10
assert mixed\min(mixedComparer) == 3
--ofType
assert isSame(lemonade\ofType('number')\toList!, {})
assert isSame(numbers\ofType('number')\toList!, numbers\toList!)
assert isSame(mixed\ofType('number')\toList!, {1,2,3})
assert isSame(lemonade\ofType('string')\toList!, lemonade\toList!)
assert isSame(numbers\ofType('string')\toList!, {})
assert isSame(mixed\ofType('string')\toList!, {'apple', 'fig', 'kiwi'})
--orderBy
--TODO: test with custom comparer
assert isSame(lemonade\orderBy!\toList!,
{'cold','get','here','ice','lemonade','your'})
assert isSame(lemonade\orderBy((a) -> #a)\toList!,
{'get','ice','your','cold','here','lemonade'})
assert isSame(numbers\orderBy!\toList!,
{1,2,3,10,10,10,100,200,300})
assert isSame(numbers\orderBy((a) -> -a)\toList!,
{300,200,100,10,10,10,3,2,1})
mixedSelector = (a) -> if type(a) == 'string' then #a else 10
assert isSame(mixed\orderBy(mixedSelector)\toList!, {'fig','kiwi','apple',1,2,3})
--orderByDescending
--TODO: test with custom comparer
assert isSame(lemonade\orderByDescending!\toList!,
{'your','lemonade','ice','here','get','cold'})
assert isSame(lemonade\orderByDescending((a) -> #a)\toList!,
{'lemonade','your','cold','here','get','ice'})
assert isSame(numbers\orderByDescending!\toList!,
{300,200,100,10,10,10,3,2,1})
assert isSame(numbers\orderByDescending((a) -> -a)\toList!,
{1,2,3,10,10,10,100,200,300})
mixedSelector = (a) -> if type(a) == 'string' then #a else 10
assert isSame(mixed\orderByDescending(mixedSelector)\toList!, {1,2,3,'apple','kiwi','fig'})
--prepend
assert isSame(lemonade\prepend('extra')\toList!,
{'extra','get','your','ice','cold','lemonade','here'})
assert isSame(numbers\prepend(17)\toList!,
{17,1,2,3,10,10,10,100,200,300})
--range
assert isSame(Enumerable\range(0,5)\toList!, {0,1,2,3,4})
assert isSame(Enumerable\range(-3,5)\toList!, {-3,-2,-1,0,1})
--repeatElement
assert isSame(Enumerable\repeatElement(0,5)\toList!, {0,0,0,0,0})
assert isSame(Enumerable\repeatElement(-3,5)\toList!, {-3,-3,-3,-3,-3})
assert isSame(Enumerable\repeatElement('i',5)\toList!, {'i','i','i','i','i'})
--reverse
assert isSame(lemonade\reverse!\toList!,
{'here','lemonade','cold','ice','your','get'})
assert isSame(numbers\reverse!\toList!,
{300,200,100,10,10,10,3,2,1})
--select
assert isSame(lemonade\select((a) -> #a)\toList!, {3,4,3,4,8,4})
assert isSame(lemonade\select((a, i) -> #a + i)\toList!, {4,6,6,8,13,10})
--selectMany
tmp = Enumerable\fromList(
{
{'dog', 'cow', 'bear'},
{'fish'},
{'mouse', 'buffalo'}
})
assert isSame(tmp\selectMany!\toList!,
{'dog', 'cow', 'bear', 'fish', 'mouse', 'buffalo'})
assert isSame(tmp\selectMany(((a) -> a), (a) -> #a)\toList!,
{3,3,4,4,5,7})
assert isSame(tmp\selectMany(nil, (a) -> #a)\toList!,
{3,3,4,4,5,7})
assert isSame(tmp\selectMany((a) -> {a[1]})\toList!,
{'dog','fish','mouse'})
assert isSame(tmp\selectMany(((a) -> {a[1]}), (a) -> #a)\toList!,
{3,4,5})
--sequenceEqual
tmp = Enumerable\fromList({'duck', 'duck','goose'})
isSameType = (a,b) -> type(a) == type(b)
assert tmp\sequenceEqual(Enumerable\fromList({'duck', 'duck', 'goose'})) == true
assert tmp\sequenceEqual(Enumerable\fromList({'duck', 'duck', 'duck'})) == false
assert tmp\sequenceEqual(Enumerable\fromList({'duck', 'duck', 'duck'}), isSameType) == true
--single
assert Enumerable\fromList({'duck'})\single! == 'duck'
assert lemonade\single((a) -> #a == 8) == 'lemonade'
--singleOrDefault
assert Enumerable\fromList({'duck'})\singleOrDefault('goose') == 'duck'
assert lemonade\singleOrDefault('goose', (a) -> #a == 8) == 'lemonade'
assert lemonade\singleOrDefault('goose', (a) -> #a == 9) == 'goose'
--skip
assert isSame(lemonade\skip(4)\toList!, {'lemonade','here'})
--skipLast
assert isSame(lemonade\skipLast(4)\toList!, {'get','your'})
--skipWhile
assert isSame(lemonade\skipWhile((a) -> #a < 6)\toList!, {'lemonade','here'})
--sum
assert numbers\sum! == 636
assert lemonade\sum((a) -> #a) == 26
--take
assert isSame(lemonade\take(2)\toList!, {'get','your'})
--takeLast
assert isSame(lemonade\takeLast(2)\toList!, {'lemonade','here'})
--takeWhile
assert isSame(lemonade\takeWhile((a) -> #a < 6)\toList!, {'get','your','ice','cold'})
--thenBy
--TODO: test with custom comparer
assert isSame(lemonade\orderBy((a) -> #a)\thenBy((a) -> a)\toList!,
{'get','ice','cold','here','your','lemonade'})
--thenByDescending
--TODO: test with custom comparer
assert isSame(lemonade\orderByDescending((a) -> #a)\thenByDescending((a) -> a)\toList!,
{'lemonade','your','here','cold','ice','get'})
--toArray
assert isSame(mixed\toArray!, {[1]:1, [2]:2, [3]:3, [4]:'apple', [5]:'fig', [6]:'kiwi'})
--toDictionary
assert isSame(lemonade\toDictionary(((a)-> a), (a) -> #a),
{ get: 3, your: 4, ice: 3, cold: 4, lemonade: 8, here: 4 })
--toEnumerable
assert isSame(lemonade\toEnumerable!, lemonade)
--toHashSet
assert isSame(lemonade\toHashSet!,
{ get: true, your: true, ice: true, cold: true, lemonade: true, here: true })
--toList
assert isSame(mixed\toList!, {1,2,3,'apple', 'fig', 'kiwi'})
--toLookup
assert isSame(lemonade\toLookup((a) -> #a),
{
[3]:{'get','ice'},
[4]:{'your','cold','here'},
[8]:{'lemonade'}
})
--union
assert isSame(numbers\union(mixed)\toList!, {1,2,3,10,100,200,300,'apple','fig','kiwi'})
--where
assert isSame(lemonade\where((a) -> #a < 4)\toList!
{'get','ice'})
assert isSame(numbers\where((a) -> a * a < 150)\toList!
{1,2,3,10,10,10})
--zip
assert isSame(numbers\zip(mixed)\toList!,
{ {1,1}, {2,2}, {3,3}, {10,'apple'}, {10,'fig'}, {10,'kiwi'} })
assert isSame(lemonade\zip(mixed, (a,b) -> 'step '..b..': print "'..a..'"')\toList!,
{
'step 1: print "get"',
'step 2: print "your"',
'step 3: print "ice"',
'step apple: print "cold"',
'step fig: print "lemonade"',
'step kiwi: print "here"'
})
print 'All Tests Passed' | 32.348837 | 105 | 0.630302 |
ec4d51fe1d2e27caebac2c4d8ac45fa06692a258 | 11,089 |
--
-- Copyright (C) 2017-2020 DBotThePony
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
DLib = DLib
Notify = DLib.Notify
import insert, remove from table
import newLines, allowedOrigin from Notify
class NotifyBase
new: (contents = {'Sample Text'}) =>
if type(contents) == 'string'
contents = {contents}
if not @m_sound then @m_sound = ''
if not @m_font then @m_font = 'Default'
if not @m_color then @m_color = Color(255, 255, 255)
if not @m_length then @m_length = 4
@m_text = contents
@m_lastThink = CurTimeL!
@m_created = @m_lastThink
@m_start = @m_created
@m_finish = @m_start + @m_length
@m_console = true
@m_timer = true
if not @m_align then @m_align = TEXT_ALIGN_LEFT
@m_isDrawn = false
@m_isValid = true
if @m_shadow == nil then @m_shadow = true
if @m_shadowSize == nil then @m_shadowSize = 2
@m_fontobj = Notify.Font(@m_font)
@CompileCache!
@CalculateTimer!
Bind: (obj) =>
@dispatcher = obj
@thinkID = insert(@dispatcher.thinkHooks, @)
@dispatcher.xSmoothPositions[@thinkID] = nil
@dispatcher.ySmoothPositions[@thinkID] = nil
return @
GetDrawInConsole: => @m_console
GetNotifyInConsole: => @m_console
GetAlign: => @m_align
GetTextAlign: => @m_align
GetSound: => @m_sound
HasSound: => @m_sound ~= ''
GetStart: => @m_start
GetLength: => @m_length
FinishesOn: => @m_finish
StopsOn: => @m_finish
IsTimer: => @m_timer
GetText: => @m_text
GetFont: => @m_font
GetColor: => @m_color
GetTextColor: => @m_color
GetDrawShadow: => @m_shadow
GetShadowSize: => @m_shadowSize
IsValid: => @m_isValid
Start: =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
assert(@dispatcher, 'Not bound to a dispatcher!')
if @m_isDrawn then return @
@m_isDrawn = true
if @m_sound ~= '' then surface.PlaySound(@m_sound)
@SetStart!
if @m_console
MsgC(Color(0, 200, 0), '[DNotify] ', @m_color, unpack(@m_text))
MsgC('\n')
return @
Remove: =>
if not @m_isDrawn then return false
@m_isValid = false
return true
SetNotifyInConsole: (val = true) =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
assert(type(val) == 'boolean', 'must be boolean')
@m_console = val
return @
SetAlign: (val = TEXT_ALIGN_LEFT) =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
assert(allowedOrigin(val), 'Not a valid align')
@m_align = val
@CompileCache!
return @
SetTextAlign: (...) => @SetAlign(...)
SetDrawShadow: (val = true) =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
assert(type(val) == 'boolean', 'must be boolean')
@m_shadow = val
return @
SetShadowSize: (val = 2) =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
assert(type(val) == 'number', 'must be number')
@m_shadowSize = val
return @
SetColor: (val = Color(255, 255, 255)) =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
assert(val.r and val.g and val.b and val.a, 'Not a valid color')
@m_color = val
@CompileCache!
return @
FixFont: =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
result = pcall(surface.SetFont, @m_font)
if not result
print '[Notify] ERROR: Invalid font: ' .. @m_font
print debug.traceback!
@m_font = 'Default'
return @
SetFont: (val = 'Default') =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
@m_font = val
@FixFont!
@m_fontobj\SetFont(val)
@CompileCache!
return @
__setTextInternal: (tab) =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
@m_text = {}
for i, value in pairs tab
if type(value) == 'table' and value.r and value.g and value.b and value.a
insert(@m_text, value)
elseif type(value) == 'string'
insert(@m_text, value)
elseif type(value) == 'number'
insert(@m_text, tostring(value))
SetText: (...) =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
tryTable = {...}
tryFirst = tryTable[1]
if type(tryFirst) == 'string' or type(tryFirst) == 'number'
@__setTextInternal(tryTable)
@CompileCache!
if not @m_isDrawn then @CalculateTimer!
return @
elseif type(tryFirst) == 'table'
if (not tryFirst.r or not tryFirst.g or not tryFirst.b or not tryFirst.a) and not tryFirst.m_Notify_type
@__setTextInternal(tryFirst)
else
@__setTextInternal(tryTable)
@CompileCache!
if not @m_isDrawn then @CalculateTimer!
return @
else
error('Unknown argument!')
return @
SetStart: (val = CurTimeL(), resetTimer = true) =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
assert(type(val) == 'number', '#1 must be a number')
assert(type(resetTimer) == 'boolean', '#2 must be a boolean')
@m_start = val
if resetTimer then @ResetTimer(false)
return @
ClearSound: =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
@m_sound = ''
return @
SetSound: (newSound = '') =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
assert(type(newSound) == 'string', 'SetSound - must be a string')
@m_sound = newSound
return @
ResetTimer: (affectStart = true) =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
if affectStart then @m_start = CurTimeL()
@m_finish = @m_start + @m_length
return @
StopTimer: =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
@m_timer = false
return @
StartTimer: =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
@m_timer = true
return @
SetLength: (new = 4) =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
assert(type(new) == 'number', 'must be a number')
if new < 3 then new = 3
@m_length = new
@ResetTimer!
return @
SetFinish: (new = CurTimeL! + 4) =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
assert(type(new) == 'number', 'must be a number')
@m_finish = new
@m_length = new - @m_start
return @
CalculateTimer: =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
newLen = 2
for i, object in pairs @m_text
if type(object) == 'string'
newLen += (#object) ^ (1 / 2)
@m_calculatedLength = math.Clamp(newLen, 4, 10)
@SetLength(@m_calculatedLength)
return @
ExtendTimer: (val = @m_calculatedLength) =>
assert(type(val) == 'number', 'must be a number')
@SetFinish(CurTimeL! + val)
return @
SetThink: (val = (->)) =>
assert(type(val) == 'function', 'must be a function')
@m_thinkf = val
return @
CompileCache: =>
@m_cache = {}
@m_sizeOfTextX = 0
@m_sizeOfTextY = 0
lineX = 0
maxX = 0
maxY = 0
nextY = 0
currentLine = {}
lastColor = @GetColor!
lastFont = @m_font
surface.SetFont(@m_font)
for i, object in pairs @m_text
if type(object) == 'table' -- But we will skip colors
if object.m_Notify_type
if object.m_Notify_type == 'font'
surface.SetFont(object\GetFont())
lastFont = object\GetFont()
else
lastColor = object
elseif type(object) == 'string'
split = newLines(object)
first = true
firstHitX = 0
for i, str in pairs split
sizeX, sizeY = surface.GetTextSize(str)
firstHitX = sizeX
if not first -- Going to new line
maxY += 4
insert(@m_cache, {content: currentLine, :lineX, shiftX: 0, :maxY, :nextY})
currentLine = {}
@m_sizeOfTextY += maxY
nextY += maxY
if lineX > maxX then maxX = lineX
lineX = 0
maxY = 0
first = false
insert(currentLine, {color: lastColor, content: str, x: lineX, font: lastFont})
lineX += sizeX
if sizeY > maxY then maxY = sizeY
if maxX == 0 then maxX = firstHitX
@m_sizeOfTextY += maxY
insert(@m_cache, {content: currentLine, :lineX, shiftX: 0, :maxY, :nextY})
@m_sizeOfTextX = maxX
if @m_align == TEXT_ALIGN_RIGHT
for i, line in pairs @m_cache
line.shiftX = @m_sizeOfTextX - line.lineX
elseif @m_align == TEXT_ALIGN_CENTER
for i, line in pairs @m_cache
line.shiftX = (@m_sizeOfTextX - line.lineX) / 2
return @
Draw: (x = 0, y = 0) =>
print 'Non overriden version!'
print debug.traceback!
return 0
ThinkNotTimer: =>
-- Override
ThinkTimer: =>
-- Override
GetNonValidTime: => @m_finish
Think: =>
assert(@IsValid!, 'tried to use a finished Slide Notification!')
deltaThink = CurTimeL() - @m_lastThink
if not @m_timer
@m_created += deltaThink
@m_finish += deltaThink
@ThinkNotTimer(deltaThink)
else
cTime = CurTimeL()
if @GetNonValidTime! <= cTime
@Remove!
return false
@ThinkTimer(deltaThink, cTime)
if @m_thinkf then @m_thinkf!
return @
class NotifyDispatcherBase
new: (data = {}) =>
@x_start = data.x or 0
@y_start = data.y or 0
@width = data.width or ScrWL!
@height = data.height or ScrHL!
@heightFunc = data.getheight
@xFunc = data.getx
@widthFunc = data.getwidth
@yFunc = data.gety
@heightArgs = data.height_func_args or {}
@widthArgs = data.width_func_args or {}
@xArgs = data.x_func_args or {}
@yArgs = data.y_func_args or {}
@data = data
if not @obj then @obj = NotifyBase
@thinkHooks = {}
@ySmoothPositions = {}
@xSmoothPositions = {}
IsValid: => true
Create: (...) => self.obj(...)\Bind(@)
Clear: => for i, obj in pairs @thinkHooks do obj\Remove()
Draw: =>
print 'Non-overriden version!'
print debug.traceback!
return @
Think: =>
if type(@xFunc) == 'function'
@x_start = @xFunc(unpack(@xArgs)) or @x_start
if type(@yFunc) == 'function'
@y_start = @yFunc(unpack(@yArgs)) or @y_start
if type(@heightFunc) == 'function'
@height = @heightFunc(unpack(@heightArgs)) or @height
if type(@widthFunc) == 'function'
@width = @widthFunc(unpack(@widthArgs)) or @width
for k, func in pairs @thinkHooks
if func\IsValid()
status, err = pcall(func.Think, func)
if not status
print '[Notify] ERROR ', err
else
@thinkHooks[k] = nil
@ySmoothPositions[func.thinkID] = nil
return @
Notify.NotifyBase = NotifyBase
Notify.NotifyDispatcherBase = NotifyDispatcherBase
| 25.550691 | 107 | 0.666516 |
3292cbd7da2163cb8251673fa702a041fb8991ad | 394 | adapters = with {}
.FileSystemAdapter = dependency("novacbn/luvit-extras/adapters/FileSystemAdapter").FileSystemAdapter
with exports
.adapters = adapters
.crypto = dependency "novacbn/luvit-extras/crypto"
.fs = dependency "novacbn/luvit-extras/fs"
.process = dependency "novacbn/luvit-extras/process"
.vfs = dependency "novacbn/luvit-extras/vfs" | 43.777778 | 104 | 0.695431 |
f2d37bf999dd25ec86b0ccc34a355ae454d0896b | 826 | export modinfo = {
type: "command"
desc: "Capture"
alias: {"cap"}
func: getDoPlayersFunction (v) ->
_pos = LocalPlayer.Character.Head.CFrame * CFrame.new(10, 10, 10)
Stop = false
Part = v.Character.Torso
if Part.Anchored == true
Part.Anchored = false
pos = CreateInstance"BodyPosition"{
Parent: Part
maxForce: Vector3.new(math.huge, math.huge, math.huge)
position: _pos.p
}
Sin = (i) -> return math.sin(math.rad(i))
Cos = (i) -> return math.cos(math.rad(i))
gyro = CreateInstance"BodyGyro"
Parent: Part
maxTorque: Vector3.new(math.huge, math.huge, math.huge)
for i = 0,math.huge,2.5
if Stop == false
pos.position = LocalPlayer.Character.Torso.CFrame\toWorldSpace(CFrame.new(Vector3.new(Sin(i)*4, 1.5, Cos(i)*4))).p
gyro.cframe = CFrame.Angles(0,math.rad(i),0)
wait()
} | 31.769231 | 119 | 0.66707 |
fed65d526db6cec1f639ca228c587e68ececd998 | 1,376 | import encode_base64 from require 'lapis.util.encoding'
--------------------------------------------------------------------------------
isempty = (s) -> s == nil or s == ''
--------------------------------------------------------------------------------
settings_basic_auth = (item) ->
'Basic ' .. encode_base64("#{item.ba_login}:#{item.ba_pass}")
--------------------------------------------------------------------------------
basic_auth = (app, setting, page_info) ->
if app.req.headers['authorization']
if settings_basic_auth(setting) == app.req.headers['authorization'] or
settings_basic_auth(page_info.folder) == app.req.headers['authorization'] or
settings_basic_auth(page_info.page) == app.req.headers['authorization']
app.session.basic_auth = app.req.headers['authorization']
--------------------------------------------------------------------------------
is_auth = (app, setting, page_info) ->
(
isempty(setting.ba_login) and
isempty(page_info.page.ba_login) and
isempty(page_info.folder.ba_login)
) or
app.session.basic_auth == settings_basic_auth(setting) or
app.session.basic_auth == settings_basic_auth(page_info.folder) or
app.session.basic_auth == settings_basic_auth(page_info.page)
--------------------------------------------------------------------------------
-- expose methods
{ :basic_auth, :is_auth } | 52.923077 | 83 | 0.512355 |
4605944fda5b2ce3c5d70ee32431bb141db035de | 4,951 | argparse = require "argparse"
fs = require "fs"
chdir = _G.chdir
parser = argparse name: "spook", description: "Watches for changes and runs functions (and commands) in response, based on a config file (eg. Spookfile) or watches any files it is given on stdin (similar to the entrproject).", epilog: "For more see https://github.com/johnae/spook"
parser\flag("-v", "Show the Spook version you're running and exit.")\action ->
print(require "version")
os.exit 0
parser\flag("-i", "Initialize an example Spookfile in the current dir.")\action ->
f = io.open("Spookfile", "wb")
content = [[
-- vim: syntax=moon
-- How much log output can you handle? (ERR, WARN, INFO, DEBUG)
log_level "INFO"
-- Require some things that come with spook
fs = require 'fs'
-- We want to use the coroutine based execute which can also be
-- interrupted using ctrl-c etc. I would recommend this most of the
-- time even though os.execute works just fine (except for job control etc).
execute = require('process').execute
-- Adds the built-in terminal_notifier
notify.add 'terminal_notifier'
-- if the added notifier is a string it will be loaded using
-- 'require'. It can also be specified right here, like:
-- notify.add {
-- start: (msg, info) ->
-- print "Start, yay"
-- success: (msg, info) ->
-- print "Success, yay!"
-- fail: (msg, info) ->
-- print "Fail, nay!"
-- }
-- If we find 'notifier' in the path, let's
-- add that notifier also but fail silently
-- if something goes wrong (eg. wasn't
-- found in path or a syntax error).
pcall notify.add, 'notifier'
-- Define a function for running rspec.
-- Please see https://github.com/johnae/spook
-- for more advanced examples which you may
-- be interested in if you want to replace
-- ruby guard.
rspec = (file) ->
return true unless fs.is_file file
notify.info "RUNNING rspec #{file}"
_, _, status = execute "./bin/rspec -f d #{file}"
assert status == 0, "rspec #{file} - failed"
-- And another for running ruby files
ruby = (file) ->
return true unless fs.is_file file
notify.info "RUNNING ruby #{file}"
_, _, status = execute "ruby #{file}"
assert status == 0, "ruby #{file} - failed"
status == 0
-- For more advanced use of notifications, reruns, task filtering
-- etc. Please see "spookfile_helpers". There should be good examples
-- of usage in spook's own Spookfile.
-- Setup what directories to watch and what to do
-- when a file is changed. For notifications, the
-- function(s) to run should be wrapped in a "notifies"
-- call and possibly other calls from spookfile_helpers.
-- See spook's own Spookfile for examples of that or
-- browse the README at https://github.com/johnae/spook.
watch '.', ->
on_changed '^(spec)/(spec_helper%.rb)', (event) ->
rspec 'spec'
on_changed '^spec/(.*)_spec%.rb', (event, name) ->
rspec "spec/#{a}_spec.rb"
on_changed '^lib/(.*)%.rb', (event, name) ->
rspec "spec/lib/#{a}_spec.rb"
on_changed '^app/(.*)%.rb', (event, name) ->
rspec "spec/#{a}_spec.rb"
-- Some experimentation perhaps?
on_changed '^playground/(.*)%.rb', (event, name) ->
ruby "playground/#{a}.rb"
-- have spook re-execute itself when the Spookfile changes,
-- a "softer" version would be load_spookfile! but normally
-- it's simpler and cleaner to just re-execute.
on_changed '^Spookfile$', ->
notify.info 'Re-executing spook...'
reload_spook!
]]
f\write(content)
f\close!
os.exit 0
parser\option("-l", "Log level either ERR, WARN, INFO or DEBUG.")\args(1)
parser\option("-c", "Expects the path to a Spook config file (eg. Spookfile) - overrides the default of loading a Spookfile from cwd.")\args("1")
parser\option("-w", "Expects the path to working directory - overrides the default of using wherever spook was launched.")\args("1")\action (args, _, dir) ->
if fs.is_dir dir
chdir dir
else
print "#{dir} is not a directory"
os.exit 1
parser\option("-f", "Expects a path to a MoonScript or Lua file - runs the script within the context of spook, skipping the default behavior completely.\nAny arguments following the path to the file will be given to the file itself.")\args(1)
parser\flag("-s", "Stdin mode only: start the given utility immediately without waiting for changes first. \nThe utility to run should be given as the last arg(s) on the commandline. Without a utility spook will output the changed file path.")
parser\flag("-o", "Stdin mode only: exit immediately after running utility (or receiving an event basically). \nThe utility to run should be given as the last arg(s) on the commandline. Without a utility spook will output the changed file path.")
parser\option("-r", "Wait this many seconds for data on stdin before bailing (0 means don't wait for any data at all).", "2")\args(1)
parser\option("-p", "Write the pid of the running spook process to given file path.")\args(1)
parser\flag("--", "Disable argument parsing from here.")
parser | 38.984252 | 281 | 0.695415 |
c3331102ef3852e24cbdf7696b5c8b88c0860a85 | 2,633 | gameplay = {}
local ui
roomsCount = 5
export depth = 0
gameplay.enter = (previous) =>
-- set up the level
export world = bump.newWorld!
ui = UI uiWidth, uiHeight
export player = Player 0, 0
export dungeon = Dungeon roomsCount
center = dungeon.currentRoom.center
export camera = Camera center.x, center.y, gameWidth, gameHeight
export fadeColor = {0,0,0,1}
fadeIn!
with camera
\setFollowStyle "SCREEN_BY_SCREEN"
\setFollowLerp 0.2
.scale = 1
export debugDrawSprites = true
export debugDrawCollisionBoxes = false
export debugEnableShaders = true
export debugDrawPathGrid = false
export debugDrawEnemyPath = false
gameplay.update = (dt) =>
-- update entities
with camera
\update dt
\follow player.pos.x + player.offset.x, player.pos.y + player.offset.y
input\update!
tick.update dt
flux.update dt
dungeon\update dt
player\update dt
gameplay.leave = (next) =>
-- destroy entities and cleanup resources
--dungeon\destruct!
--for item in *world\getItems!
-- world\remove item
--player = nil
--camera = nil
--ui = nil
gameplay.draw = () =>
-- draw the level
push\start!
love.graphics.translate 0, uiHeight
camera\attach!
dungeon\draw!
player\draw!
camera\detach!
camera\draw!
love.graphics.translate 0, -uiHeight
ui\draw!
love.graphics.setColor fadeColor
love.graphics.rectangle "fill", 0, 0, gameWidth, screenHeight
push\finish!
gameplay.keypressed = (key) =>
switch key
when "k" then dungeon.currentRoom.cleared = true
when "h" then manager\push states.help
when "f"
push\switchFullscreen(windowedWidth, windowedHeight)
when "g" then manager\enter states.death
when "f1" then export debugDrawSprites = not debugDrawSprites
when "f2" then export debugDrawCollisionBoxes = not debugDrawCollisionBoxes
when "f3"
export debugEnableShaders = not debugEnableShaders
shaders\set debugEnableShaders
when "f4" then export debugDrawPathGrid = not debugDrawPathGrid
when "f5" then export debugDrawEnemyPath = not debugDrawEnemyPath
when "f6" nextDungeon!
when "kp4"
export colorScheme = colorScheme + 1
if colorScheme > #colorSchemes then colorScheme = 1
export colors = colorSchemes[colorScheme]
sprites\refreshColors!
when "kp6"
export colorScheme = colorScheme - 1
if colorScheme < 1 then colorScheme = #colorSchemes
export colors = colorSchemes[colorScheme]
sprites\refreshColors!
when "escape"
manager\pop!
when "kp+" camera.scale += 0.1
when "kp-" camera.scale -= 0.1
return gameplay | 26.33 | 79 | 0.700722 |
e43d369c3454bc1ff5c038aa20fc0e47d402489f | 101 | export modinfo = {
type: "command"
desc: "GameOver"
alias: {"gmov"}
func: ->
SetSky 264663367
} | 14.428571 | 18 | 0.633663 |
eef6db955f59f2119a2eb0d394e9af513453b5f8 | 222 | import insert, concat from table
(flags={}) ->
lines = {
"logs/"
"nginx.conf.compiled"
}
if not flags.lua
insert lines, "*.lua"
if flags.tup
insert lines, ".tup"
concat(lines, "\n") .. "\n"
| 13.875 | 32 | 0.54955 |
bd3aaf9c8f1b7a651782b65185b6426068cb54f5 | 531 | -- implement singleton log
logger = require "log"
list_writer = require "log.writer.list"
console_color = require "log.writer.console.color"
util = require "mooncrafts.util"
local *
to_json = util.to_json
doformat = (p) ->
if type(p) == "table"
return to_json p
if p == nil
return "nil"
tostring(p)
formatter = (...) ->
params = [doformat(v) for v in *{...}]
table.concat(params, ' ')
log = logger.new( "info", list_writer.new( console_color.new() ), formatter )
log
| 18.310345 | 77 | 0.60452 |
feb3b23109b33f709ca80b1070f62117e309631d | 820 | Dorothy!
TabButtonView = require "View.Control.Item.TabButton"
-- [signal]
-- "Checked",(checked,tabButton)->
-- "Expanded",(expanded)->
-- [params]
-- x, y, width, height, text, file
Class TabButtonView,
__init: (args)=>
@file = args.file
@_expanded = args.expanded == true
@emit "Expanded",true if @_expanded
@_checked = false
@_isCheckMode = false
@slot "Tapped", ->
if @_isCheckMode
@_checked = not @_checked
@emit "Checked",@_checked,@
else
@_expanded = not @_expanded
@emit "Expanded",@_expanded
expanded: property => @_expanded
checked: property => @_checked
isCheckMode: property => @_isCheckMode,
(value)=>
@_isCheckMode = value
if not value and @_checked
@_checked = false
@emit "Checked",false,@
@emit "TapEnded"
| 23.428571 | 54 | 0.629268 |
c922ebd068e57009a1564c62c26b9e0a93894257 | 2,300 | import HelpContext from howl.ui
describe 'HelpContext', ->
local help
get_text = -> help\get_buffer!.text
before_each -> help = HelpContext!
context 'add_section', ->
it 'returns text added via add_section', ->
help\add_section heading: 'hello', text: 'world'
assert.same 'hello\n\nworld\n', get_text!
it 'parses text as markup', ->
help\add_section heading: 'hello', text: '<string>world</>'
assert.same 'hello\n\nworld\n', get_text!
it 'concatenates multiple sections add_section', ->
help\add_section heading: 'title', text: 'line 1'
help\add_section text: 'line 2'
assert.same 'title\n\nline 1\n\nline 2\n', get_text!
context 'add_keys', ->
it 'returns a table of keys added via add_keys', ->
help\add_keys ctrl_a: 'line 1'
help\add_keys f2: 'line 2'
assert.same 'Keys\nctrl_a line 1\nf2 line 2\n', get_text!
it 'preserves order in which keys were added', ->
help\add_keys f3: 'line 1'
help\add_keys f1: 'line 2'
help\add_keys f2: 'line 3'
help\add_keys f5: 'line 4'
assert.same 'Keys\nf3 line 1\nf1 line 2\nf2 line 3\nf5 line 4\n', get_text!
it 'maps command names to binding keys', ->
howl.bindings.push ctrl_t: 'test-command'
help\add_keys ['test-command']: 'line 1'
assert.same 'Keys\nctrl_t line 1\n', get_text!
it 'also accepts list of tables as keys', ->
help\add_keys {
{ctrl_b: 'line 1'}
{ctrl_c: 'line 2'}
{ctrl_a: 'line 3'}
}
assert.same 'Keys\nctrl_b line 1\nctrl_c line 2\nctrl_a line 3\n', get_text!
it 'puts all sections together before all keys', ->
help\add_keys ctrl_a: 'line 1'
help\add_section text: 'section 1'
help\add_keys ctrl_b: 'line 2'
help\add_section text: 'section 2'
assert.same 'section 1\n\nsection 2\n\nKeys\nctrl_a line 1\nctrl_b line 2\n', get_text!
context 'merge', ->
it 'merges keys and sections from other contexts', ->
help\add_keys ctrl_a: 'line 1'
help\add_section text: 'section 1'
help2 = HelpContext!
help2\add_keys ctrl_b: 'line 2'
help2\add_section text: 'section 2'
help\merge help2
assert.same 'section 1\n\nsection 2\n\nKeys\nctrl_a line 1\nctrl_b line 2\n', get_text!
| 33.823529 | 93 | 0.642609 |
efa2a4614064c5cbf1402955d6a873e072b27d20 | 4,683 | {
whitelist_shadowing: {
['bundles/vi']: {
'editor'
}
}
whitelist_globals: {
["."]: {
'bundle_file',
'bundle_load',
'bundles',
'callable',
'howl',
'jit',
'log',
'moon',
'moonscript',
'r',
'typeof',
'user_load',
},
['bundles/']: {
'provide_module',
'require_bundle'
}
['themes/']: {
'flair',
'highlight',
'theme_file',
'aliceblue',
'antiquewhite',
'aqua',
'aquamarine',
'azure',
'beige',
'bisque',
'black',
'blanchedalmond',
'blue',
'blueviolet',
'brown',
'burlywood',
'cadetblue',
'chartreuse',
'chocolate',
'coral',
'cornflowerblue',
'cornsilk',
'crimson',
'cyan',
'darkblue',
'darkcyan',
'darkgoldenrod',
'darkgray',
'darkgrey',
'darkgreen',
'darkkhaki',
'darkmagenta',
'darkolivegreen',
'darkorange',
'darkorchid',
'darkred',
'darksalmon',
'darkseagreen',
'darkslateblue',
'darkslategray',
'darkslategrey',
'darkturquoise',
'darkviolet',
'deeppink',
'deepskyblue',
'dimgray',
'dimgrey',
'dodgerblue',
'firebrick',
'floralwhite',
'forestgreen',
'fuchsia',
'gainsboro',
'ghostwhite',
'gold',
'goldenrod',
'gray',
'grey',
'green',
'greenyellow',
'honeydew',
'hotpink',
'indianred',
'indigo',
'ivory',
'khaki',
'lavender',
'lavenderblush',
'lawngreen',
'lemonchiffon',
'lightblue',
'lightcoral',
'lightcyan',
'lightgoldenrodyellow',
'lightgray',
'lightgrey',
'lightgreen',
'lightpink',
'lightsalmon',
'lightseagreen',
'lightskyblue',
'lightslategray',
'lightslategrey',
'lightsteelblue',
'lightyellow',
'lime',
'limegreen',
'linen',
'magenta',
'maroon',
'mediumaquamarine',
'mediumblue',
'mediumorchid',
'mediumpurple',
'mediumseagreen',
'mediumslateblue',
'mediumspringgreen',
'mediumturquoise',
'mediumvioletred',
'midnightblue',
'mintcream',
'mistyrose',
'moccasin',
'navajowhite',
'navy',
'oldlace',
'olive',
'olivedrab',
'orange',
'orangered',
'orchid',
'palegoldenrod',
'palegreen',
'paleturquoise',
'palevioletred',
'papayawhip',
'peachpuff',
'peru',
'pink',
'plum',
'powderblue',
'purple',
'red',
'rosybrown',
'royalblue',
'saddlebrown',
'salmon',
'sandybrown',
'seagreen',
'seashell',
'sienna',
'silver',
'skyblue',
'slateblue',
'slategray',
'slategrey',
'snow',
'springgreen',
'steelblue',
'tan',
'teal',
'thistle',
'tomato',
'turquoise',
'violet',
'wheat',
'white',
'whitesmoke',
'yellow',
'yellowgreen',
},
spec: {
'after_each',
'async',
'before_each',
'close_all_buffers',
'collect_memory',
'context',
'describe',
'get_ui_list_widget_column',
'howl_async',
'howl_main_ctx'
'it',
'moon',
'set_howl_loop',
'settimeout',
'setup',
'spy',
'Spy',
'teardown',
'within_activity',
'with_signal_handler',
'with_tmpdir',
'trimmed_text'
},
sandboxed_loader_spec: {
'foo_load',
'foo_file'
}
sandbox_spec: {
'from_env'
}
_lexer: {
'alpha',
'alnum',
'any',
'back_was',
'blank',
'capture',
'B',
'C',
'Cc',
'Cg',
'Cmt',
'compose',
'complement',
'digit',
'eol',
'float',
'hexadecimal',
'hexadecimal_float',
'last_token_matches',
'line_start',
'lower',
'match_back',
'match_until',
'sequence',
'S',
'scan_to',
'scan_until',
'separate',
'octal',
'P',
'paired',
'R',
'scan_through_indented',
'scan_until_capture',
'space',
'span',
'sub_lex',
'sub_lex_by_lexer',
'sub_lex_by_inline',
'sub_lex_match_time',
'sub_lex_by_pattern',
'sub_lex_by_pattern_match_time',
'word',
'V',
'upper',
'xdigit'
}
}
}
| 17.539326 | 38 | 0.462097 |
dc70154f87c3ba7b126036b8e171c3653d59cc92 | 671 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
append = table.insert
new = (options = {}) ->
spy =
called: false
reads: {}
writes: {}
called_with: {}
setmetatable spy,
__call: (_, ...) ->
spy.called = true
rawset spy, 'called_with', {...}
options.with_return
__index: (t,k) ->
append spy.reads, k
if options.as_null_object
sub = new options
rawset spy, k, sub
return sub
spy.writes[k]
__newindex: (t,k,v) ->
spy.writes[k] = v
spy
return setmetatable {}, __call: (_, options) -> new options
| 21.645161 | 79 | 0.584203 |
8a6fb191cd81536c97b15fc18db2da217def2a00 | 11,395 | -- Copyright 2018 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import SearchView, NotificationWidget from howl.ui
match = require 'luassert.match'
describe 'SearchView', ->
local command_line, search_view, list_widget, editor, buffer, finish_result, search, preview_buffer, error_message, info_message, find_iter_count
keypress = (keystroke) ->
search_view.keymap[keystroke] search_view
howl.app\pump_mainloop! -- allow all timer.asap functions to run
keypress_binding_for = (cmd) ->
search_view.keymap.binding_for[cmd] search_view
howl.app\pump_mainloop! -- allow all timer.asap functions to run
set_text = (sv, text) ->
command_line.text = text
sv\on_text_changed text
-- wait for searcher to be done, since it runs in a separate coroutine
if sv.searcher.running
howl.dispatch.wait sv.searcher.running
howl.app\pump_mainloop! -- allow all timer.asap functions to run
list_widget_items = -> list_widget.list._items
list_widget_height = -> list_widget.height
found_count = ->
return unless info_message
_, _, count = info_message\find '(%d+) match'
tonumber count
before_each ->
preview_buffer = nil
editor = {
preview: spy.new (b) => preview_buffer = b
cancel_preview: spy.new =>
line_at_top: 1
line_at_bottom: 1
}
command_line =
add_widget: spy.new (name, w) => list_widget = w if name == 'matches'
notification: NotificationWidget!
finish: spy.new (r) => finish_result = r
info_message = '<not-set>'
error_message = '<not-set>'
command_line.notification.error = spy.new (self, msg) -> error_message = msg
command_line.notification.info = spy.new (self, msg) -> info_message = msg
command_line.notification.clear = spy.new (self, msg) ->
info_message = ''
error_message = ''
buffer = howl.Buffer!
editor.buffer = buffer
search = spy.new (query) ->
-- an iterator that returns buffer chunks from ufind
return if query.is_empty
start = 1
find_iter_count = 0
text = buffer.text
->
start_pos, end_pos = text\ufind query, start, true
return unless start_pos
start = end_pos + 1
find_iter_count += 1
buffer\chunk start_pos, end_pos
context 'on initialization', ->
it 'calls add_widget on the passed command line, adding a list widget', ->
search_view = SearchView
editor: editor
buffer: buffer
:search
search_view\init command_line, max_height: 100
assert.spy(command_line.add_widget).was_called 1
assert.same "ListWidget", typeof(list_widget)
it 'displays the specified prompt and title', ->
search_view = SearchView
editor: editor
buffer: buffer
:search
prompt: 'hello>'
title: '#hello'
search_view\init command_line, max_height: 100
assert.same 'hello>', command_line.prompt
assert.same '#hello', command_line.title
it 'displays no info message', ->
buffer.text = 'content'
search_view = SearchView
editor: editor
buffer: buffer
:search
search_view\init command_line, max_height: 100
set_text search_view, ''
assert.is_nil found_count!
it 'displays all lines of buffer', ->
buffer.text = 'hello1\nhello2\nhello3'
search_view = SearchView
editor: editor
buffer: buffer
:search
search_view\init command_line, max_height: 100
set_text search_view, ''
items = list_widget_items!
assert.same {'hello1', 'hello2', 'hello3'}, [item[2].text for item in *items]
assert.same {}, [item.item_highlights for item in *items]
it 'does not call search for empty query', ->
search = spy.new ->
search_view = SearchView
editor: editor
buffer: buffer
:search
search_view\init command_line, max_height: 100
set_text search_view, ''
assert.spy(search).was_not_called!
context 'searching', ->
it 'calls search(query) iterator when text is updated', ->
buffer.text = 'buffer-content'
search_view = SearchView
:editor
:buffer
:search
search_view\init command_line, max_height: 100
set_text search_view, 'query-target'
assert.spy(search).was_called_with 'query-target'
context 'when query text is set', ->
before_each ->
buffer.text = 'cöntent-line1\ncöntent-line12\ncontent-line3'
search_view = SearchView
:editor
:buffer
:search
search_view\init command_line, max_height: 100
it 'iterates over search(query)', ->
set_text search_view, 'line1'
assert.spy(search).was_called 1
assert.spy(search).was_called_with 'line1'
assert.same 2, find_iter_count
it 'displays the matching lines, at most one match per line', ->
set_text search_view, 'line1'
items = list_widget_items!
assert.same {1, 2}, [item[1] for item in *items]
assert.same {'cöntent-line1', 'cöntent-line12'}, [item[2].text for item in *items]
set_text search_view, 'line3'
items = list_widget_items!
assert.same {3}, [item[1] for item in *items]
assert.same {'content-line3'}, [item[2].text for item in *items]
it 'displays an info message with match count', ->
set_text search_view, 'line1'
assert.same 2, found_count!
set_text search_view, 'line12'
assert.same 1, found_count!
set_text search_view, 'line-'
assert.same 0, found_count!
it 'resets info message when query text is cleared', ->
set_text search_view, 'line1'
assert.same 2, found_count!
set_text search_view, ''
assert.is_nil found_count!
it 'does not shrink diplayed list widget size', ->
set_text search_view, 'li'
height = list_widget_height!
set_text search_view, 'line1'
assert.same height, list_widget_height!
context 'selected line', ->
it 'is centered', ->
set_text search_view, 'line1'
assert.same 1, editor.line_at_center
it 'is changed by keypresses', ->
set_text search_view, 'line1'
keypress_binding_for 'cursor-down'
assert.same 2, editor.line_at_center
keypress_binding_for 'cursor-up'
assert.same 1, editor.line_at_center
it 'returns selected match on pressing enter', ->
set_text search_view, 'line1'
assert.spy(command_line.finish).was_not_called!
keypress_binding_for 'cursor-down'
keypress 'enter'
assert.spy(command_line.finish).was_called 1
assert.same 23, finish_result.chunk.start_pos
assert.same 27, finish_result.chunk.end_pos
it 'displays error message on pressing enter when no selection', ->
set_text search_view, 'xxxxxxxxxxxxx'
keypress 'enter'
assert.spy(command_line.finish).was_not_called!
assert.spy(command_line.notification.error).was_called 1
assert.same error_message, 'No selection'
context 'when search raises an error', ->
before_each ->
search_view = SearchView
:editor
:buffer
search: -> error 'search-error', 0
search_view\init command_line, max_height: 100
it 'displays the error message', ->
set_text search_view, 'query'
assert.same 'search-error', error_message
context 'when limit is set', ->
before_each ->
buffer.text = 'a a a a a a a a'
search_view = SearchView
:editor
:buffer
:search
limit: 3
search_view\init command_line, max_height: 100
it 'does not iterate once limit matches are found', ->
set_text search_view, 'a'
assert.same 3, find_iter_count
context 'replacing', ->
local replace
before_each ->
replace = spy.new (_, _, _, replacement)-> replacement
search = spy.new (query) ->
return if query.is_empty
start = 1
find_iter_count = 0
text = buffer.text
->
start_pos, end_pos = text\ufind query, start, true
return unless start_pos
start = end_pos + 1
find_iter_count += 1
buffer\chunk(start_pos, end_pos), 'match-info'
it 'parses query and calls search(query) with the search part', ->
buffer.text = 'buffer-content'
search_view = SearchView
:editor
:buffer
:search
:replace
search_view\init command_line, max_height: 100
set_text search_view, '/search'
assert.spy(search).was_called_with 'search'
it 'displays all matches', ->
buffer.text = 'cöntent-line1\ncöntent-line2\n'
search_view = SearchView
:editor
:buffer
:search
:replace
search_view\init command_line, max_height: 100
set_text search_view, '/t'
assert.same {'cöntent-line1', 'cöntent-line1', 'cöntent-line2', 'cöntent-line2'}, [item[2].text for item in *list_widget_items!]
context 'when the query includes a replacement', ->
before_each ->
buffer.text = 'content-line1\ncontent-line2\n'
search_view = SearchView
:editor
:buffer
:search
:replace
search_view\init command_line, max_height: 100
it 'calls replace for each match', ->
set_text search_view, '/content/<new>'
assert.spy(replace).was_called 2
assert.spy(replace).was_called_with match._, 'match-info', match._, '<new>'
it 'displays a preview with replacements applied', ->
editor.line_at_top = 1
editor.line_at_bottom = 2
set_text search_view, '/line/<new>'
assert.spy(editor.preview).was_called 1
assert.same 'content-<new>1\ncontent-<new>2\n', preview_buffer.text
assert.same {'search'}, howl.ui.highlight.at_pos preview_buffer, 9
it 'returns text with replacements applied as previewed', ->
set_text search_view, '/line/<new>'
text = preview_buffer.text
keypress 'enter'
assert.same text, finish_result.replacement_text
assert.same 2, finish_result.replacement_count
context 'if no replacement text', ->
it 'previews deletions using strikeout style', ->
editor.line_at_top = 1
editor.line_at_bottom = 2
set_text search_view, '/line/'
text = preview_buffer.text
assert.same buffer.text, text
assert.same {'replace_strikeout', 'search'}, howl.ui.highlight.at_pos preview_buffer, 9
assert.same {'replace_strikeout', 'search'}, howl.ui.highlight.at_pos preview_buffer, 10
it 'returns text with deletions applied', ->
set_text search_view, '/line/'
keypress 'enter'
assert.same 'content-1\ncontent-2\n', finish_result.replacement_text
context 'if no trailing delimiter', ->
it 'previews existing buffer', ->
set_text search_view, '/line'
assert.equal preview_buffer, buffer
it 'returns nil', ->
set_text search_view, '/line'
keypress 'enter'
assert.is_nil finish_result
| 34.219219 | 147 | 0.636858 |
3809120c34af66cae548b2129e7e51c408771940 | 226 | export modinfo = {
type: "command"
desc: "List commands"
alias: {"cmds"}
func: (Msg,Speaker) ->
for name, v in pairs(ConfigSystem("Get", "Commands"))
Output(string.format("%s : %s",name, v.Command), {Colors.Orange})
} | 28.25 | 68 | 0.641593 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.