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
|
---|---|---|---|---|---|
434542c7ac0e46d6222fb5a08014375f5931dc71 | 1,145 | package.path = "?.lua;?/init.lua;" .. package.path
import resume, yield, yieldto, bypass from require "lift"
describe 'lift', ->
before_each ->
export co = coroutine.create ->
yield("foo", "bar")
it 'passes a nil target when yielding', ->
ok, target, a, b = coroutine.resume(co)
assert.is.nil target
assert.equal a, "foo"
assert.equal b, "bar"
it 'hides the target parameter when resuming', ->
ok, a, b = resume(co)
assert.equal a, "foo"
assert.equal b, "bar"
it 'lifts values through when yielding to target', ->
top = coroutine.running()
outer = coroutine.create ->
inner = coroutine.create ->
yield("foo", "bar")
yieldto(top, "FOO", "BAR")
yield select 2, resume inner
resume inner
ok, a, b = resume outer
assert.equal a, "foo"
assert.equal b, "bar"
ok, a, b = resume outer
assert.equal a, "FOO"
assert.equal b, "BAR"
it 'allows bypassing to normal coroutine.resume call', ->
outer = coroutine.create ->
inner = coroutine.create ->
bypass("foo", "bar")
resume inner
ok, a, b = coroutine.resume outer
assert.true ok
assert.equal "foo", a
assert.equal "foo", a
| 26.022727 | 58 | 0.646288 |
f7b0e7a0c2cda4dd408433940da1b15be1c579e2 | 710 | describe "transform.append", ->
run = require("shipwright.builder").run
append = require("shipwright.transform.append")
it "appends one value", ->
value = run({1, 2,},
{append, 3})
assert.equals(1, value[1])
assert.equals(2, value[2])
assert.equals(3, value[3])
it "appends one value in table", ->
value = run({1, 2,},
{append, {3}})
assert.equals(1, value[1])
assert.equals(2, value[2])
assert.equals(3, value[3])
it "appends all values", ->
value = run({1, 2},
{append, {3,4,5}})
assert.equals(1, value[1])
assert.equals(2, value[2])
assert.equals(3, value[3])
assert.equals(4, value[4])
assert.equals(5, value[5])
| 26.296296 | 49 | 0.580282 |
457cf3f31a7e81fb06e744223225522384177b55 | 4,461 | local *
_VERSION = "1.0"
_DESCRIPTION = "LMines – Lua-implemented Mines"
_AUTHOR = "ℜodrigo Arĥimedeς ℳontegasppa ℭacilhας <[email protected]>"
_URL = "https://github.com/cacilhas/LMines"
_LICENSE = "BSD 3-Clause License"
import floor, random, randomseed from math
Cell = assert require "cell"
DCoords = assert require "dcoords"
--------------------------------------------------------------------------------
around = {
DCoords -1, -1
DCoords 0, -1
DCoords 1, -1
DCoords -1, 0
DCoords 1, 0
DCoords -1, 1
DCoords 0, 1
DCoords 1, 1
}
--------------------------------------------------------------------------------
class Board
gameover: false
new: (width=16, height=16, bombs=40) =>
error "invalid parameters" if bombs >= width * height
@width, @height, @bombs = width, height, bombs
@board = [Cell! for _ = 1, width * height]
for _ = 1, bombs
done = false
while not done
x, y = (random width), (random height)
cell = @\get x, y
if cell and cell.value != -1
done = true
cell.value = -1
for t in *around
cell = @\get x + t.dx, y + t.dy
cell.value += 1 if cell and cell.value != -1
get: (x, y) => @board[(y-1) * @width + x] if 1 <= x and x <= @width
toggleflag: (x, y) =>
unless @gameover
@started = love.timer.getTime! unless @started
if cell = @\get x, y
if cell.open
false
else
cell.flag = not cell.flag
cell
open: (x, y) =>
unless @gameover
@started = love.timer.getTime! unless @started
if cell = @\get x, y
if cell.open or cell.flag
false
else
if cell.value == -1 -- bomb
cell.open = true
@gameover = true
@win = false
@stopped = @\gettime!
else
@\_keepopening x, y
@\_checkgameover!
cell
_keepopening: (x, y) =>
cell = @\get x, y
if cell and not cell.open
cell.open = true
if cell.value == 0
@\_keepopening x + t.dx, y + t.dy for t in *around
_checkgameover: =>
count = @bombs
for cell in *@board
count += 1 if cell.open and cell.value != -1
if count == @width * @height
@gameover = true
@win = true
@stopped = @\gettime!
gettime: =>
if @stopped
@stopped
elseif @started
t = love.timer.getTime! - @started
"%02d:%02d"\format (floor t / 60), (floor t % 60)
else
"00:00"
draw: (xoffset, yoffset, objects, tiles, font, fontcolors) =>
for y = 1, @height
for x = 1, @width
lx = (x - 1) * 48 + xoffset
ly = (y - 1) * 48 + yoffset
cell = @\get x, y
tile = if cell.open and cell.value == -1
tiles.red
elseif cell.open
tiles.open
else
tiles.closed
love.graphics.draw tile.img, tile.quad, lx, ly
object = if @gameover
if cell.open
objects.mine if cell.value == -1
elseif cell.value == -1
if @win or cell.flag then objects.flag else objects.mine
elseif cell.flag
objects.xflag
elseif cell.flag
objects.flag
with love.graphics
if object
.draw object.img, object.quad, lx, ly
elseif cell.open and cell.value > 0
.setFont font
.setColor (fontcolors cell.value)\explode!
.print "#{cell.value}", lx+4, ly+4
.reset!
--------------------------------------------------------------------------------
{
:_VERSION
:_DESCRIPTION
:_AUTHOR
:_URL
:_LICENSE
newboard: Board
}
| 29.74 | 80 | 0.416274 |
ba1d34cfb6971f25a18380cbf1d6747203682323 | 27,012 | import TABLE from require "ZF.util.table"
import UTIL from require "ZF.util.util"
class TAGS
version: "2.0.0"
new: (getValues) => @getPatternsTags getValues
-- gets captures for all types of tag values
-- @param getValues boolean
-- @return table
patterns: (getValues) =>
@ptt = {
font: getValues and "%s*([^\\}]*)" or "%s*[^\\}]*"
int: getValues and "%s*(%d+)" or "%s*%d+"
dec: getValues and "%s*(%d[%.%d]*)" or "%s*%d[%.%d]*"
float: getValues and "%s*(%-?%d[%.%d]*)" or "%s*%-?%d[%.%d]*"
hex: getValues and "%s*(&?[Hh]%x+&?)" or "%s*&?[Hh]%x+&?"
bool: getValues and "%s*([0-1])" or "%s*[0-1]"
tag: getValues and "%{(.-)%}" or "%b{}"
prt: getValues and "%((.-)%)" or "%b()"
pmt: getValues and "%((.+)%)" or "%b()"
brk: getValues and "%[(.-)%]" or "%b[]"
oun: getValues and "%s*([1-9])" or "%s*[1-9]" -- one until nine
zut: getValues and "%s*([0-3])" or "%s*[0-3]" -- zero until three
shp: "m%s+%-?%d[%.%-%d mlb]*"
}
return @ptt
-- sets a table containing all tags and their set captures
-- @param getValues boolean
-- @return table
getPatternsTags: (getValues) =>
{:font, :int, :dec, :float, :hex, :prt, :pmt, :oun, :zut, :shp} = @patterns getValues
@all = {
fn: {pattern: "\\fn#{font}", type: "font"}
fs: {pattern: "\\fs#{float}", type: "dec"}
fsp: {pattern: "\\fsp#{float}", type: "float"}
["1c"]: {pattern: "\\1?c#{hex}", type: "hex"}
["2c"]: {pattern: "\\2c#{hex}", type: "hex"}
["3c"]: {pattern: "\\3c#{hex}", type: "hex"}
["4c"]: {pattern: "\\4c#{hex}", type: "hex"}
alpha: {pattern: "\\alpha#{hex}", type: "hex"}
["1a"]: {pattern: "\\1a#{hex}", type: "hex"}
["2a"]: {pattern: "\\2a#{hex}", type: "hex"}
["3a"]: {pattern: "\\3a#{hex}", type: "hex"}
["4a"]: {pattern: "\\4a#{hex}", type: "hex"}
pos: {pattern: "\\pos#{prt}", type: "prt"}
move: {pattern: "\\move#{prt}", type: "prt"}
org: {pattern: "\\org#{prt}", type: "prt"}
clip: {pattern: "\\clip#{prt}", type: "prt", pattern_alt: "\\clip#{shp}", type_alt: "shp"}
iclip: {pattern: "\\iclip#{prt}", type: "prt", pattern_alt: "\\iclip#{shp}", type_alt: "shp"}
fad: {pattern: "\\fad#{prt}", type: "prt"}
fade: {pattern: "\\fade#{prt}", type: "prt"}
t: {pattern: "\\t#{pmt}", type: "pmt"}
fscx: {pattern: "\\fscx#{dec}", type: "dec"}
fscy: {pattern: "\\fscy#{dec}", type: "dec"}
frx: {pattern: "\\frx#{float}", type: "float"}
fry: {pattern: "\\fry#{float}", type: "float"}
frz: {pattern: "\\frz?#{float}", type: "float"}
fax: {pattern: "\\fax#{float}", type: "float"}
fay: {pattern: "\\fay#{float}", type: "float"}
be: {pattern: "\\be#{dec}", type: "dec"}
blur: {pattern: "\\blur#{dec}", type: "dec"}
bord: {pattern: "\\bord#{dec}", type: "dec"}
xbord: {pattern: "\\xbord#{float}", type: "float"}
ybord: {pattern: "\\ybord#{float}", type: "float"}
shad: {pattern: "\\shad#{dec}", type: "dec"}
xshad: {pattern: "\\xshad#{float}", type: "float"}
yshad: {pattern: "\\yshad#{float}", type: "float"}
an: {pattern: "\\an#{oun}", type: "oun"}
b: {pattern: "\\b#{bool}", type: "bool"}
i: {pattern: "\\i#{bool}", type: "bool"}
s: {pattern: "\\s#{bool}", type: "bool"}
u: {pattern: "\\u#{bool}", type: "bool"}
k: {pattern: "\\[kK]^*[fo ]*#{int}", type: "int"}
q: {pattern: "\\q#{zut}", type: "zut"}
p: {pattern: "\\p#{int}", type: "int"}
}
-- tag name for the style
@styleTags = {
fn: "fontname"
fs: "fontsize"
fsp: "spacing"
fscx: "scale_x"
fscy: "scale_y"
frz: "angle"
bord: "outline"
shad: "shadow"
alpha: "alpha"
["1a"]: "alpha1"
["2a"]: "alpha2"
["3a"]: "alpha3"
["4a"]: "alpha4"
["1c"]: "color1"
["2c"]: "color2"
["3c"]: "color3"
["4c"]: "color4"
b: "bold"
i: "italic"
u: "underline"
s: "strikeout"
}
-- tags that appear only once
@once = {"an", "org", "pos", "move"}
return @all
-- removes the tag barces
-- @param text string
-- @return string
remBarces: (text) => if text\match("%b{}") then text\gsub(@patterns(true)["tag"], "%1") else text
-- adds the tag barces
-- @param value string
-- @return string
addBarces: (value) => if value\match("%b{}") then value else "{#{value}}"
-- hides all transformations
-- @param value string
-- @return string
hidetr: (value) => value\gsub "\\t%b()", (v) -> v\gsub "\\", "\\@"
-- unhides all transformations
-- @param value string
-- @return string
unhidetr: (value) => value\gsub "\\@", "\\"
-- moves transformations in transformations out
-- @param value string
-- @return string
fixtr: (value) =>
fix = (val) ->
new = ""
while val
new ..= "\\t(#{val\gsub "\\t%b()", ""})"
val = val\match "\\t%((.+)%)%}?"
return new
return value\gsub "\\t(%b())", (tr) -> fix tr\match "%((.+)%)"
-- gets the text non tags
-- @param value string
-- @return string
getRawText: (value) =>
rawTag = value\match("%b{}") or "{}"
rawTxt = value\gsub "%b{}", ""
return rawTag, rawTxt
-- gets the values in brackets
-- @param value string
-- @param tag string
-- @return number
inBrackets: (value, tag) =>
arguments = {}
value\gsub("%s+", "")\gsub("\\#{tag}%((.-)%)", "%1")\gsub "[^,]*", (i) ->
TABLE(arguments)\push tonumber i
return #arguments == 0 and value or arguments
-- gets the last value that can be found in a capture
-- @param value string
-- @param pattern string
-- @return string
getLastTag: (value, pattern = "", last) =>
for val in value\gmatch pattern
last = val
return last
-- gets all the tag layers contained in the text
-- @param value string
-- @return table
getTagLayers: (value) => [t for t in value\gmatch "%b{}"]
-- adds a tag to the end of a tag layer
-- @param value string
-- @param tag string
-- @param addBarces boolean
-- @return string
insertTag: (value, tag, addBarces = true) =>
result = @remBarces(value) .. tag
return not addBarces and result or @addBarces result
-- adds one or more tags to the end of a tag layer
-- @param value string
-- @return string
insertTags: (value, ...) =>
for tag in *{...}
value = @insertTag value, tag, false
return @splitTags(value).__tostring!
-- removes a tag from a tag layer
-- @param value string
-- @param delete string
-- @param replace string
-- @return string
removeTag: (value, delete, replace = "", n) =>
@getPatternsTags!
return value\gsub @all[delete]["pattern"], replace, n
-- removes one or more tags from a tag layer
-- @param value string
-- @param ... table
-- @return string
removeTags: (value, ...) =>
for v in *{...}
value = type(v) == "string" and @removeTag(value, v) or @removeTag value, v[1], v[2], v[3]
return value
-- checks if dependent tags are contained within the tags layer
-- @param value string
-- @return nil
dependency: (value, ...) =>
@getPatternsTags!
for val in *{...}
assert value\match(@all[val]["pattern"]), "#{val} not found"
-- finds a tag within the text and returns its value
-- @param value string
-- @param tag string
-- @param typ string
-- @param getValues boolean
-- @return string || number || boolean
getTagInTags: (value, tagName) =>
@getPatternsTags true
if tagName == "clip" or tagName == "iclip"
result = @hidetr value
if a = @getLastTag result, @all[tagName]["pattern"]
return @inBrackets a, tagName
elseif b = @getLastTag result, @all[tagName]["pattern_alt"]
return b
else
if result = @getLastTag @hidetr(value), @all[tagName]["pattern"]
switch @all[tagName]["type"]
when "float", "int", "dec", "oun", "zut" then tonumber result
when "bool" then result == "1"
when "prt" then @inBrackets result, tagName
else result
-- removes the spaces at the beginning or end of the text
-- @param text string
-- @param where string
-- @return string
blankText: (text, where = "both") =>
switch where
when "both" then text\match "^%s*(.-)%s*$"
when "start" then text\match "^%s*(.-%s*)$"
when "end" then text\match "^(%s*.-)%s*$"
when "spaceL" then text\match "^(%s*).-%s*$"
when "spaceR" then text\match "^%s*.-(%s*)$"
when "spaces" then text\match "^(%s*).-(%s*)$"
-- adds the first category tags to the first tag layer and removes them if they are found in other layers
-- @param text string
-- @return string
firstCategory: (text) =>
@getPatternsTags!
firstCategory = (txt, pattern) ->
i = 1
for t in txt\gmatch "%b{}"
if match = t\match pattern
if i > 1
txt = txt\gsub(pattern, "")\gsub "{(.-)}", "{%1#{match}}", 1
else
j = 1
txt = txt\gsub pattern, (p) ->
if j > 1
return ""
j += 1
return p
break
i += 1
return txt
for name in *@once
text = firstCategory text, @all[name]["pattern"]
return text
-- readjusts the style values using values set on the line
-- @param subs userdata
-- @param line table
-- @return table, table, table
toStyle: (subs, line) =>
meta, style = karaskel.collect_head subs
-- copies the old style and adds the alpha values into it
old_style = TABLE(style)\copy!
for i = 1, old_style.n
with old_style[i]
.alpha = "&H00&"
.alpha1 = alpha_from_style .color1
.alpha2 = alpha_from_style .color2
.alpha3 = alpha_from_style .color3
.alpha4 = alpha_from_style .color4
.color1 = color_from_style .color1
.color2 = color_from_style .color2
.color3 = color_from_style .color3
.color4 = color_from_style .color4
-- defines the new values for the style
for i = 1, style.n
with style[i]
{:margin_l, :margin_r, :margin_t, :margin_b, :text} = line
.margin_l = margin_l if margin_l > 0
.margin_r = margin_r if margin_r > 0
.margin_v = margin_t if margin_t > 0
.margin_v = margin_b if margin_b > 0
if rawTag = @hidetr @getRawText text
.align = @getTagInTags(rawTag, "an") or .align
.fontname = @getTagInTags(rawTag, "fn") or .fontname
-- fixes problem with fontsize being 0 or smaller than 0
if fontsize = @getTagInTags(rawTag, "fs")
.fontsize = fontsize <= 0 and .fontsize or fontsize
.scale_x = @getTagInTags(rawTag, "fscx") or .scale_x
.scale_y = @getTagInTags(rawTag, "fscy") or .scale_y
.spacing = @getTagInTags(rawTag, "fsp") or .spacing
.outline = @getTagInTags(rawTag, "bord") or .outline
.shadow = @getTagInTags(rawTag, "shad") or .shadow
.angle = @getTagInTags(rawTag, "frz") or .angle
.alpha = @getTagInTags(rawTag, "alpha") or "&H00&"
.alpha1 = @getTagInTags(rawTag, "1a") or alpha_from_style .color1
.alpha2 = @getTagInTags(rawTag, "2a") or alpha_from_style .color2
.alpha3 = @getTagInTags(rawTag, "3a") or alpha_from_style .color3
.alpha4 = @getTagInTags(rawTag, "4a") or alpha_from_style .color4
.color1 = @getTagInTags(rawTag, "1c") or color_from_style .color1
.color2 = @getTagInTags(rawTag, "2c") or color_from_style .color2
.color3 = @getTagInTags(rawTag, "3c") or color_from_style .color3
.color4 = @getTagInTags(rawTag, "4c") or color_from_style .color4
.bold = @getTagInTags(rawTag, "b") or .bold
.italic = @getTagInTags(rawTag, "i") or .italic
.underline = @getTagInTags(rawTag, "u") or .underline
.strikeout = @getTagInTags(rawTag, "s") or .strikeout
return meta, style, old_style
-- find coordinates
-- @param line table
-- @param meta table
-- @param ogp boolean
-- @return table
findCoords: (line, meta) =>
line.text = @firstCategory line.text
with {pos: {}, move: {}, org: {}, fax: 0, fay: 0, frx: 0, fry: 0, p: "text"}
if meta
{:res_x, :res_y} = meta
{:align, :margin_l, :margin_r, :margin_v} = line.styleref
x = switch align
when 1, 4, 7 then margin_l
when 2, 5, 8 then (res_x - margin_r + margin_l) / 2
when 3, 6, 9 then res_x - margin_r
y = switch align
when 1, 2, 3 then res_y - margin_v
when 4, 5, 6 then res_y / 2
when 7, 8, 9 then margin_v
.pos, .org = {x, y}, {x, y}
if rawTag = @hidetr @getRawText line.text
.p = @getTagInTags(rawTag, "p") or .p
-- gets values from the perspective
.frx = @getTagInTags(rawTag, "frx") or 0
.fry = @getTagInTags(rawTag, "fry") or 0
.fax = @getTagInTags(rawTag, "fax") or 0
.fay = @getTagInTags(rawTag, "fay") or 0
-- gets \pos or \move
if mPos = @getTagInTags rawTag, "pos", false
.pos = mPos
elseif mMov = @getTagInTags rawTag, "move", false
.move = mMov
.pos = {mMov[1], mMov[2]}
-- gets \org
if mOrg = @getTagInTags rawTag, "org", false
.org = mOrg
else
.org = {.pos[1], .pos[2]}
-- finds all tags within the tag set and adds them to a table
-- @param value string
-- @return table
splitTags: (value = "") =>
-- delete empty tags
for name in *{"t", "pos", "org", "move", "fad", "fade", "i?clip"}
value = value\gsub "\\#{name}%(%s*%)", ""
-- fixes the problem of different tags having the same meaning
value = value\gsub("\\c(#{@ptt["hex"]})", "\\1c%1")\gsub "\\fr(#{@ptt["float"]})", "\\frz%1"
-- saves the original value for future changes
split, copyValue = {}, value
-- builds the tag
buildTag = (tname, tvalue, notp) ->
build = "\\" .. tname
if type(tvalue) == "table"
concat = ""
for key, val in ipairs tvalue
concat ..= val .. (key == #tvalue and "" or ",")
build ..= "(#{concat})"
elseif UTIL\isShape tvalue
build ..= notp and "#{tvalue}" or "(#{tvalue})"
else
build ..= type(tvalue) == "boolean" and (tvalue and "1" or "0") or tvalue
return build, value\find build, 1, true
-- builds the tags
split.builder = ->
add = {}
for key, val in ipairs split
{name: a, value: b} = val
if type(b) == "table" and b.builder
with val
ts = .ts and .ts .. "," or ""
te = .te and .te .. "," or ""
ac = .ac and .ac .. "," or ""
result = "\\t(#{ts .. te .. ac}#{b.builder!})"
TABLE(add)\push result
else
result = buildTag a, b
TABLE(add)\push result
return table.concat add
-- builds the tags permanently
split.__tostring = -> @addBarces split.builder!
for tagName in pairs @all
if tagValue = @getTagInTags value, tagName
build, i, j = buildTag tagName, tagValue
TABLE(split)\push {value: tagValue, name: tagName, :build, :i, :j}
elseif copyValue\match "\\t%b()"
ts, te, ac, transform, tf = 0, 0, 1, "", ""
fn = (t) ->
if tf = t\match "%(.+%)"
ts, te, ac, transform = tf\match "%(([%.%d]*)%,?([%.%d]*)%,?([%.%d]*)%,?(.+)%)"
ts = tonumber ts
te = tonumber te
ac = tonumber ac
return ""
while copyValue\match "\\t%b()"
copyValue = copyValue\gsub "\\t%b()", fn, 1
build, i, j = buildTag "t", tf, true
TABLE(split)\push {value: @splitTags(transform), name: "t", :build, :ts, :te, :ac, :i, :j}
-- sorts the table with the tag values at the position relative to the original line
table.sort split, (a, b) -> a.i < b.i
return split
-- checks if a tag contains in another tag layer
-- @param tags table || string
-- @return table || boolean
tagsContainsTag: (tags, tagName) =>
tags = type(tags) == "table" and tags or @splitTags tags
for t, tag in ipairs tags
if tag.name == tagName
return tag
return false
-- adds the tags contained in the style to the current tags
-- @param line table
-- @param tags string
-- @param pos table
-- @return string
addStyleTags: (line, tags, pos) =>
tags = @remBarces tags
for name, style_name in pairs @styleTags
unless @tagsContainsTag tags, name
style_value = line.styleref_old[style_name]
style_value = style_value == true and "1" or style_value == false and "0" or style_value
tags = "\\" .. name .. style_value .. tags
return not pos and @addBarces(tags) or @replaceCoords tags, pos
-- splits text by tag layers
-- @param text string
-- @param addPendingTags boolean
-- @param skipOnceBool boolean
-- @return table
splitTextByTags: (text, addPendingTags = true, skipOnceBool = false) =>
text = @firstCategory text
-- adds pending values in other tag layers
addPending = (tags) ->
skipOnce = (name) ->
for sk in *@once
if name == sk
return true
return false
-- scans between all tag layers to eliminate repeated tags
for i = 1, #tags
tags[i] = @splitTags(tags[i]).__tostring!
-- adds pending values
for i = 2, #tags
splitPrev = @splitTags tags[i - 1]
for j = #splitPrev, 1, -1
with splitPrev[j]
if .name == "t" or not @tagsContainsTag tags[i], .name
unless skipOnceBool and skipOnce .name
tags[i] = @addBarces .build .. @remBarces tags[i]
return tags
-- adds an empty tag to the beginning of the text if there is no tag at the beginning
text = @blankText text, "both"
hast = text\gsub("%s+", "")\find "%b{}"
text = hast != 1 and "{}#{text}" or text
-- table that will index the text and tag values
split = {tags: {}, text: {}}
-- turn the table back to text
split.__tostring = ->
concat = ""
for i = 1, #split.tags
concat ..= split.tags[i] .. split.text[i]
return concat
with split
.tags = @getTagLayers text
if addPendingTags
.tags = addPending .tags
.text = UTIL\headTails text, "%b{}"
if #.text > 1 and .text[1] == ""
TABLE(.text)\shift!
-- if the last tag contains no text, add some accompanying text
if #.tags - #.text == 1
TABLE(.text)\push ""
-- removes the line start and end spacing
.text[1] = @blankText .text[1], "start" if .text[1]
.text[#.text] = @blankText .text[#.text], "end" if #.text > 1
-- splits the text by line breaks
-- @param value string
-- @return table
splitTextByBreaks: (value) =>
split = UTIL\headTails value, "\\N"
if #split >= 1
split[1] = @splitTextByTags(split[1]).__tostring!
for i = 2, #split
result = @getLastTag(split[i - 1], "%b{}") .. split[i]
result = result\gsub "}%s*{", ""
split[i] = @splitTextByTags(result).__tostring!
else
split[1] = "{}"
return split
-- replaces values relative to coordinate tags
-- @param value string
-- @param posVals table
-- @param orgVals table
-- @return string
replaceCoords: (value, posVals, orgVals) =>
value = @remBarces value
hasMove = value\match "\\move%b()"
if hasMove and #posVals >= 4
times = posVals[5] and ",#{posVals[5]}" or ""
times ..= posVals[6] and ",#{posVals[6]}" or ""
pos = "\\move(#{posVals[1]},#{posVals[2]},#{posVals[3]},#{posVals[4]}#{times})"
value = value\gsub "\\move%b()", pos, 1
elseif not hasMove and #posVals == 2
pos = "\\pos(#{posVals[1]},#{posVals[2]})"
hasPos = value\match "\\pos%b()"
value = not hasPos and pos .. value or value\gsub "\\pos%b()", pos, 1
if orgVals
org = #orgVals > 0 and "\\org(#{orgVals[1]},#{orgVals[2]})" or ""
hasOrg = value\match "\\org%b()"
value = not hasOrg and org .. value or value\gsub "\\org%b()", org, 1
return @addBarces value
-- remove equal tags in tag layers
-- @param text string
-- @return string
clearEqualTags: (text) =>
split = @splitTextByTags text, false
for i = 2, #split.tags
prevTag = @splitTags split.tags[i - 1]
currTag = @splitTags split.tags[i]
tagsToRemove = {}
for j = 1, #prevTag
{name: prev_name, build: prev_build} = prevTag[j]
if tag = @tagsContainsTag currTag, prev_name
if prev_build == tag.build
TABLE(tagsToRemove)\push prev_name
split.tags[i] = @clearByPreset split.tags[i], tagsToRemove
return split.__tostring!\gsub "{%s*}", ""
-- removes tags from the line if they match the values defined in the style
-- @param line table
-- @param tags string
-- @return string
clearStyleValues: (line, tags, setToOld) =>
i, split = 1, @splitTags tags
{:styleTags} = @
while i <= #split
{name: sn, value: sv} = split[i]
if styleTags[sn] and sv == line.styleref_old[styleTags[sn]]
table.remove split, i
i -= 1
-- sets the current value to the old value
if setToOld
if val = line.styleref_old[styleTags[sn]]
line.styleref_old[styleTags[sn]] = val != sv and sv or val
i += 1
return split.__tostring!
-- clears the tags from a preset
-- @param tags string
-- @param presetValue string
-- @return string
clearByPreset: (tags, presetValue = "To Text") =>
-- checks if a tag contains in another tag layer
tagsContainsTag = (t, name) ->
for v in *t
if (type(v) == "table" and v[1] or v) == name
return v
return false
-- function default presets
presets = {
["To Text"]: {"fs", "fscx", "fscy", "fsp", "fn", "b", "i", "u", "s"}
["Clip To Shape"]: {"clip", "iclip", "fax", "fay", "frx", "fry", "frz", "org"}
["Shape Expand"]: {"an", "fscx", "fscy", "fax", "fay", "frx", "fry", "frz", "org"}
}
i, split = 1, @splitTags tags
if preset = type(presetValue) == "table" and presetValue or presets[presetValue]
if #preset >= 1
while i <= #split
{name: sn, value: sv} = split[i]
if tag = tagsContainsTag preset, sn
-- if there is a value to replace, replace it, else, remove the tag
if tag[2]
split[i].value = tag[2]
else
table.remove split, i
i -= 1
i += 1
return split.__tostring!
-- clears the unnecessary tags and replaces set tags
-- @param line table
-- @param tags string
-- @param preset string || table
-- @return string
clear: (line, tags, preset) => @clearStyleValues line, @clearByPreset tags, preset
{:TAGS} | 43.15016 | 114 | 0.473604 |
6b9f6214c55f7dedbe6902c0559938020cb4ed4d | 923 | -- Copyright 2017 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
howl.util.lpeg_lexer ->
c = capture
name = (alpha + '_')^1 * (alpha + digit + P'_')^0
keyword = c 'keyword', word {
'cimport', 'cdef', 'cpdef', 'ctypedef', 'struct', 'union', 'include', 'inline', 'public', 'extern'
}
typename = c 'type', word {
'enum',
'char', 'short', 'int', 'long', 'float', 'double', 'bint', 'unsigned'
'object'
}
operator = c 'operator', S'[]*<>'
cython_rules = P {
any(V'cython_fdecl', keyword, typename)
cython_fdecl: sequence {
c('keyword', word {'cdef', 'cpdef'})
sequence({
c('whitespace', space^0)
any(keyword, typename, operator)
})^0
c('whitespace', space^0)
c('fdecl', name)
c('whitespace', space^0)
c('operator', '(')
}
}
compose 'python', cython_rules
| 24.945946 | 104 | 0.562297 |
699d90d661041faf564592098dfdc70aac0b0499 | 1,173 | easing = {}
funcs = {}
defaults = {
quad: "x^2"
cubic: "x^3"
quart: "x^4"
quint: "x^5"
expo: "2^(10 * (x - 1))"
sine: "-math.cos(x * (math.pi * 0.5)) + 1"
circ: "-(math.sqrt(1 - (x^2)) - 1)"
back: "x^2 * (2.7 * x - 1.7)"
elastic: "-(2^(10 * (x - 1)) * math.sin((x - 1.075) * (math.pi * 2) / 0.3))"
}
make_function = (s, e) ->
loadstring "return function(x) " .. (s\gsub "%$e", e) .. " end"
generate_ease = (name, f) ->
funcs[name .. "in"] = make_function "return $e", f
funcs[name .. "out"] = make_function [[
x = 1 - x
return 1 - ($e)
]]
funcs[name .. "in_out"] = make_function([[
x = x * 2
if x < 1 then
return 0.5 * ($e)
else
x = 2 - x
return 0.5 * (1 - ($e)) + 0.5
end
]], f)
easing.get = (name, value) =>
unless funcs[name]
name ..= "in"
assert funcs[name] == nil, "Why would you use a non-existing function?"
funcs[name](value)
easing.add = (name, f) =>
assert funcs[name] ~= nil, "Why would you add an existing function?"
generate_ease name, f
for k, v in pairs defaults
generate_ease k, v
setmetatable easy, {
__call: easing.get
}
easing
| 21.327273 | 78 | 0.513214 |
8e02aae738e2a7ae6c1df1ca77ced11b86eb9596 | 10,230 |
import concat, insert from table
import type, pairs, ipairs, tostring, getmetatable,
setmetatable, table from _G
unpack = unpack or table.unpack
import getfenv, setfenv from require "lapis.util.fenv"
import locked_fn, release_fn from require "lapis.util.functions"
CONTENT_FOR_PREFIX = "_content_for_"
escape_patt = do
punct = "[%^$()%.%[%]*+%-?]"
(str) ->
(str\gsub punct, (p) -> "%"..p)
html_escape_entities = {
['&']: '&'
['<']: '<'
['>']: '>'
['"']: '"'
["'"]: '''
}
html_unescape_entities = {}
for key,value in pairs html_escape_entities
html_unescape_entities[value] = key
html_escape_pattern = "[" .. concat([escape_patt char for char in pairs html_escape_entities]) .. "]"
escape = (text) ->
(text\gsub html_escape_pattern, html_escape_entities)
unescape = (text) ->
(text\gsub "(&[^&]-;)", (enc) ->
decoded = html_unescape_entities[enc]
decoded if decoded else enc)
strip_tags = (html) ->
html\gsub "<[^>]+>", ""
void_tags = {
"area"
"base"
"br"
"col"
"command"
"embed"
"hr"
"img"
"input"
"keygen"
"link"
"meta"
"param"
"source"
"track"
"wbr"
}
for tag in *void_tags
void_tags[tag] = true
------------------
classnames = (t) ->
if type(t) == "string"
return t
ccs = for k,v in pairs t
if type(k) == "number"
continue if v == ""
v
else
continue unless v
k
table.concat ccs, " "
element_attributes = (buffer, t) ->
return unless type(t) == "table"
for k,v in pairs t
if type(k) == "string" and not k\match "^__"
vtype = type(v)
if vtype == "boolean"
if v
buffer\write " ", k
else
if vtype == "table" and k == "class"
v = classnames v
continue if v == ""
else
v = tostring v
buffer\write " ", k, "=", '"', escape(v), '"'
nil
element = (buffer, name, attrs, ...) ->
with buffer
\write "<", name
element_attributes(buffer, attrs)
if void_tags[name]
-- check if it has content
has_content = false
for thing in *{attrs, ...}
t = type thing
switch t
when "string"
has_content = true
break
when "table"
if thing[1]
has_content = true
break
unless has_content
\write "/>"
return buffer
\write ">"
\write_escaped attrs, ...
\write "</", name, ">"
class Buffer
builders: {
html_5: (...) ->
raw '<!DOCTYPE HTML>'
if type((...)) == "table"
html ...
else
html lang: "en", ...
}
new: (@buffer) =>
@old_env = {}
@i = #@buffer
@make_scope!
with_temp: (fn) =>
old_i, old_buffer = @i, @buffer
@i = 0
@buffer = {}
fn!
with @buffer
@i, @buffer = old_i, old_buffer
make_scope: =>
@scope = setmetatable { [Buffer]: true }, {
__index: (scope, name) ->
handler = switch name
when "widget"
@\render_widget
when "render"
@\render
when "capture"
(fn) -> table.concat @with_temp fn
when "element"
(...) -> element @, ...
when "text"
@\write_escaped
when "raw"
@\write
unless handler
default = @old_env[name]
return default unless default == nil
unless handler
builder = @builders[name]
unless builder == nil
handler = (...) -> @call builder, ...
unless handler
handler = (...) -> element @, name, ...
scope[name] = handler
handler
}
render: (mod_name, ...) =>
widget = require mod_name
@render_widget widget ...
render_widget: (w) =>
-- instantiate widget if it's a class
if w.__init and w.__base
w = w!
if current = @widget
w\_inherit_helpers current
w\render @
call: (fn, ...) =>
env = getfenv fn
if env == @scope
return fn!
before = @old_env
@old_env = env
clone = locked_fn fn
setfenv clone, @scope
out = {clone ...}
release_fn clone
@old_env = before
unpack out
write_escaped: (thing, next_thing, ...) =>
switch type thing
when "string"
@write escape thing
when "table"
for chunk in *thing
@write_escaped chunk
else
@write thing
if next_thing -- keep the tail call
@write_escaped next_thing, ...
write: (thing, next_thing, ...) =>
switch type thing
when "string"
@i += 1
@buffer[@i] = thing
when "number"
@write tostring thing
when "nil"
nil -- ignore
when "table"
for chunk in *thing
@write chunk
when "function"
@call thing
else
error "don't know how to handle: " .. type(thing)
if next_thing -- keep tail call
@write next_thing, ...
html_writer = (fn) ->
(buffer) -> Buffer(buffer)\write fn
render_html = (fn) ->
buffer = {}
html_writer(fn) buffer
concat buffer
helper_key = setmetatable {}, __tostring: -> "::helper_key::"
-- ensures that all methods are called in the buffer's scope
class Widget
@__inherited: (cls) =>
cls.__base.__call = (...) => @render ...
-- get the class where mixins can be inserted
-- will inject a class one above the current class in the inheritance
-- hierarchy. If a mixins class has already been injected then it will be returned
-- returns MixinClass, created(boolean)
@get_mixins_class: (model) ->
parent = model.__parent
unless parent
error "model does not have parent class"
-- if class has already been injected, return it
if rawget parent, "_mixins_class"
return parent, false
mixins_class = class extends model.__parent
@__name: "#{model.__name}Mixins"
@_mixins_class: true
model.__parent = mixins_class
setmetatable model.__base, mixins_class.__base
mixins_class, true
@include: (other_cls) =>
other_cls, other_cls_name = if type(other_cls) == "string"
require(other_cls), other_cls
if other_cls == Widget
error "Your widget tried to include a class that extends from Widget. An included class should be a plain class and not another widget"
mixins_class = @get_mixins_class!
-- if there is a parent, do it first
-- note: this will flatten the inheritance chain, so super semantics are lost for mixed in methods!
if other_cls.__parent
@include other_cls.__parent
unless other_cls.__base
error "Expecting a class when trying to include #{other_cls_name or other_cls} into #{@__name}"
-- copy over all instance methods
for k,v in pairs other_cls.__base
continue if k\match("^__")
mixins_class.__base[k] = v
true
new: (opts) =>
-- copy in options
if opts
for k,v in pairs opts
if type(k) == "string"
@[k] = v
_set_helper_chain: (chain) => rawset @, helper_key, chain
_get_helper_chain: => rawget @, helper_key
_find_helper: (name) =>
if chain = @_get_helper_chain!
for h in *chain
helper_val = h[name]
if helper_val != nil
-- call functions in scope of helper
value = if type(helper_val) == "function"
(w, ...) -> helper_val h, ...
else
helper_val
return value
_inherit_helpers: (other) =>
@_parent = other
-- add helpers from parents
if other_helpers = other\_get_helper_chain!
for helper in *other_helpers
@include_helper helper
-- insert table onto end of helper_chain
include_helper: (helper) =>
if helper_chain = @[helper_key]
insert helper_chain, helper
else
@_set_helper_chain { helper }
nil
content_for: (name, val) =>
full_name = CONTENT_FOR_PREFIX .. name
return @_buffer\write @[full_name] unless val
if helper = @_get_helper_chain![1]
layout_opts = helper.layout_opts
val = if type(val) == "string"
escape val
else
getfenv(val).capture val
existing = layout_opts[full_name]
switch type existing
when "nil"
layout_opts[full_name] = val
when "table"
table.insert layout_opts[full_name], val
else
layout_opts[full_name] = {existing, val}
has_content_for: (name) =>
full_name = CONTENT_FOR_PREFIX .. name
not not @[full_name]
content: => -- implement me
render_to_string: (...) =>
buffer = {}
@render buffer, ...
concat buffer
render_to_file: (file, ...) =>
opened_file = false
file = if type(file) == "string"
opened_file = true
assert io.open file, "w"
buffer = setmetatable {}, {
__newindex: (key, val) =>
file\write val
true
}
@render buffer, ...
if opened_file
file\close!
true
render: (buffer, ...) =>
@_buffer = if buffer.__class == Buffer
buffer
else
Buffer buffer
old_widget = @_buffer.widget
@_buffer.widget = @
meta = getmetatable @
index = meta.__index
index_is_fn = type(index) == "function"
seen_helpers = {}
scope = setmetatable {}, {
__tostring: meta.__tostring
__index: (scope, key) ->
value = if index_is_fn
index scope, key
else
index[key]
-- run method in buffer scope
if type(value) == "function"
wrapped = if Widget.__base[key] and key != "content"
value
else
(...) -> @_buffer\call value, ...
scope[key] = wrapped
return wrapped
-- look for helper
if value == nil and not seen_helpers[key]
helper_value = @_find_helper key
seen_helpers[key] = true
if helper_value != nil
scope[key] = helper_value
return helper_value
value
}
setmetatable @, __index: scope
@content ...
setmetatable @, meta
@_buffer.widget = old_widget
nil
{ :Widget, :Buffer, :html_writer, :render_html, :escape, :unescape, :classnames, :element, :CONTENT_FOR_PREFIX }
| 22.733333 | 141 | 0.57087 |
9c8d698130eb91509d2acc239643e3a319eb5179 | 18,155 |
-- 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 hook, DPP2, DLib from _G
import Menus from DPP2
local lastMenu
lastMenuFrame = 0
_entlist = {
DPP2.PhysgunProtection.RestrictionList, DPP2.DriveProtection.RestrictionList, DPP2.PickupProtection.RestrictionList
DPP2.UseProtection.RestrictionList, DPP2.VehicleProtection.RestrictionList, DPP2.GravgunProtection.RestrictionList
DPP2.ToolgunProtection.RestrictionList, DPP2.DamageProtection.RestrictionList, DPP2.SpawnRestrictions
}
addRestrictionMenuOption = (classname, menu) =>
with menu
if @Has(classname)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. @add_command_identifier)
edit = -> @OpenMenu(classname)
\AddOption('gui.dpp2.menu.edit_in_' .. @identifier .. '_restrictions', edit)\SetIcon(Menus.Icons.Edit)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. @remove_command_identifier)
remove = -> RunConsoleCommand('dpp2_' .. @remove_command_identifier, classname)
submenu, button = \AddSubMenu('gui.dpp2.menu.remove_from_' .. @identifier .. '_restrictions')
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', remove)\SetIcon(Menus.Icons.Remove)
else
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. @add_command_identifier)
add = -> @OpenMenu(classname)
\AddOption('gui.dpp2.menu.add_to_' .. @identifier .. '_restrictions', add)\SetIcon(Menus.Icons.Add)
addLimitMenuOption = (classname, menu) =>
with menu
if @Has(classname)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. @add_command_identifier)
edit = -> @OpenMenu(classname)
\AddOption('gui.dpp2.menu.edit_in_' .. @identifier .. '_limits', edit)\SetIcon(Menus.Icons.Edit)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. @remove_command_identifier)
remove = -> RunConsoleCommand('dpp2_' .. @remove_command_identifier, classname, entry.group) for entry in *@GetByClass(classname)
submenu, button = \AddSubMenu('gui.dpp2.menu.remove_from_' .. @identifier .. '_limits')
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', remove)\SetIcon(Menus.Icons.Remove)
else
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. @add_command_identifier)
add = -> @OpenMenu(classname)
\AddOption('gui.dpp2.menu.add_to_' .. @identifier .. '_limits', add)\SetIcon(Menus.Icons.Add)
addBlacklistMenuOption = (classname, menu) =>
with menu
if @Has(classname)
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. @remove_command_identifier)
remove = -> RunConsoleCommand('dpp2_' .. @remove_command_identifier, classname)
submenu, button = \AddSubMenu('gui.dpp2.menu.remove_from_' .. @identifier .. '_' .. @@REGULAR_NAME)
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', remove)\SetIcon(Menus.Icons.Remove)
else
if DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. @add_command_identifier)
add = -> RunConsoleCommand('dpp2_' .. @add_command_identifier, classname)
\AddOption('gui.dpp2.menu.add_to_' .. @identifier .. '_' .. @@REGULAR_NAME, add)\SetIcon(Menus.Icons.AddPlain)
SpawnlistOpenGenericMenu = =>
selected = @GetSelectedChildren()
return if #selected == 0
--models = [panel\GetModelName()\lower() for panel in *selected when panel\GetName() == 'SpawnIcon' and panel.GetModelName and panel\GetModelName()]
models = [panel\GetModelName()\lower() for panel in *selected when panel.GetModelName and panel\GetModelName()]
return if #models == 0
hitRemove = false
hitAdd = false
hitRemove2 = false
hitAdd2 = false
hitRemove3 = false
hitAdd3 = false
for model in *models
if DPP2.ModelBlacklist\Has(model)
hitRemove = true
else
hitAdd = true
if DPP2.ModelExclusions\Has(model)
hitRemove2 = true
else
hitAdd2 = true
if DPP2.ModelRestrictions\Has(model)
hitRemove3 = true
else
hitAdd3 = true
break if hitRemove and hitAdd and hitRemove2 and hitAdd2 and hitRemove3 and hitAdd3
return if not hitRemove and not hitAdd and not hitRemove2 and not hitAdd2 and not hitRemove3 -- a?
local menu
if lastMenu and lastMenuFrame == FrameNumber()
menu = lastMenu
else
menu = DermaMenu()
menu\AddSpacer()
if hitRemove and DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.ModelBlacklist.remove_command_identifier)
lastMenuFrame = FrameNumber() + 1
remove = ->
for model in *models
if DPP2.ModelBlacklist\Has(model)
RunConsoleCommand('dpp2_' .. DPP2.ModelBlacklist.remove_command_identifier, model)
submenu, button = menu\AddSubMenu('gui.dpp2.menu.remove_from_model_blacklist')
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', remove)\SetIcon(Menus.Icons.Remove)
if hitAdd and DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.ModelBlacklist.add_command_identifier)
add = ->
for model in *models
if not DPP2.ModelBlacklist\Has(model)
RunConsoleCommand('dpp2_' .. DPP2.ModelBlacklist.add_command_identifier, model)
menu\AddOption('gui.dpp2.menu.add_to_model_blacklist', add)\SetIcon(Menus.Icons.AddPlain)
if hitRemove2 and DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.ModelExclusions.remove_command_identifier)
lastMenuFrame = FrameNumber() + 1
remove = ->
for model in *models
if DPP2.ModelExclusions\Has(model)
RunConsoleCommand('dpp2_' .. DPP2.ModelExclusions.remove_command_identifier, model)
submenu, button = menu\AddSubMenu('gui.dpp2.menu.remove_from_model_exclist')
button\SetIcon(Menus.Icons.Remove)
submenu\AddOption('gui.dpp2.menus.remove2', remove)\SetIcon(Menus.Icons.Remove)
if hitAdd2 and DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.ModelExclusions.add_command_identifier)
add = ->
for model in *models
if not DPP2.ModelExclusions\Has(model)
RunConsoleCommand('dpp2_' .. DPP2.ModelExclusions.add_command_identifier, model)
menu\AddOption('gui.dpp2.menu.add_to_model_exclist', add)\SetIcon(Menus.Icons.AddPlain)
if hitAdd3 and DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.ModelRestrictions.add_command_identifier)
action = -> DPP2.ModelRestrictions\OpenMultiMenu(models)
menu\AddOption('gui.dpp2.menu.add_to_model_restrictions', action)\SetIcon(Menus.Icons.AddPlain)
if hitRemove3 and DPP2.cmd_perm_watchdog\HasPermission('dpp2_' .. DPP2.ModelRestrictions.add_command_identifier)
action = ->
for model in *models
if DPP2.ModelRestrictions\Has(model)
RunConsoleCommand('dpp2_' .. DPP2.ModelRestrictions.remove_command_identifier, model)
menu\AddOption('gui.dpp2.menu.remove_from_model_restrictions', action)\SetIcon(Menus.Icons.Remove)
DPP2.ToolStuff = {}
local catchButtons
PatchToolPanel = =>
@AddCategory_DPP2 = @AddCategory_DPP2 or @AddCategory
@AddCategory = (name, label, items, ...) =>
panels = {}
catchButtons = panels
a, b, c, d, e, f = @AddCategory_DPP2(name, label, items, ...)
catchButtons = nil
for button in *panels
if IsValid(button)
if isstring(button.Command) and button.Command\startsWith('gmod_tool ')
toolname = button.Command\sub(11)
with button
.DoRightClick_DPP2 = .DoRightClick_DPP2 or .DoRightClick or () ->
.DoRightClick = ->
\DoRightClick_DPP2(button)
local menu
if lastMenu and lastMenuFrame == FrameNumber()
menu = lastMenu
else
menu = DermaMenu()
select_tool = ->
\DoClickInternal()
\DoClick()
menu\AddOption('gui.dpp2.property.copyclassname', (-> SetClipboardText(toolname)))\SetIcon(Menus.Icons.Copy)
menu\AddSpacer()
menu\AddOption('gui.dpp2.toolmenu.select_tool2', (-> RunConsoleCommand(unpack(.Command\split(' ')))))\SetIcon(Menus.Icons.Wrench)
menu\AddOption('gui.dpp2.toolmenu.select_tool', select_tool)\SetIcon(Menus.Icons.Wrench2)
addRestrictionMenuOption(DPP2.ToolgunModeRestrictions, toolname, menu)
addBlacklistMenuOption(DPP2.ToolgunModeExclusions, toolname, menu)
menu\Open()
return a, b, c, d, e, f
modelthing = (model, lastMenu) ->
addBlacklistMenuOption(DPP2.ModelBlacklist, model, lastMenu)
addBlacklistMenuOption(DPP2.ModelExclusions, model, lastMenu)
addRestrictionMenuOption(DPP2.ModelRestrictions, model, lastMenu)
addLimitMenuOption(DPP2.PerModelLimits, model, lastMenu)
PatchSpawnIcon = =>
@OpenMenu_DPP2 = @OpenMenu_DPP2 or @OpenMenu
@OpenMenu = =>
@OpenMenu_DPP2()
if IsValid(lastMenu) and lastMenuFrame == FrameNumber()
lastMenuFrame = FrameNumber() + 1
lastMenu\AddSpacer()
modelthing(@GetModelName()\lower(), lastMenu)
hook.Add 'SpawnlistOpenGenericMenu', 'DPP2.ContextMenuCatch', SpawnlistOpenGenericMenu, 8
hook.Add 'VGUIPanelCreated', 'DPP2.ContextMenuCatch', =>
name = @GetName()
if catchButtons and name == 'DButton'
table.insert(catchButtons, @)
return
if name == 'DMenu' and lastMenuFrame < FrameNumber()
lastMenu = @
lastMenuFrame = FrameNumber()
return
if name == 'SpawnIcon'
timer.Simple 0, -> PatchSpawnIcon(@) if IsValid(@)
return
if name == 'ToolPanel'
PatchToolPanel(@)
return
return if name ~= 'ContentIcon'
timer.Simple 0, ->
return if not @IsValid()
contentType = @GetContentType()
return if not contentType
if contentType == 'entity'
@OpenMenu_DPP2 = @OpenMenu_DPP2 or @OpenMenu
@OpenMenu = =>
@OpenMenu_DPP2()
if IsValid(lastMenu) and lastMenuFrame == FrameNumber()
lastMenuFrame = FrameNumber() + 1
lastMenu\AddSpacer()
addRestrictionMenuOption(DPP2.SpawnRestrictions, @GetSpawnName(), lastMenu)
lastMenu\AddSpacer()
addRestrictionMenuOption(DPP2.PhysgunProtection.RestrictionList, @GetSpawnName(), lastMenu)
addRestrictionMenuOption(DPP2.DriveProtection.RestrictionList, @GetSpawnName(), lastMenu)
addRestrictionMenuOption(DPP2.PickupProtection.RestrictionList, @GetSpawnName(), lastMenu)
addRestrictionMenuOption(DPP2.UseProtection.RestrictionList, @GetSpawnName(), lastMenu)
addRestrictionMenuOption(DPP2.GravgunProtection.RestrictionList, @GetSpawnName(), lastMenu)
addRestrictionMenuOption(DPP2.ToolgunProtection.RestrictionList, @GetSpawnName(), lastMenu)
addRestrictionMenuOption(DPP2.DamageProtection.RestrictionList, @GetSpawnName(), lastMenu)
lastMenu\AddSpacer()
addBlacklistMenuOption(DPP2.PhysgunProtection.Blacklist, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.DriveProtection.Blacklist, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.PickupProtection.Blacklist, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.UseProtection.Blacklist, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.GravgunProtection.Blacklist, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.ToolgunProtection.Blacklist, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.DamageProtection.Blacklist, @GetSpawnName(), lastMenu)
lastMenu\AddSpacer()
addBlacklistMenuOption(DPP2.PhysgunProtection.Exclusions, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.DriveProtection.Exclusions, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.PickupProtection.Exclusions, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.UseProtection.Exclusions, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.GravgunProtection.Exclusions, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.ToolgunProtection.Exclusions, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.DamageProtection.Exclusions, @GetSpawnName(), lastMenu)
lastMenu\Open()
elseif contentType == 'weapon'
@OpenMenu_DPP2 = @OpenMenu_DPP2 or @OpenMenu
@OpenMenu = =>
@OpenMenu_DPP2()
if IsValid(lastMenu) and lastMenuFrame == FrameNumber()
lastMenuFrame = FrameNumber() + 1
lastMenu\AddSpacer()
addRestrictionMenuOption(DPP2.SpawnRestrictions, @GetSpawnName(), lastMenu)
lastMenu\AddSpacer()
addRestrictionMenuOption(DPP2.PickupProtection.RestrictionList, @GetSpawnName(), lastMenu)
addRestrictionMenuOption(DPP2.UseProtection.RestrictionList, @GetSpawnName(), lastMenu)
addRestrictionMenuOption(DPP2.GravgunProtection.RestrictionList, @GetSpawnName(), lastMenu)
lastMenu\AddSpacer()
addBlacklistMenuOption(DPP2.PickupProtection.Blacklist, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.UseProtection.Blacklist, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.GravgunProtection.Blacklist, @GetSpawnName(), lastMenu)
lastMenu\AddSpacer()
addBlacklistMenuOption(DPP2.PickupProtection.Exclusions, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.UseProtection.Exclusions, @GetSpawnName(), lastMenu)
addBlacklistMenuOption(DPP2.GravgunProtection.Exclusions, @GetSpawnName(), lastMenu)
lastMenu\Open()
elseif contentType == 'npc'
@OpenMenu_DPP2 = @OpenMenu_DPP2 or @OpenMenu
@OpenMenu = =>
@OpenMenu_DPP2()
if IsValid(lastMenu) and lastMenuFrame == FrameNumber()
lastMenuFrame = FrameNumber() + 1
classname = @GetSpawnName()
classname = list.GetForEdit('NPC')[classname].Class or classname if list.GetForEdit('NPC')[classname]
lastMenu\AddSpacer()
addRestrictionMenuOption(DPP2.SpawnRestrictions, classname, lastMenu)
lastMenu\AddSpacer()
addRestrictionMenuOption(DPP2.PhysgunProtection.RestrictionList, classname, lastMenu)
addRestrictionMenuOption(DPP2.ToolgunProtection.RestrictionList, classname, lastMenu)
addRestrictionMenuOption(DPP2.UseProtection.RestrictionList, classname, lastMenu)
addRestrictionMenuOption(DPP2.GravgunProtection.RestrictionList, classname, lastMenu)
addRestrictionMenuOption(DPP2.DamageProtection.RestrictionList, classname, lastMenu)
lastMenu\AddSpacer()
addBlacklistMenuOption(DPP2.PhysgunProtection.Blacklist, classname, lastMenu)
addBlacklistMenuOption(DPP2.ToolgunProtection.Blacklist, classname, lastMenu)
addBlacklistMenuOption(DPP2.UseProtection.Blacklist, classname, lastMenu)
addBlacklistMenuOption(DPP2.GravgunProtection.Blacklist, classname, lastMenu)
addBlacklistMenuOption(DPP2.DamageProtection.Blacklist, classname, lastMenu)
lastMenu\AddSpacer()
addBlacklistMenuOption(DPP2.PhysgunProtection.Exclusions, classname, lastMenu)
addBlacklistMenuOption(DPP2.ToolgunProtection.Exclusions, classname, lastMenu)
addBlacklistMenuOption(DPP2.UseProtection.Exclusions, classname, lastMenu)
addBlacklistMenuOption(DPP2.GravgunProtection.Exclusions, classname, lastMenu)
addBlacklistMenuOption(DPP2.DamageProtection.Exclusions, classname, lastMenu)
lastMenu\Open()
elseif contentType == 'vehicle'
@OpenMenu_DPP2 = @OpenMenu_DPP2 or @OpenMenu
@OpenMenu = =>
@OpenMenu_DPP2()
if IsValid(lastMenu) and lastMenuFrame == FrameNumber()
if getdata = list.GetForEdit('Vehicles')[@GetSpawnName()]
lastMenuFrame = FrameNumber() + 1
lastMenu\AddSpacer()
if getdata.Model
modelthing(getdata.Model, lastMenu)
addRestrictionMenuOption(DPP2.SpawnRestrictions, getdata.Class, lastMenu)
lastMenu\AddSpacer()
addRestrictionMenuOption(DPP2.PhysgunProtection.RestrictionList, getdata.Class, lastMenu)
addRestrictionMenuOption(DPP2.ToolgunProtection.RestrictionList, getdata.Class, lastMenu)
addRestrictionMenuOption(DPP2.UseProtection.RestrictionList, getdata.Class, lastMenu)
addRestrictionMenuOption(DPP2.VehicleProtection.RestrictionList, getdata.Class, lastMenu)
addRestrictionMenuOption(DPP2.GravgunProtection.RestrictionList, getdata.Class, lastMenu)
addRestrictionMenuOption(DPP2.DamageProtection.RestrictionList, getdata.Class, lastMenu)
lastMenu\AddSpacer()
addBlacklistMenuOption(DPP2.PhysgunProtection.Blacklist, getdata.Class, lastMenu)
addBlacklistMenuOption(DPP2.ToolgunProtection.Blacklist, getdata.Class, lastMenu)
addBlacklistMenuOption(DPP2.UseProtection.Blacklist, getdata.Class, lastMenu)
addBlacklistMenuOption(DPP2.VehicleProtection.Blacklist, getdata.Class, lastMenu)
addBlacklistMenuOption(DPP2.GravgunProtection.Blacklist, getdata.Class, lastMenu)
addBlacklistMenuOption(DPP2.DamageProtection.Blacklist, getdata.Class, lastMenu)
lastMenu\AddSpacer()
addBlacklistMenuOption(DPP2.PhysgunProtection.Exclusions, getdata.Class, lastMenu)
addBlacklistMenuOption(DPP2.ToolgunProtection.Exclusions, getdata.Class, lastMenu)
addBlacklistMenuOption(DPP2.UseProtection.Exclusions, getdata.Class, lastMenu)
addBlacklistMenuOption(DPP2.VehicleProtection.Exclusions, getdata.Class, lastMenu)
addBlacklistMenuOption(DPP2.GravgunProtection.Exclusions, getdata.Class, lastMenu)
addBlacklistMenuOption(DPP2.DamageProtection.Exclusions, getdata.Class, lastMenu)
lastMenu\Open()
elseif contentType == 'model'
@OpenMenu_DPP2 = @OpenMenu_DPP2 or @OpenMenu
@OpenMenu = =>
@OpenMenu_DPP2()
if IsValid(lastMenu) and lastMenuFrame == FrameNumber()
lastMenuFrame = FrameNumber() + 1
lastMenu\AddSpacer()
lower = @GetModelName()\lower()
modelthing(lower, lastMenu)
| 43.021327 | 149 | 0.75957 |
7a7daac2431817ea04603961e95c73914ca1600a | 176 | export modinfo = {
type: "function"
id: "Output4"
func: (message, color, recipient, stick) ->
TabletMerge message, color, recipient, stick, 5 --note: this isn't a typo
}
| 22 | 75 | 0.676136 |
125d35e0f512f57d94307091fc1946bf9de1c192 | 2,434 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
append = table.insert
find_previous_starter = (line) ->
prev = line.previous_non_blank
while prev and (prev.indentation > line.indentation or not prev\match '%a')
prev = prev.previous_non_blank
prev
class CoffeeScriptMode
new: (lexer) =>
@lexer = bundle_load lexer
comment_syntax: '#'
indentation: {
more_after: {
'[-=]>%s*$', -- fdecls
'[([{:=]%s*$' -- hanging operators
{ r'^(.*=)?\\s*\\b(try|catch|finally|class|switch|for|when)\\b', '%sthen%s*' }, -- block starters
{ r'^\\s*\\b(if|unless|while|else\\s+if)\\b', '%sthen%s*'}, -- conditionals
'^%s*else%s*$',
{ '=%s*if%s', '%sthen%s*' } -- 'if' used as rvalue
}
same_after: {
',%s*$',
}
less_for: {
authoritive: false
{ '^%s*else%s+if%s', '%sthen%s*' },
r'^\\s*(else|\\})\\s*$',
'^%s*[]})]',
}
}
auto_pairs: {
'(': ')'
'[': ']'
'{': '}'
'"': '"'
"'": "'"
}
code_blocks:
multiline: {
{ '{%s*$', '^%s*}', '}'}
{ '%[%s*$', '^%s*%]', ']'}
{ '%(%s*$', '^%s*%)', ')'}
{ '###%s*$', '^%s*###', '###'}
{ '///%s*$', '^%s*///', '///'}
{ '"""%s*$', '^%s*"""', '"""'}
{ "'''%s*$", "^%s*'''", "'''"}
}
indent_for: (line, indent_level) =>
if line\match '^%s*%.'
prev = find_previous_starter line
return prev.indentation if prev and prev\match '^%s*%.'
return prev.indentation + indent_level
@parent.indent_for self, line, indent_level
structure: (editor) =>
buffer = editor.buffer
lines = {}
parents = {}
prev_line = nil
patterns = {
'%s*class%s+%w'
r'\\w\\s*[=:]\\s*(\\([^)]*\\))?\\s*[=-]>'
r'(?:it|describe|context)\\(?\\s+[\'"].+->\\s*$'
}
for line in *editor.buffer.lines
if prev_line
if prev_line.indentation < line.indentation
append parents, prev_line
else
parents = [l for l in *parents when l.indentation < line.indentation]
prev_line = line if line and not line.is_blank
for p in *patterns
if line\umatch p
for i = 1, #parents
append lines, table.remove parents, 1
append lines, line
prev_line = nil
break
#lines > 0 and lines or self.parent.structure @, editor
| 24.585859 | 103 | 0.490551 |
ec92a9b0421eb2b20ddf28d7c9944aefc66d10e9 | 392 | config:
-- general config
format: "markdown" -- fir.generic.emit.markdown
name: "Fir/tests"
-- language (moon/mp)
language: {single: "--"}
-- files
input: {"examples/*.test.lua"} -- formatted for filekit.iglob
transform: (path) -> (path\match "examples/(.+)%.test.lua") .. ".md"
output: "examples"
ignore: { -- formatted for filekit.fromGlob
"module/*"
} | 26.133333 | 70 | 0.602041 |
91fa4b207831af84e5a3f6853071ab722e070941 | 9,596 | -- This file contains container classes, i.e. Lists and Dicts, plus some extended string functionality
local List, Dict, Undict, _undict_mt, _dict_mt
{:insert,:remove,:concat} = table
as_nomsu = =>
if type(@) == 'number'
return tostring(@)
if mt = getmetatable(@)
if _as_nomsu = mt.as_nomsu
return _as_nomsu(@)
return tostring(@)
as_lua = =>
if type(@) == 'number'
return tostring(@)
if mt = getmetatable(@)
if _as_lua = mt.as_lua
return _as_lua(@)
return tostring(@)
nth_to_last = (n)=> @[#@-n+1]
-- List and Dict classes to provide basic equality/tostring functionality for the tables
-- used in Nomsu. This way, they retain a notion of whether they were originally lists or dicts.
_list_mt =
__type: "a List"
__eq: (other)=>
unless type(other) == 'table' and getmetatable(other) == getmetatable(@) and #other == #@
return false
for i,x in ipairs(@)
return false unless x == other[i]
return true
-- Could consider adding a __newindex to enforce list-ness, but would hurt performance
__tostring: =>
"["..concat([as_nomsu(b) for b in *@], ", ").."]"
as_nomsu: =>
"["..concat([as_nomsu(b) for b in *@], ", ").."]"
as_lua: =>
"a_List{"..concat([as_lua(b) for b in *@], ", ").."}"
__lt: (other)=>
assert type(@) == 'table' and type(other) == 'table', "Incompatible types for comparison"
for i=1,math.max(#@, #other)
if not @[i] and other[i] then return true
elseif @[i] and not other[i] then return false
elseif @[i] < other[i] then return true
elseif @[i] > other[i] then return false
return false
__le: (other)=>
assert type(@) == 'table' and type(other) == 'table', "Incompatible types for comparison"
for i=1,math.max(#@, #other)
if not @[i] and other[i] then return true
elseif @[i] and not other[i] then return false
elseif @[i] < other[i] then return true
elseif @[i] > other[i] then return false
return true
__add: (other)=>
ret = List[x for x in *@]
for x in *other
insert(ret, x)
return ret
__index:
add: insert, append: insert
add_1_at_index: (t,x,i)-> insert(t,i,x)
at_index_1_add: insert
pop: remove, remove_last: remove, remove_index: remove
last: (=> @[#@]), first: (=> @[1])
_1_st_to_last:nth_to_last, _1_nd_to_last:nth_to_last
_1_rd_to_last:nth_to_last, _1_th_to_last:nth_to_last
joined: => table.concat([tostring(x) for x in *@]),
joined_with: (glue)=> table.concat([tostring(x) for x in *@], glue),
has: (item)=>
for x in *@
if x == item
return true
return false
remove: (item)=>
for i,x in ipairs @
if x == item
remove(@, i)
index_of: (item)=>
for i,x in ipairs @
if x == item
return i
return nil
from_1_to: (start, stop)=>
n = #@
start = (n+1-start) if start < 0
stop = (n+1-stop) if stop < 0
return List[@[i] for i=start,stop]
from: (start)=> @from_1_to(start, -1)
up_to: (stop)=> @from_1_to(1, stop)
copy: => List[@[i] for i=1,#@]
reverse: =>
n = #@
for i=1,math.floor(n/2)
@[i], @[n-i+1] = @[n-i+1], @[i]
reversed: => List[@[i] for i=#@,1,-1]
sort: => table.sort(@)
sort_by: (fn)=>
keys = setmetatable {},
__index: (k)=>
key = fn(k)
@[k] = key
return key
table.sort(@, (a,b)->keys[a] <= keys[b])
sorted: =>
c = @copy!
c\sort!
return c
sorted_by: (fn)=>
c = @copy!
c\sort_by(fn)
return c
filter_by: (keep)=>
deleted = 0
for i=1,#@
unless keep(@[i])
deleted += 1
elseif deleted > 0
@[i-deleted] = @[i]
for i=#@-deleted+1,#@
@[i] = nil
filtered_by: (keep)=>
c = @copy!
c\filter_by(keep)
return c
-- TODO: remove this safety check to get better performance?
__newindex: (k,v)=>
assert type(k) == 'number', "List indices must be numbers"
rawset(@, k, v)
_list_mt.__index.as_lua = _list_mt.as_lua
_list_mt.__index.as_nomsu = _list_mt.as_nomsu
List = (t,...)->
local l
if type(t) == 'table'
l = setmetatable(t, _list_mt)
elseif type(t) == 'function'
l = setmetatable({}, _list_mt)
add = (...)->
for i=1,select('#',...) do l[#l+1] = select(i,...)
t(add)
elseif type(t) == 'thread'
l = setmetatable({}, _list_mt)
for val in coroutine.wrap(t)
l[#l+1] = val
else error("Unsupported List type: "..type(t))
if select(1,...)
for x in *List(...)
l[#l+1] = x
return l
compliments = setmetatable({}, {__mode:'k'})
_undict_mt =
__type: "an Inverse Dict"
__index: (k)=> not compliments[@][k] and true or nil
__newindex: (k,v)=>
if k
compliments[@][k] = nil
else
compliments[@][k] = true
__eq: (other)=>
unless type(other) == 'table' and getmetatable(other) == getmetatable(@)
return false
return compliments[@] == compliments[other]
__len: => math.huge
__tostring: => "~".._dict_mt.__tostring(compliments[@])
as_nomsu: => "~".._dict_mt.as_nomsu(compliments[@])
as_lua: => "~"..__dict_mt.as_lua(compliments[@])
__band: (other)=>
if getmetatable(other) == _undict_mt
-- ~{x,y} & ~{y,z} == ~{x,y,z} == ~({x,y} | {y,z})
Undict(_dict_mt.__bor(compliments[@], compliments[other]))
else
-- ~{x,y} & {y,z} == {z} == {y,z} & ~{x,y}
_dict_mt.__band(other, @)
__bor: (other)=>
if getmetatable(other) == _undict_mt
-- ~{x,y} | ~{y,z} == ~{y} = ~({x,y} & {y,z})
Undict(_dict_mt.__band(compliments[@], compliments[other]))
else
-- ~{x,y} | {y,z} == ~{z} = ~({y,z} & ~{x,y})
Undict{k,v for k,v in pairs(compliments[@]) when not other[k]}
__bxor: (other)=>
if getmetatable(other) == _undict_mt
-- ~{x,y} ^ ~{y,z} == {x,z} = {x,y} ^ {y,z}
_dict_mt.__bxor(compliments[@], compliments[other])
else
-- ~{x,y} ^ {y,z} == ~{x} = ~({x,y} & ~{y,z})
Undict(_dict_mt.__band(other, @))
__bnot: => Dict{k,v for k,v in pairs(compliments[@])}
Undict = (d)->
u = setmetatable({}, _undict_mt)
compliments[u] = Dict{k,true for k,v in pairs(d) when v}
return u
_dict_mt =
__type: "a Dict"
__eq: (other)=>
unless type(other) == 'table' and getmetatable(other) == getmetatable(@)
return false
for k,v in pairs(@)
return false unless v == other[k]
for k,v in pairs(other)
return false unless v == @[k]
return true
__len: =>
n = 0
for _ in pairs(@) do n += 1
return n
__tostring: =>
"{"..concat([v == true and "."..as_nomsu(k) or ".#{k} = #{v}" for k,v in pairs @], ", ").."}"
as_nomsu: =>
"{"..concat([v == true and "."..as_nomsu(k) or ".#{as_nomsu(k)} = #{as_nomsu(v)}" for k,v in pairs @], ", ").."}"
as_lua: =>
"a_Dict{"..concat(["[ #{as_lua(k)}]= #{as_lua(v)}" for k,v in pairs @], ", ").."}"
__inext: (key)=>
nextkey, value = next(@, key)
if nextkey != nil
return nextkey, Dict{key:nextkey, value:value}
__band: (other)=>
Dict{k,v for k,v in pairs(@) when other[k]}
__bor: (other)=>
if getmetatable(other) == _undict_mt
return _undict_mt.__bor(other, @)
ret = Dict{k,v for k,v in pairs(@)}
for k,v in pairs(other)
if ret[k] == nil then ret[k] = v
return ret
__bxor: (other)=>
if getmetatable(other) == _undict_mt
return _undict_mt.__bxor(other, @)
ret = Dict{k,v for k,v in pairs(@)}
for k,v in pairs(other)
if ret[k] == nil then ret[k] = v
else ret[k] = nil
return ret
__bnot: Undict
__add: (other)=>
ret = Dict{k,v for k,v in pairs(@)}
for k,v in pairs(other)
if ret[k] == nil then ret[k] = v
else ret[k] += v
return ret
__sub: (other)=>
ret = Dict{k,v for k,v in pairs(@)}
for k,v in pairs(other)
if ret[k] == nil then ret[k] = -v
else ret[k] -= v
return ret
Dict = (t,more,...)->
local d
if type(t) == 'table'
d = setmetatable(t, _dict_mt)
elseif type(t) == 'function'
d = setmetatable({}, _dict_mt)
add = (...)->
for i=1,select('#',...) do d[select(i,...)] = true
add_1_eq_2 = (k, v)-> d[k] = v
t(add, add_1_eq_2)
elseif type(t) == 'thread'
d = setmetatable({}, _dict_mt)
for k,v in coroutine.wrap(t)
d[k] = v
else error("Unsupported Dict type: "..type(t))
if more
for k,v in pairs(Dict(more,...))
d[k] = v
return d
return {:List, :Dict}
| 34.394265 | 121 | 0.490725 |
a866e3db84a5b920fd96475e592ba9d0094c39d8 | 966 | export ^
class InGameMenu extends GameState
new: =>
@font = love.graphics.newFont("res/font/special-elite/SpecialElite.ttf", 100)
draw: =>
@previousState()\draw()
love.graphics.reset()
love.graphics.setColor(0, 0, 0, 220)
love.graphics.rectangle("fill", 0, 0, wScr(), hScr())
love.graphics.setColor(255, 255, 255, 255)
love.graphics.setFont(@font)
love.graphics.printf("PAUSED", 0, hScr() / 4 - @font\getHeight() / 2, wScr(), "center")
love.graphics.setColor(255, 255, 255, 200)
love.graphics.printf("Press enter to resume\nPress escape to go back to the menu", 0, hScr() / 2, wScr(), "center")
previousState: =>
statestack\peek(1)
keypressed: (key) =>
switch key
when "return"
statestack\pop()
when "escape"
while statestack\peek().__class != MainMenu
statestack\pop()
| 30.1875 | 123 | 0.570393 |
996b38557c6b9ec6f5b018ce0aea8a32d65332ce | 3,078 |
util = require "moonscript.util"
data = require "moonscript.data"
import reversed, unpack from util
import ntype from require "moonscript.types"
import concat, insert from table
{
raw: (node) => @add node[2]
lines: (node) =>
for line in *node[2]
@add line
declare: (node) =>
names = node[2]
undeclared = @declare names
if #undeclared > 0
with @line "local "
\append_list [@name name for name in *undeclared], ", "
-- this overrides the existing names with new locals, used for local keyword
declare_with_shadows: (node) =>
names = node[2]
@declare names
with @line "local "
\append_list [@name name for name in *names], ", "
assign: (node) =>
_, names, values = unpack node
undeclared = @declare names
declare = "local "..concat(undeclared, ", ")
has_fndef = false
i = 1
while i <= #values
if ntype(values[i]) == "fndef"
has_fndef = true
i = i +1
with @line!
if #undeclared == #names and not has_fndef
\append declare
else
@add declare if #undeclared > 0
\append_list [@value name for name in *names], ", "
\append " = "
\append_list [@value v for v in *values], ", "
return: (node) =>
@line "return ", if node[2] != "" then @value node[2]
break: (node) =>
"break"
if: (node) =>
cond, block = node[2], node[3]
root = with @block @line "if ", @value(cond), " then"
\stms block
current = root
add_clause = (clause)->
type = clause[1]
i = 2
next = if type == "else"
@block "else"
else
i += 1
@block @line "elseif ", @value(clause[2]), " then"
next\stms clause[i]
current.next = next
current = next
add_clause cond for cond in *node[4,]
root
repeat: (node) =>
cond, block = unpack node, 2
with @block "repeat", @line "until ", @value cond
\stms block
while: (node) =>
_, cond, block = unpack node
with @block @line "while ", @value(cond), " do"
\stms block
for: (node) =>
_, name, bounds, block = unpack node
loop = @line "for ", @name(name), " = ", @value({"explist", unpack bounds}), " do"
with @block loop
\declare {name}
\stms block
-- for x in y ...
-- {"foreach", {names...}, {exp...}, body}
foreach: (node) =>
_, names, exps, block = unpack node
loop = with @line!
\append "for "
with @block loop
loop\append_list [\name name, false for name in *names], ", "
loop\append " in "
loop\append_list [@value exp for exp in *exps], ","
loop\append " do"
\declare names
\stms block
export: (node) =>
_, names = unpack node
if type(names) == "string"
if names == "*"
@export_all = true
elseif names == "^"
@export_proper = true
else
@declare names
nil
run: (code) =>
code\call self
nil
group: (node) =>
@stms node[2]
do: (node) =>
with @block!
\stms node[2]
noop: => -- nothing!
}
| 21.985714 | 86 | 0.548733 |
f04887ee550d32faf458a224c07cf41b3bcad192 | 3,024 |
--
-- 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.
util.AddNetworkString('PPM2.DamageAnimation')
util.AddNetworkString('PPM2.KillAnimation')
util.AddNetworkString('PPM2.AngerAnimation')
util.AddNetworkString('PPM2.PlayEmote')
hook.Add 'EntityTakeDamage', 'PPM2.Emotes', (ent, dmg) ->
do
self = ent
if not @__ppm2_ragdoll_parent and @GetPonyData()
@__ppm2_last_hurt_anim = @__ppm2_last_hurt_anim or 0
if @__ppm2_last_hurt_anim < CurTimeL()
@__ppm2_last_hurt_anim = CurTimeL() + 1
net.Start('PPM2.DamageAnimation', true)
net.WriteEntity(@)
net.Broadcast()
do
self = dmg\GetAttacker()
if @GetPonyData() and IsValid(ent) and (ent\IsNPC() or ent\IsPlayer() or ent.Type == 'nextbot')
@__ppm2_last_anger_anim = @__ppm2_last_anger_anim or 0
if @__ppm2_last_anger_anim < CurTimeL()
@__ppm2_last_anger_anim = CurTimeL() + 1
net.Start('PPM2.AngerAnimation', true)
net.WriteEntity(@)
net.Broadcast()
killGrin = =>
return if not IsValid(@)
return if not @GetPonyData()
@__ppm2_grin_hurt_anim = @__ppm2_grin_hurt_anim or 0
return if @__ppm2_grin_hurt_anim > CurTimeL()
@__ppm2_grin_hurt_anim = CurTimeL() + 1
net.Start('PPM2.KillAnimation', true)
net.WriteEntity(@)
net.Broadcast()
hook.Add 'OnNPCKilled', 'PPM2.Emotes', (npc = NULL, attacker = NULL, weapon = NULL) => killGrin(attacker)
hook.Add 'DoPlayerDeath', 'PPM2.Emotes', (ply = NULL, attacker = NULL) => killGrin(attacker)
net.Receive 'PPM2.PlayEmote', (len = 0, ply = NULL) ->
return if not IsValid(ply)
self = ply
emoteID = net.ReadUInt(8)
isEndless = net.ReadBool()
shouldStop = net.ReadBool()
return if not PPM2.AVALIABLE_EMOTES[emoteID]
@__ppm2_last_played_emote = @__ppm2_last_played_emote or 0
return if @__ppm2_last_played_emote > RealTimeL()
@__ppm2_last_played_emote = RealTimeL() + 1
net.Start('PPM2.PlayEmote')
net.WriteUInt(emoteID, 8)
net.WriteEntity(ply)
net.WriteBool(isEndless)
net.WriteBool(shouldStop)
net.SendOmit(ply)
| 39.272727 | 105 | 0.747024 |
f4ee42eb1c2907c4edc49a9b850ba4168c79cc98 | 1,153 | -- resolve remote file like it's local file
--
-- remotefs = require("mooncrafts.remotefs")
-- fs = remotefs({ngx_path: '/__mooncrafts'})
-- content = fs.read("/niiknow/mooncrafts/master/dist.ini")
--
util = require "mooncrafts.util"
httpc = require "mooncrafts.http"
url = require "mooncrafts.url"
import trim, path_sanitize from util
local *
url_parse = url.parse
class Remotefs
new: (conf={}) =>
assert(conf, "conf object is required")
myConf = {}
-- default base to github
myConf.base = trim(conf.base or "https://raw.githubusercontent.com/", "%/*")
myConf.ngx_path = conf.ngx_path or "/__mooncrafts"
@conf = myConf
readRaw: (location) =>
-- build location
url = location
url = @conf.base .. "/" .. trim(path_sanitize(location), "%/*") if location\find(":") == nil
-- ngx.log(ngx.ERR, 'remotefs retrieving: ' .. url)
req = { url: url, method: "GET", capture_url: @conf.ngx_path, headers: {} }
httpc.request(req)
read: (location, default="") =>
rst = @readRaw(location)
return default if (rst.err or rst.code < 200 or rst.code > 299)
rst.body
Remotefs
| 25.622222 | 96 | 0.631396 |
7ee6a5f2842de6610c106a49529e75f66f602abb | 1,059 |
check_args = (name, more) ->
error "spec template takes arguments: name" unless name
if name\match "%u"
error "name should be underscore form, all lowercase"
if more
error "got a second argument to generator, did you mean to pass a string?"
filename = (name) ->
"spec/#{name}_spec.moon"
spec_types = {
models: (name) ->
[[import use_test_env from require "lapis.spec"
import truncate_tables from require "lapis.spec.db"
describe "]] ..name .. [[", ->
use_test_env!
before_each ->
it "should ...", ->
]]
applications: (name) ->
[[import use_test_server from require "lapis.spec"
import request from require "lapis.spec.server"
import truncate_tables from require "lapis.spec.db"
describe "]] ..name .. [[", ->
use_test_server!
before_each ->
it "should ...", ->
]]
}
spec_types.helpers = spec_types.models
write = (writer, name) ->
path = writer\mod_to_path name
prefix = name\match "^(.+)%."
writer\write filename(path), (spec_types[prefix] or spec_types.applications) name
{:check_args, :write}
| 20.764706 | 83 | 0.6695 |
db0749e8dcb4bf49237e7bccae79c329bda53794 | 270 | M = {}
M.trim = (path) ->
if (string.match path, "[/\\%.]") == nil
-- if both caller and callee modules live at the root directory
return ""
else
return string.match path, "(.-)[/\\%.]?[^%./\\]+$" -- example "a.b/c.d" => "a.b/c"
return M | 33.75 | 90 | 0.488889 |
4227bfe6882bd68a0145d5da43cbe29bc37efaae | 236 | M = {}
parent = ...
case = require(parent.."._".."case")["case"]
M.main = () ->
case {}, {}, true, "case 0"
case {1,2}, {1,2}, true, "case 1"
case {{1},2}, {{1},2}, true, "case 2"
case {1},{1,2}, false, "case 3"
return M | 26.222222 | 44 | 0.461864 |
93862c418c8e7c8b36b90b8d5c939c10f5af789b | 39 | square = (x) ->
x * x
{
:square
}
| 5.571429 | 15 | 0.384615 |
8b9a406b5dbd83158ec645a7479c7f98b44659b4 | 3,616 | lpeg = require 'lpeg'
userdata = lpeg.P('')
file = io.open('/dev/null')
values = { true, false, 42, 'aloha!', userdata, -> 'hi!', {} }
stdtypes = { 'nil', 'boolean', 'number', 'string', 'userdata', 'function', 'thread', 'table' }
for impl in *{'pure', 'native'} do
{ type: mtype, istype: istype } = require 'mtype.'..impl
describe "#{impl}.istype", ->
for ttype in *stdtypes do
context "('#{ttype}', nil)", ->
expected = ttype == 'nil'
it "returns #{expected}", ->
assert.equals expected, istype(ttype, nil)
assert.equals expected, istype(ttype)(nil)
context "('#{ttype}', <file>)", ->
expected = ttype == 'userdata'
it "returns #{expected}", ->
assert.equals expected, istype(ttype, file)
assert.equals expected, istype(ttype)(file)
for value in *values do
context "('#{ttype}', <#{mtype(value)}>)", ->
expected = mtype(value) == ttype
it "returns #{expected}", ->
assert.equals expected, istype(ttype, value)
assert.equals expected, istype(ttype)(value)
context "('file', <file>)", ->
it 'returns true', ->
assert.is_true istype('file', file)
context 'given table with __istype', ->
context 'function', ->
it 'calls it and returns return value', ->
for expected in *{true, false} do
value = setmetatable({}, { __istype: -> expected })
assert.same expected, istype('foo', value)
it 'calls it with (table, type)', ->
ttype, value = 'foo', {}
setmetatable(value, { __istype: (t, v) ->
assert t == value
assert v == ttype
true
})
assert.is_true istype(ttype, value)
context 'table', ->
table = { Truthy: true, Falsy: false, Number: 1 }
value = setmetatable({}, { __istype: table })
context 'when contains given type as key', ->
it 'returns false when its value is false', ->
assert.is_false istype('Falsy', value)
it 'returns true when its value is true', ->
assert.is_true istype('Truthy', value)
it 'returns true when its value is not nil or false', ->
assert.is_true istype('Number', value)
context 'when does not contain given type as key', ->
it 'returns false', ->
assert.is_false istype('NoHere', value)
context 'of incorrect type', ->
for field in *values unless contains type(field), {'function', 'table'} do
value = setmetatable({}, { __istype: field })
it 'raises error', ->
assert.has_error -> istype('foo', value)
assert.has_error -> istype('foo')(value)
context 'given table with __type and w/o __istype', ->
metatype = 'Metal'
value = setmetatable({}, { __type: metatype })
it 'returns true when given type is same as metatype', ->
assert.is_true istype(metatype, value)
it 'returns true for type "table" (supertype)', ->
assert.is_true istype('table', value)
context 'given 1 argument', ->
subject = istype('string')
it 'returns partially applied function', ->
assert.is_same 'function', type(subject)
assert.is_true subject('aloha!')
assert.is_false subject(66)
context 'when 1st arg is not string', ->
for value in *values if type(value) != 'string' do
it 'raises error', ->
assert.has_error -> istype(value, 'foo')
assert.has_error -> istype(value)('foo')
| 32 | 94 | 0.561117 |
72d419870a04632806d1d63998e86ab7ea4df208 | 26,322 |
--
-- Copyright (C) 2017-2019 DBot
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
wUInt = (def = 0, size = 8) ->
return (arg = def) -> net.WriteUInt(arg, size)
wInt = (def = 0, size = 8) ->
return (arg = def) -> net.WriteInt(arg, size)
rUInt = (size = 8, min = 0, max = 255) ->
return -> math.Clamp(net.ReadUInt(size), min, max)
rInt = (size = 8, min = -128, max = 127) ->
return -> math.Clamp(net.ReadInt(size), min, max)
rFloat = (min = 0, max = 255) ->
return -> math.Clamp(net.ReadDouble(), min, max)
wFloat = net.WriteDouble
rBool = net.ReadBool
wBool = net.WriteBool
rColor = net.ReadColor
wColor = net.WriteColor
rString = net.ReadString
wString = net.WriteString
COLOR_FIXER = (r = 255, g = 255, b = 255, a = 255) ->
func = (arg = Color(r, g, b, a)) ->
if not IsColor(arg)
return Color(255, 255, 255)
else
{:r, :g, :b, :a} = arg
if r and g and b and a
return Color(r, g, b, a)
else
return Color(255, 255, 255)
return func
URL_FIXER = (arg = '') ->
arg = tostring(arg)
if arg\find('^https?://')
return arg
else
return ''
rURL = -> URL_FIXER(rString())
FLOAT_FIXER = (def = 1, min = 0, max = 1) ->
defFunc = -> def if type(def) ~= 'function'
defFunc = def if type(def) == 'function'
return (arg = defFunc()) -> math.Clamp(tonumber(arg) or defFunc(), min, max)
INT_FIXER = (def = 1, min = 0, max = 1) ->
defFunc = -> def if type(def) ~= 'function'
defFunc = def if type(def) == 'function'
return (arg = defFunc()) -> math.floor(math.Clamp(tonumber(arg) or defFunc(), min, max))
PPM2.PonyDataRegistry = {
'age': {
default: -> PPM2.AGE_ADULT
getFunc: 'Age'
enum: {'FILLY', 'ADULT', 'MATURE'}
}
'race': {
default: -> PPM2.RACE_EARTH
getFunc: 'Race'
enum: [arg for _, arg in ipairs PPM2.RACE_ENUMS]
}
'wings_type': {
default: -> 0
getFunc: 'WingsType'
enum: [arg for _, arg in ipairs PPM2.AvaliablePonyWings]
}
'gender': {
default: -> PPM2.GENDER_FEMALE
getFunc: 'Gender'
enum: [arg for _, arg in ipairs PPM2.AGE_ENUMS]
}
'weight': {
default: -> 1
getFunc: 'Weight'
min: PPM2.MIN_WEIGHT
max: PPM2.MAX_WEIGHT
type: 'FLOAT'
}
'ponysize': {
default: -> 1
getFunc: 'PonySize'
min: PPM2.MIN_SCALE
max: PPM2.MAX_SCALE
type: 'FLOAT'
}
'necksize': {
default: -> 1
getFunc: 'NeckSize'
min: PPM2.MIN_NECK
max: PPM2.MAX_NECK
type: 'FLOAT'
}
'legssize': {
default: -> 1
getFunc: 'LegsSize'
min: PPM2.MIN_LEGS
max: PPM2.MAX_LEGS
type: 'FLOAT'
}
'spinesize': {
default: -> 1
getFunc: 'BackSize'
min: PPM2.MIN_SPINE
max: PPM2.MAX_SPINE
type: 'FLOAT'
}
'male_buff': {
default: -> PPM2.DEFAULT_MALE_BUFF
getFunc: 'MaleBuff'
min: PPM2.MIN_MALE_BUFF
max: PPM2.MAX_MALE_BUFF
type: 'FLOAT'
}
'eyelash': {
default: -> 0
getFunc: 'EyelashType'
enum: [arg for _, arg in ipairs PPM2.EyelashTypes]
}
'tail': {
default: -> 0
getFunc: 'TailType'
enum: [arg for _, arg in ipairs PPM2.AvaliableTails]
}
'tail_new': {
default: -> 0
getFunc: 'TailTypeNew'
enum: [arg for _, arg in ipairs PPM2.AvaliableTailsNew]
}
'mane': {
default: -> 0
getFunc: 'ManeType'
enum: [arg for _, arg in ipairs PPM2.AvaliableUpperManes]
}
'mane_new': {
default: -> 0
getFunc: 'ManeTypeNew'
enum: [arg for _, arg in ipairs PPM2.AvaliableUpperManesNew]
}
'manelower': {
default: -> 0
getFunc: 'ManeTypeLower'
enum: [arg for _, arg in ipairs PPM2.AvaliableLowerManes]
}
'manelower_new': {
default: -> 0
getFunc: 'ManeTypeLowerNew'
enum: [arg for _, arg in ipairs PPM2.AvaliableLowerManesNew]
}
'socks_texture': {
default: -> 0
getFunc: 'SocksTexture'
enum: [arg for _, arg in ipairs PPM2.SocksTypes]
}
'socks_texture_url': {
default: -> ''
getFunc: 'SocksTextureURL'
type: 'URL'
}
'tailsize': {
default: -> 1
getFunc: 'TailSize'
min: PPM2.MIN_TAIL_SIZE
max: PPM2.MAX_TAIL_SIZE
type: 'FLOAT'
}
'cmark': {
default: -> true
getFunc: 'CMark'
type: 'BOOLEAN'
}
'cmark_size': {
default: -> 1
getFunc: 'CMarkSize'
min: 0
max: 1
type: 'FLOAT'
}
'cmark_color': {
default: -> Color(255, 255, 255)
getFunc: 'CMarkColor'
type: 'COLOR'
}
'eyelash_color': {
default: -> Color(0, 0, 0)
getFunc: 'EyelashesColor'
type: 'COLOR'
}
'eyelashes_phong_separate': {
default: -> false
getFunc: 'SeparateEyelashesPhong'
type: 'BOOLEAN'
}
'fangs': {
default: -> false
getFunc: 'Fangs'
type: 'BOOLEAN'
}
'bat_pony_ears': {
default: -> false
getFunc: 'BatPonyEars'
type: 'BOOLEAN'
}
'claw_teeth': {
default: -> false
getFunc: 'ClawTeeth'
type: 'BOOLEAN'
}
'cmark_type': {
default: -> 4
getFunc: 'CMarkType'
enum: [arg for _, arg in ipairs PPM2.DefaultCutiemarks]
}
'cmark_url': {
default: -> ''
getFunc: 'CMarkURL'
type: 'URL'
}
'body': {
default: -> Color(255, 255, 255)
getFunc: 'BodyColor'
type: 'COLOR'
}
'body_bump': {
default: -> 0.5
getFunc: 'BodyBumpStrength'
type: 'FLOAT'
min: 0
max: 1
}
'eyebrows': {
default: -> Color(0, 0, 0)
getFunc: 'EyebrowsColor'
type: 'COLOR'
}
'eyebrows_glow': {
default: -> false
getFunc: 'GlowingEyebrows'
type: 'BOOLEAN'
}
'eyebrows_glow_strength': {
default: -> 1
getFunc: 'EyebrowsGlowStrength'
type: 'FLOAT'
min: 0
max: 1
}
'hide_manes': {
default: -> true
getFunc: 'HideManes'
type: 'BOOLEAN'
}
'hide_manes_socks': {
default: -> true
getFunc: 'HideManesSocks'
type: 'BOOLEAN'
}
'hide_manes_mane': {
default: -> true
getFunc: 'HideManesMane'
type: 'BOOLEAN'
}
'hide_manes_tail': {
default: -> true
getFunc: 'HideManesTail'
type: 'BOOLEAN'
}
'horn_color': {
default: -> Color(255, 255, 255)
getFunc: 'HornColor'
type: 'COLOR'
}
'wings_color': {
default: -> Color(255, 255, 255)
getFunc: 'WingsColor'
type: 'COLOR'
}
'separate_wings': {
default: -> false
getFunc: 'SeparateWings'
type: 'BOOLEAN'
}
'separate_horn': {
default: -> false
getFunc: 'SeparateHorn'
type: 'BOOLEAN'
}
'separate_magic_color': {
default: -> false
getFunc: 'SeparateMagicColor'
type: 'BOOLEAN'
}
'horn_magic_color': {
default: -> Color(255, 255, 255)
getFunc: 'HornMagicColor'
type: 'COLOR'
}
'horn_glow': {
default: -> false
getFunc: 'HornGlow'
type: 'BOOLEAN'
}
'horn_glow_strength': {
default: -> 1
getFunc: 'HornGlowSrength'
min: 0
max: 1
type: 'FLOAT'
}
'horn_detail_color': {
default: -> Color(90, 90, 90)
getFunc: 'HornDetailColor'
type: 'COLOR'
}
'separate_eyes': {
default: -> false
getFunc: 'SeparateEyes'
type: 'BOOLEAN'
}
'separate_mane': {
default: -> false
getFunc: 'SeparateMane'
type: 'BOOLEAN'
}
'call_playerfootstep': {
default: -> true
getFunc: 'CallPlayerFootstepHook'
type: 'BOOLEAN'
}
'disable_hoofsteps': {
default: -> false
getFunc: 'DisableHoofsteps'
type: 'BOOLEAN'
}
'disable_wander_sounds': {
default: -> false
getFunc: 'DisableWanderSounds'
type: 'BOOLEAN'
}
'disable_new_step_sounds': {
default: -> false
getFunc: 'DisableStepSounds'
type: 'BOOLEAN'
}
'disable_jump_sound': {
default: -> false
getFunc: 'DisableJumpSound'
type: 'BOOLEAN'
}
'disable_falldown_sound': {
default: -> false
getFunc: 'DisableFalldownSound'
type: 'BOOLEAN'
}
'socks': {
default: -> false
getFunc: 'Socks'
type: 'BOOLEAN'
}
'new_male_muzzle': {
default: -> true
getFunc: 'NewMuzzle'
type: 'BOOLEAN'
}
'noflex': {
default: -> false
getFunc: 'NoFlex'
type: 'BOOLEAN'
}
'socks_model': {
default: -> false
getFunc: 'SocksAsModel'
type: 'BOOLEAN'
}
'socks_model_new': {
default: -> false
getFunc: 'SocksAsNewModel'
type: 'BOOLEAN'
}
'socks_model_color': {
default: -> Color(255, 255, 255)
getFunc: 'SocksColor'
type: 'COLOR'
}
'socks_new_model_color1': {
default: -> Color(255, 255, 255)
getFunc: 'NewSocksColor1'
type: 'COLOR'
}
'socks_new_model_color2': {
default: -> Color(0, 0, 0)
getFunc: 'NewSocksColor2'
type: 'COLOR'
}
'socks_new_model_color3': {
default: -> Color(0, 0, 0)
getFunc: 'NewSocksColor3'
type: 'COLOR'
}
'socks_new_texture_url': {
default: -> ''
getFunc: 'NewSocksTextureURL'
type: 'URL'
}
'suit': {
default: -> 0
getFunc: 'Bodysuit'
enum: [arg for _, arg in ipairs PPM2.AvaliablePonySuits]
}
'left_wing_size': {
default: -> 1
getFunc: 'LWingSize'
min: PPM2.MIN_WING
max: PPM2.MAX_WING
type: 'FLOAT'
}
'left_wing_x': {
default: -> 0
getFunc: 'LWingX'
min: PPM2.MIN_WINGX
max: PPM2.MAX_WINGX
type: 'FLOAT'
}
'left_wing_y': {
default: -> 0
getFunc: 'LWingY'
min: PPM2.MIN_WINGY
max: PPM2.MAX_WINGY
type: 'FLOAT'
}
'left_wing_z': {
default: -> 0
getFunc: 'LWingZ'
min: PPM2.MIN_WINGZ
max: PPM2.MAX_WINGZ
type: 'FLOAT'
}
'right_wing_size': {
default: -> 1
getFunc: 'RWingSize'
min: PPM2.MIN_WING
max: PPM2.MAX_WING
type: 'FLOAT'
}
'right_wing_x': {
default: -> 0
getFunc: 'RWingX'
min: PPM2.MIN_WINGX
max: PPM2.MAX_WINGX
type: 'FLOAT'
}
'right_wing_y': {
default: -> 0
getFunc: 'RWingY'
min: PPM2.MIN_WINGY
max: PPM2.MAX_WINGY
type: 'FLOAT'
}
'right_wing_z': {
default: -> 0
getFunc: 'RWingZ'
min: PPM2.MIN_WINGZ
max: PPM2.MAX_WINGZ
type: 'FLOAT'
}
'teeth_color': {
default: -> Color(255, 255, 255)
getFunc: 'TeethColor'
type: 'COLOR'
}
'mouth_color': {
default: -> Color(219, 65, 155)
getFunc: 'MouthColor'
type: 'COLOR'
}
'tongue_color': {
default: -> Color(235, 131, 59)
getFunc: 'TongueColor'
type: 'COLOR'
}
'bat_wing_color': {
default: -> Color(255, 255, 255)
getFunc: 'BatWingColor'
type: 'COLOR'
}
'bat_wing_skin_color': {
default: -> Color(255, 255, 255)
getFunc: 'BatWingSkinColor'
type: 'COLOR'
}
'separate_horn_phong': {
default: -> false
getFunc: 'SeparateHornPhong'
type: 'BOOLEAN'
}
'separate_wings_phong': {
default: -> false
getFunc: 'SeparateWingsPhong'
type: 'BOOLEAN'
}
'separate_mane_phong': {
default: -> false
getFunc: 'SeparateManePhong'
type: 'BOOLEAN'
}
'separate_tail_phong': {
default: -> false
getFunc: 'SeparateTailPhong'
type: 'BOOLEAN'
}
'alternative_fangs': {
default: -> false
getFunc: 'AlternativeFangs'
type: 'BOOLEAN'
}
'hoof_fluffers': {
default: -> false
getFunc: 'HoofFluffers'
type: 'BOOLEAN'
}
'hoof_fluffers_strength': {
default: -> 1
getFunc: 'HoofFluffersStrength'
min: 0
max: 1
type: 'FLOAT'
}
'ears_size': {
default: -> 1
getFunc: 'EarsSize'
min: 0.1
max: 2
type: 'FLOAT'
}
'bat_pony_ears_strength': {
default: -> 1
getFunc: 'BatPonyEarsStrength'
min: 0
max: 1
type: 'FLOAT'
}
'fangs_strength': {
default: -> 1
getFunc: 'FangsStrength'
min: 0
max: 1
type: 'FLOAT'
}
'clawteeth_strength': {
default: -> 1
getFunc: 'ClawTeethStrength'
min: 0
max: 1
type: 'FLOAT'
}
'lips_color_inherit': {
default: -> true
getFunc: 'LipsColorInherit'
type: 'BOOLEAN'
}
'nose_color_inherit': {
default: -> true
getFunc: 'NoseColorInherit'
type: 'BOOLEAN'
}
'lips_color': {
default: -> Color(172, 92, 92)
getFunc: 'LipsColor'
type: 'COLOR'
}
'nose_color': {
default: -> Color(77, 84, 83)
getFunc: 'NoseColor'
type: 'COLOR'
}
'weapon_hide': {
default: -> true
getFunc: 'HideWeapons'
type: 'BOOLEAN'
}
}
for _, {internal, publicName} in ipairs {{'_left', 'Left'}, {'_right', 'Right'}, {'', ''}}
PPM2.PonyDataRegistry["eye_url#{internal}"] = {
default: -> ''
getFunc: "EyeURL#{publicName}"
type: 'URL'
}
PPM2.PonyDataRegistry["eye_bg#{internal}"] = {
default: -> Color(255, 255, 255)
getFunc: "EyeBackground#{publicName}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["eye_hole#{internal}"] = {
default: -> Color(0, 0, 0)
getFunc: "EyeHole#{publicName}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["eye_iris1#{internal}"] = {
default: -> Color(200, 200, 200)
getFunc: "EyeIrisTop#{publicName}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["eye_iris2#{internal}"] = {
default: -> Color(200, 200, 200)
getFunc: "EyeIrisBottom#{publicName}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["eye_irisline1#{internal}"] = {
default: -> Color(255, 255, 255)
getFunc: "EyeIrisLine1#{publicName}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["eye_irisline_direction#{internal}"] = {
default: -> false
getFunc: "EyeLineDirection#{publicName}"
type: 'BOOLEAN'
}
PPM2.PonyDataRegistry["eye_irisline2#{internal}"] = {
default: -> Color(255, 255, 255)
getFunc: "EyeIrisLine2#{publicName}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["eye_reflection#{internal}"] = {
default: -> Color(255, 255, 255, 127)
getFunc: "EyeReflection#{publicName}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["eye_effect#{internal}"] = {
default: -> Color(255, 255, 255)
getFunc: "EyeEffect#{publicName}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["eye_lines#{internal}"] = {
default: -> true
getFunc: "EyeLines#{publicName}"
type: 'BOOLEAN'
}
PPM2.PonyDataRegistry["eye_iris_size#{internal}"] = {
default: -> 1
getFunc: "IrisSize#{publicName}"
min: PPM2.MIN_IRIS
max: PPM2.MAX_IRIS
type: 'FLOAT'
modifiers: true
}
PPM2.PonyDataRegistry["eye_derp#{internal}"] = {
default: -> false
getFunc: "DerpEyes#{publicName}"
type: 'BOOLEAN'
}
PPM2.PonyDataRegistry["eye_use_refract#{internal}"] = {
default: -> false
getFunc: "EyeRefract#{publicName}"
type: 'BOOLEAN'
}
PPM2.PonyDataRegistry["eye_cornera#{internal}"] = {
default: -> false
getFunc: "EyeCornerA#{publicName}"
type: 'BOOLEAN'
}
PPM2.PonyDataRegistry["eye_derp_strength#{internal}"] = {
default: -> 1
getFunc: "DerpEyesStrength#{publicName}"
min: PPM2.MIN_DERP_STRENGTH
max: PPM2.MAX_DERP_STRENGTH
type: 'FLOAT'
modifiers: true
}
PPM2.PonyDataRegistry["eye_type#{internal}"] = {
default: -> 0
getFunc: "EyeType#{publicName}"
enum: [arg for _, arg in ipairs PPM2.AvaliableEyeTypes]
}
PPM2.PonyDataRegistry["eye_reflection_type#{internal}"] = {
default: -> 0
getFunc: "EyeReflectionType#{publicName}"
enum: [arg for _, arg in ipairs PPM2.AvaliableEyeReflections]
}
PPM2.PonyDataRegistry["hole_width#{internal}"] = {
default: -> 1
getFunc: "HoleWidth#{publicName}"
min: PPM2.MIN_PUPIL_SIZE
max: PPM2.MAX_PUPIL_SIZE
type: 'FLOAT'
modifiers: true
}
PPM2.PonyDataRegistry["hole_height#{internal}"] = {
default: -> 1
getFunc: "HoleHeight#{publicName}"
min: PPM2.MIN_PUPIL_SIZE
max: PPM2.MAX_PUPIL_SIZE
type: 'FLOAT'
modifiers: true
}
PPM2.PonyDataRegistry["iris_width#{internal}"] = {
default: -> 1
getFunc: "IrisWidth#{publicName}"
min: PPM2.MIN_PUPIL_SIZE
max: PPM2.MAX_PUPIL_SIZE
type: 'FLOAT'
modifiers: true
}
PPM2.PonyDataRegistry["iris_height#{internal}"] = {
default: -> 1
getFunc: "IrisHeight#{publicName}"
min: PPM2.MIN_PUPIL_SIZE
max: PPM2.MAX_PUPIL_SIZE
type: 'FLOAT'
modifiers: true
}
PPM2.PonyDataRegistry["eye_glossy_reflection#{internal}"] = {
default: -> 0.16
getFunc: "EyeGlossyStrength#{publicName}"
min: 0
max: 1
type: 'FLOAT'
}
PPM2.PonyDataRegistry["hole_shiftx#{internal}"] = {
default: -> 0
getFunc: "HoleShiftX#{publicName}"
min: PPM2.MIN_HOLE_SHIFT
max: PPM2.MAX_HOLE_SHIFT
type: 'FLOAT'
modifiers: true
}
PPM2.PonyDataRegistry["hole_shifty#{internal}"] = {
default: -> 0
getFunc: "HoleShiftY#{publicName}"
min: PPM2.MIN_HOLE_SHIFT
max: PPM2.MAX_HOLE_SHIFT
type: 'FLOAT'
modifiers: true
}
PPM2.PonyDataRegistry["eye_hole_size#{internal}"] = {
default: -> .8
getFunc: "HoleSize#{publicName}"
min: PPM2.MIN_HOLE
max: PPM2.MAX_HOLE
type: 'FLOAT'
modifiers: true
}
PPM2.PonyDataRegistry["eye_rotation#{internal}"] = {
default: -> 0
getFunc: "EyeRotation#{publicName}"
min: PPM2.MIN_EYE_ROTATION
max: PPM2.MAX_EYE_ROTATION
type: 'INT'
}
for i = 1, 3
PPM2.PonyDataRegistry["horn_url_#{i}"] = {
default: -> ''
getFunc: "HornURL#{i}"
type: 'URL'
}
PPM2.PonyDataRegistry["bat_wing_url_#{i}"] = {
default: -> ''
getFunc: "BatWingURL#{i}"
type: 'URL'
}
PPM2.PonyDataRegistry["bat_wing_skin_url_#{i}"] = {
default: -> ''
getFunc: "BatWingSkinURL#{i}"
type: 'URL'
}
PPM2.PonyDataRegistry["wings_url_#{i}"] = {
default: -> ''
getFunc: "WingsURL#{i}"
type: 'URL'
}
PPM2.PonyDataRegistry["horn_url_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "HornURLColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["bat_wing_url_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "BatWingURLColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["bat_wing_skin_url_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "BatWingSkinURLColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["wings_url_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "WingsURLColor#{i}"
type: 'COLOR'
}
for i = 1, 6
PPM2.PonyDataRegistry["socks_detail_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "SocksDetailColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["mane_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "ManeColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["mane_detail_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "ManeDetailColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["mane_url_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "ManeURLColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["mane_url_#{i}"] = {
default: -> ''
getFunc: "ManeURL#{i}"
type: 'URL'
}
PPM2.PonyDataRegistry["tail_detail_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "TailDetailColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["tail_url_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "TailURLColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["tail_url_#{i}"] = {
default: -> ''
getFunc: "TailURL#{i}"
type: 'URL'
}
PPM2.PonyDataRegistry["tail_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "TailColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["lower_mane_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "LowerManeColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["lower_mane_url_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "LowerManeURLColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["lower_mane_url_#{i}"] = {
default: -> ''
getFunc: "LowerManeURL#{i}"
type: 'URL'
}
PPM2.PonyDataRegistry["upper_mane_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "UpperManeColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["upper_mane_url_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "UpperManeURLColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["upper_mane_url_#{i}"] = {
default: -> ''
getFunc: "UpperManeURL#{i}"
type: 'URL'
}
PPM2.PonyDataRegistry["lower_mane_detail_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "LowerManeDetailColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["upper_mane_detail_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "UpperManeDetailColor#{i}"
type: 'COLOR'
}
for i = 1, PPM2.MAX_BODY_DETAILS
PPM2.PonyDataRegistry["body_detail_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "BodyDetailColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["body_detail_#{i}"] = {
default: -> 0
getFunc: "BodyDetail#{i}"
enum: [arg for _, arg in ipairs PPM2.BodyDetailsEnum]
}
PPM2.PonyDataRegistry["body_detail_url_#{i}"] = {
default: -> ''
getFunc: "BodyDetailURL#{i}"
type: 'URL'
}
PPM2.PonyDataRegistry["body_detail_url_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "BodyDetailURLColor#{i}"
type: 'COLOR'
}
PPM2.PonyDataRegistry["body_detail_glow_#{i}"] = {
default: -> false
getFunc: "BodyDetailGlow#{i}"
type: 'BOOLEAN'
}
PPM2.PonyDataRegistry["body_detail_glow_strength_#{i}"] = {
default: -> 1
getFunc: "BodyDetailGlowStrength#{i}"
type: 'FLOAT'
min: 0
max: 1
}
for i = 1, PPM2.MAX_TATTOOS
PPM2.PonyDataRegistry["tattoo_type_#{i}"] = {
default: -> 0
getFunc: "TattooType#{i}"
enum: [arg for _, arg in ipairs PPM2.TATTOOS_REGISTRY]
}
PPM2.PonyDataRegistry["tattoo_posx_#{i}"] = {
default: -> 0
getFunc: "TattooPosX#{i}"
min: -100
max: 100
type: 'FLOAT'
}
PPM2.PonyDataRegistry["tattoo_posy_#{i}"] = {
default: -> 0
getFunc: "TattooPosY#{i}"
fix: (arg = 0) -> math.Clamp(tonumber(arg) or 0, -100, 100)
min: -100
max: 100
type: 'FLOAT'
}
PPM2.PonyDataRegistry["tattoo_rotate_#{i}"] = {
default: -> 0
getFunc: "TattooRotate#{i}"
min: -180
max: 180
type: 'INT'
}
PPM2.PonyDataRegistry["tattoo_scalex_#{i}"] = {
default: -> 1
getFunc: "TattooScaleX#{i}"
min: 0
max: 10
type: 'FLOAT'
}
PPM2.PonyDataRegistry["tattoo_glow_strength_#{i}"] = {
default: -> 1
getFunc: "TattooGlowStrength#{i}"
min: 0
max: 1
type: 'FLOAT'
}
PPM2.PonyDataRegistry["tattoo_scaley_#{i}"] = {
default: -> 1
getFunc: "TattooScaleY#{i}"
min: 0
max: 10
type: 'FLOAT'
}
PPM2.PonyDataRegistry["tattoo_glow_#{i}"] = {
default: -> false
getFunc: "TattooGlow#{i}"
type: 'BOOLEAN'
}
PPM2.PonyDataRegistry["tattoo_over_detail_#{i}"] = {
default: -> false
getFunc: "TattooOverDetail#{i}"
type: 'BOOLEAN'
}
PPM2.PonyDataRegistry["tattoo_color_#{i}"] = {
default: -> Color(255, 255, 255)
getFunc: "TattooColor#{i}"
type: 'COLOR'
}
for _, ttype in ipairs {'Body', 'Horn', 'Wings', 'BatWingsSkin', 'Socks', 'Mane', 'Tail', 'UpperMane', 'LowerMane', 'LEye', 'REye', 'BEyes', 'Eyelashes', 'Mouth', 'Teeth', 'Tongue'}
PPM2.PonyDataRegistry[ttype\lower() .. '_phong_exponent'] = {
default: -> 3
getFunc: ttype .. 'PhongExponent'
min: 0.04
max: 10
type: 'FLOAT'
}
PPM2.PonyDataRegistry[ttype\lower() .. '_phong_boost'] = {
default: -> 0.09
getFunc: ttype .. 'PhongBoost'
min: 0.01
max: 1
type: 'FLOAT'
}
PPM2.PonyDataRegistry[ttype\lower() .. '_phong_front'] = {
default: -> 1
getFunc: ttype .. 'PhongFront'
min: 0
max: 20
type: 'FLOAT'
}
PPM2.PonyDataRegistry[ttype\lower() .. '_phong_middle'] = {
default: -> 5
getFunc: ttype .. 'PhongMiddle'
min: 0
max: 20
type: 'FLOAT'
}
PPM2.PonyDataRegistry[ttype\lower() .. '_phong_sliding'] = {
default: -> 10
getFunc: ttype .. 'PhongSliding'
min: 0
max: 20
type: 'FLOAT'
}
PPM2.PonyDataRegistry[ttype\lower() .. '_phong_tint'] = {
default: -> Color(255, 200, 200)
getFunc: ttype .. 'PhongTint'
type: 'COLOR'
}
PPM2.PonyDataRegistry[ttype\lower() .. '_lightwarp_texture'] = {
default: -> 0
getFunc: ttype .. 'Lightwarp'
enum: [arg for _, arg in ipairs PPM2.AvaliableLightwarps]
}
PPM2.PonyDataRegistry[ttype\lower() .. '_lightwarp_texture_url'] = {
default: -> ''
getFunc: ttype .. 'LightwarpURL'
type: 'URL'
}
PPM2.PonyDataRegistry[ttype\lower() .. '_bumpmap_texture_url'] = {
default: -> ''
getFunc: ttype .. 'BumpmapURL'
type: 'URL'
}
for _, {:flex, :active} in ipairs PPM2.PonyFlexController.FLEX_LIST
continue if not active
PPM2.PonyDataRegistry["flex_disable_#{flex\lower()}"] = {
default: -> false
getFunc: "DisableFlex#{flex}"
type: 'BOOLEAN'
}
testMinimalBits = 0
for key, value in pairs PPM2.PonyDataRegistry
if value.enum
value.min = 0
value.max = #value.enum - 1
value.type = 'INT'
switch value.type
when 'INT'
error("Variable #{key} has invalid minimal value (#{type(value.min)})") if type(value.min) ~= 'number'
error("Variable #{max} has invalid maximal value (#{type(value.max)})") if type(value.max) ~= 'number'
value.fix = INT_FIXER(value.default, value.min, value.max)
if value.min >= 0
selectBits = net.ChooseOptimalBits(value.max - value.min)
testMinimalBits += selectBits
value.read = rUInt(selectBits, value.min, value.max)
value.write = wUInt(value.default(), selectBits)
else
selectBits = net.ChooseOptimalBits(math.max(math.abs(value.max), math.abs(value.min)))
testMinimalBits += selectBits
value.read = rInt(selectBits, value.min, value.max)
value.write = wInt(value.default(), selectBits)
when 'FLOAT'
error("Variable #{key} has invalid minimal value (#{type(value.min)})") if type(value.min) ~= 'number'
error("Variable #{max} has invalid maximal value (#{type(value.max)})") if type(value.max) ~= 'number'
value.fix = FLOAT_FIXER(value.default, value.min, value.max)
value.read = rFloat(value.min, value.max)
value.write = (arg = value.default()) -> wFloat(arg)
testMinimalBits += 32
when 'URL'
value.fix = URL_FIXER
value.read = rURL
value.write = wString
testMinimalBits += 8
when 'BOOLEAN'
value.fix = (arg = value.default()) -> tobool(arg)
value.read = rBool
value.write = wBool
testMinimalBits += 1
when 'COLOR'
{:r, :g, :b, :a} = value.default()
value.fix = COLOR_FIXER(r, g, b, a)
value.read = rColor
value.write = wColor
testMinimalBits += 32
else
error("Unknown variable type - #{value.type} for #{key}")
-- print('Minimal required bits - ' .. testMinimalBits)
PPM2.testMinimalBits = testMinimalBits
for key, value in pairs PPM2.PonyDataRegistry
error("Data has no fix function: #{key}") if not value.fix
| 20.420481 | 181 | 0.646265 |
1b259f8d3264a6f33e7d42257a22ab3318bcb3b8 | 97 | module2 = require "module2"
func = -> "module1"
func2 = -> module2.func!
{
:func, :func2
}
| 8.818182 | 27 | 0.587629 |
27e38f82b6a4411089eb403b3a79e6c812f974be | 167 | package.path ..= ";?.lua;"
wklua = require"wklua".create true
wklua.settings =
out: "result.jpg"
in: "http://luajit.org/" -- or C:/path/to/local/file
wklua\image!
| 23.857143 | 54 | 0.652695 |
4eefb54e665ad52d32972764ab179291d535fde4 | 595 | #!/usr/bin/env moon
require"buildah".from "docker://docker.io/library/debian:stable-slim", "pandoc"
APT_GET "update"
APT_GET "full-upgrade"
APT_GET "install inotify-tools locales"
APT_GET "install pandoc texlive-xetex librsvg2-bin texlive-font-utils texlive-latex-recommended lmodern texlive-fonts-recommended"
APT_PURGE "sysvinit-utils e2fsprogs e2fslibs hostname bsdutils ncurses-bin"
APT_GET "--purge autoremove"
APT_GET "autoclean"
WIPE "docs"
WIPE "directories"
WIPE "debian"
WIPE "perl"
COPY "esshd"
COPY "custom", "/usr/share/fonts/custom"
RM "/etc/profile"
START "/esshd"
XPUSH "pandoc"
| 31.315789 | 130 | 0.781513 |
6a8d1ed226d8c602aa831a8a07f6cca3d2c8aea0 | 2,223 | class Chapters extends BarBase
minWidth = settings['chapter-marker-width']*100
maxWidth = settings['chapter-marker-width-active']*100
maxHeight = settings['bar-height-active']*100
maxHeightFrac = settings['chapter-marker-active-height-fraction']
new: =>
super!
@line = { }
@markers = { }
@animation = Animation 0, 1, @animationDuration, @\animate
createMarkers: =>
@line = { }
@markers = { }
-- small number to avoid division by 0
totalTime = mp.get_property_number 'duration', 0.01
chapters = mp.get_property_native 'chapter-list', { }
markerHeight = @active and maxHeight*maxHeightFrac or BarBase.instantiatedBars[1].animationMinHeight
markerWidth = @active and maxWidth or minWidth
for chapter in *chapters
marker = ChapterMarker chapter.time/totalTime, markerWidth, markerHeight
table.insert @markers, marker
table.insert @line, marker\stringify!
@needsUpdate = true
reconfigure: =>
-- Need to call the UIElement reconfigure implementation, but can't use
-- super because calling the BarBase reconfigure on this class would break a
-- lot. This should probably not be a subclass of BarBase.
UIElement.reconfigure @
minWidth = settings['chapter-marker-width']*100
maxWidth = settings['chapter-marker-width-active']*100
maxHeight = settings['bar-height-active']*100
maxHeightFrac = settings['chapter-marker-active-height-fraction']
ChapterMarker\reconfigure!
@createMarkers!
@animation = Animation 0, 1, @animationDuration, @\animate
resize: =>
for i, marker in ipairs @markers
marker\resize!
@line[i] = marker\stringify!
@needsUpdate = true
animate: ( value ) =>
width = (maxWidth - minWidth)*value + minWidth
height = (maxHeight*maxHeightFrac - BarBase.instantiatedBars[1].animationMinHeight)*value + BarBase.instantiatedBars[1].animationMinHeight
for i, marker in ipairs @markers
marker\animate width, height
@line[i] = marker\stringify!
@needsUpdate = true
redraw: =>
super!
currentPosition = mp.get_property_number( 'percent-pos', 0 )*0.01
update = false
for i, marker in ipairs @markers
if marker\redraw currentPosition
@line[i] = marker\stringify!
update = true
return @needsUpdate or update
| 33.179104 | 140 | 0.728295 |
c9b803f9579ac5cb11540a72f2cee0d36cbb4fd0 | 314 | #!/usr/bin/env moon
import parse_args from require "pl.app"
import run from require "moonrocks.actions"
original_args = { k,v for k,v in pairs(arg) }
flags = parse_args!
params = [arg for arg in *{...} when not arg\match "^%-"]
flags.original_args = original_args
run params, flags
-- vim: set filetype=moon:
| 20.933333 | 57 | 0.703822 |
1316cf0d830f5039dceb8bd65007ef9c455ae3ac | 525 |
utils = require("utils")
import OdfFile from utils
HEIGHT_TOLERANCE = 5
NORMAL_TOLERANCE = 0.1
class Terrain
new: (filename) =>
@file = OdfFile(filename)
@minVec = SetVector(@file\getInt("Size", "MinX"), @file\getInt("Size", "Height"), @file\getInt("Size", "MinZ"))
@maxVec = @minVec + SetVector(@file\getInt("Size", "Width"), 0, @file\getInt("Size", "Depth"))
getSize: () =>
@maxVec - @minVec
getBoundary: () =>
return @minVec, @maxVec
return {
:Terrain
} | 19.444444 | 116 | 0.586667 |
06dc006cb21d23059cbd3fed4b0818c5764e4376 | 90 | {
test: (scene,name,x,y,z,object,layer) ->
return scene\newEntity "test",x,y,z,layer
}
| 18 | 43 | 0.655556 |
cd8ee403a1ea1aeccdfda152ee4f978a12a9c135 | 230 | System = require 'tinyx.System'
tiny = require 'tiny'
class ProcessingSystem extends System
new: =>
@ = tiny.processingSystem @
-- process: (e, dt) =>
-- preProcess: (dt) =>
-- postProcess: (dt) =>
ProcessingSystem
| 17.692308 | 37 | 0.63913 |
6c4b8264ca1f2d22ec93c2b595e96d61a4b6be33 | 5,952 | require "spec.helpers" -- for one_of
db = require "lapis.db.mysql"
schema = require "lapis.db.mysql.schema"
unpack = unpack or table.unpack
-- TODO: we can't test escape_literal with strings here because we need a
-- connection for escape function
value_table = { hello: db.FALSE, age: 34 }
tests = {
-- lapis.db.mysql
{
-> db.escape_identifier "dad"
'`dad`'
}
{
-> db.escape_identifier "select"
'`select`'
}
{
-> db.escape_identifier 'love`fish'
'`love``fish`'
}
{
-> db.escape_identifier db.raw "hello(world)"
"hello(world)"
}
{
-> db.escape_literal 3434
"3434"
}
{
-> db.interpolate_query "select * from cool where hello = ?", 123
"select * from cool where hello = 123"
}
{
-> db.encode_values(value_table)
[[(`hello`, `age`) VALUES (FALSE, 34)]]
[[(`age`, `hello`) VALUES (34, FALSE)]]
}
{
-> db.encode_assigns(value_table)
[[`hello` = FALSE, `age` = 34]]
[[`age` = 34, `hello` = FALSE]]
}
{
-> db.encode_assigns thing: db.NULL
[[`thing` = NULL]]
}
{
-> db.encode_clause thing: db.NULL
[[`thing` IS NULL]]
}
{
-> db.interpolate_query "update x set x = ?", db.raw"y + 1"
"update x set x = y + 1"
}
{
-> db.select "* from things where id = ?", db.TRUE
[[SELECT * from things where id = TRUE]]
}
{
-> db.insert "cats", age: 123, name: db.NULL
[[INSERT INTO `cats` (`name`, `age`) VALUES (NULL, 123)]]
[[INSERT INTO `cats` (`age`, `name`) VALUES (123, NULL)]]
}
{
-> db.update "cats", { age: db.raw"age - 10" }, "name = ?", db.FALSE
[[UPDATE `cats` SET `age` = age - 10 WHERE name = FALSE]]
}
{
-> db.update "cats", { color: db.NULL }, { weight: 1200, length: 392 }
[[UPDATE `cats` SET `color` = NULL WHERE `weight` = 1200 AND `length` = 392]]
[[UPDATE `cats` SET `color` = NULL WHERE `length` = 392 AND `weight` = 1200]]
}
{
-> db.delete "cats"
[[DELETE FROM `cats`]]
}
{
-> db.delete "cats", "name = ?", 777
[[DELETE FROM `cats` WHERE name = 777]]
}
{
-> db.delete "cats", name: 778
[[DELETE FROM `cats` WHERE `name` = 778]]
}
{
-> db.delete "cats", name: db.FALSE, dad: db.TRUE
[[DELETE FROM `cats` WHERE `name` = FALSE AND `dad` = TRUE]]
[[DELETE FROM `cats` WHERE `dad` = TRUE AND `name` = FALSE]]
}
{
-> db.truncate "dogs"
[[TRUNCATE `dogs`]]
}
-- lapis.db.mysql.schema
{
-> tostring schema.types.varchar
"VARCHAR(255) NOT NULL"
}
{
-> tostring schema.types.varchar 1024
"VARCHAR(1024) NOT NULL"
}
{
-> tostring schema.types.varchar primary_key: true, auto_increment: true
"VARCHAR(255) NOT NULL AUTO_INCREMENT PRIMARY KEY"
}
{
-> tostring schema.types.varchar null: true, default: 2000
"VARCHAR(255) DEFAULT 2000"
}
{
-> tostring schema.types.varchar 777, primary_key: true, auto_increment: true, default: 22
"VARCHAR(777) NOT NULL DEFAULT 22 AUTO_INCREMENT PRIMARY KEY"
}
{
-> tostring schema.types.varchar null: true, default: 2000, length: 88
"VARCHAR(88) DEFAULT 2000"
}
{
-> tostring schema.types.boolean
"TINYINT(1) NOT NULL"
}
{
-> tostring schema.types.id
"INT NOT NULL AUTO_INCREMENT PRIMARY KEY"
}
{
-> schema.create_index "things", "age"
"CREATE INDEX `things_age_idx` ON `things` (`age`);"
}
{
-> schema.create_index "things", "color", "height"
"CREATE INDEX `things_color_height_idx` ON `things` (`color`, `height`);"
}
{
-> schema.create_index "things", "color", "height", unique: true
"CREATE UNIQUE INDEX `things_color_height_idx` ON `things` (`color`, `height`);"
}
{
-> schema.create_index "things", "color", "height", unique: true, using: "BTREE"
"CREATE UNIQUE INDEX `things_color_height_idx` USING BTREE ON `things` (`color`, `height`);"
}
{
-> schema.drop_index "things", "age"
"DROP INDEX `things_age_idx` on `things`;"
}
{
-> schema.drop_index "items", "cat", "paw"
"DROP INDEX `items_cat_paw_idx` on `items`;"
}
{
-> schema.add_column "things", "age", schema.types.varchar 22
"ALTER TABLE `things` ADD COLUMN `age` VARCHAR(22) NOT NULL"
}
{
-> schema.drop_column "items", "cat"
"ALTER TABLE `items` DROP COLUMN `cat`"
}
{
-> schema.rename_column "items", "cat", "paw", schema.types.integer
"ALTER TABLE `items` CHANGE COLUMN `cat` `paw` INT NOT NULL"
}
{
-> schema.rename_table "goods", "sweets"
"RENAME TABLE `goods` TO `sweets`"
}
{
name: "schema.create_table"
->
schema.create_table "top_posts", {
{"id", schema.types.id}
{"user_id", schema.types.integer null: true}
{"title", schema.types.text null: false}
{"body", schema.types.text null: false}
{"created_at", schema.types.datetime}
{"updated_at", schema.types.datetime}
}
[[CREATE TABLE `top_posts` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`user_id` INT,
`title` TEXT NOT NULL,
`body` TEXT NOT NULL,
`created_at` DATETIME NOT NULL,
`updated_at` DATETIME NOT NULL
) CHARSET=UTF8;]]
}
{
name: "schema.create_table not exists"
->
schema.create_table "tags", {
{"id", schema.types.id}
{"tag", schema.types.varchar}
}, if_not_exists: true
[[CREATE TABLE IF NOT EXISTS `tags` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`tag` VARCHAR(255) NOT NULL
) CHARSET=UTF8;]]
}
}
local old_query_fn
describe "lapis.db.mysql", ->
setup ->
old_query_fn = db.set_backend "raw", (q) -> q
teardown ->
db.set_backend "raw", old_query_fn
for group in *tests
name = "should match"
if group.name
name ..= " #{group.name}"
it name, ->
output = group[1]!
if #group > 2
assert.one_of output, { unpack group, 2 }
else
assert.same group[2], output
| 22.126394 | 96 | 0.585853 |
175d6876251a01f7991c865d4687ea8527175c85 | 1,406 | -- Options
OptCaseSensitive=true
-- End of options
F=far.Flags
color = far.AdvControl(F.ACTL_GETCOLOR, far.Colors.COL_EDITORTEXT)
color.ForegroundColor, color.BackgroundColor = color.BackgroundColor, color.ForegroundColor
colorguid=win.Uuid "507CFA2A-3BA3-4f2b-8A80-318F5A831235"
words={}
Macro
area:"Editor"
key:"F5"
description:"Color Word Under Cursor"
action:->
ei=editor.GetInfo!
id=ei.EditorID
if words[id] then words[id]=nil
else
pos=ei.CurPos
line=editor.GetString!.StringText
if pos<=line\len()+1
slab=pos>1 and line\sub(1,pos-1)\match('[%w_]+$') or ""
tail=line\sub(pos)\match('^[%w_]+') or ""
if slab~="" or tail~="" then words[id]=OptCaseSensitive and slab..tail or (slab..tail)\lower!
Event
group:"EditorEvent"
action:(id,event,param)->
if event==F.EE_REDRAW
if words[id]
ei=editor.GetInfo id
start,finish=ei.TopScreenLine,math.min ei.TopScreenLine+ei.WindowSizeY,ei.TotalLines
for ii=start,finish
line,pos=editor.GetString(id,ii).StringText,1
while true
jj,kk,curr=line\cfind("([%w_]+)",pos)
if not jj then break
if not OptCaseSensitive then curr=curr\lower!
if curr==words[id] then editor.AddColor id,ii,jj,kk,F.ECF_AUTODELETE,color,100,colorguid
pos=kk+1
elseif event==F.EE_CLOSE then words[id]=nil
| 32.697674 | 101 | 0.657183 |
dfdfa9865c33d969e521c72fb1477e9f1f8bfdc0 | 176 | ifoldr = zb2rhcw9WTW6XGdppMfUnQGz2na5VoCJRmjWyFAHkXaRHgDxs
separator =>
(ifoldr
i => a => b =>
sep = (if (eql i 0) "" separator)
(con (con sep a) b)
"")
| 19.555556 | 58 | 0.585227 |
926128bbabc3f2329ecef8b5c383741584d5ce96 | 135 | foldr = zb2rhbTuYiZm5fGUHUhd3sQNRDhEW6FVjXLp8UyWk5hE9nQ5F
concat = zb2rhen9kLmNpH8Tt7ASAjV3ws1EYDeqXYG1Us5AWyHc7qiX5
(foldr concat [])
| 33.75 | 58 | 0.888889 |
0dfa9c47cd3d7f2e3fbfc8e88549b8e9c8e5c381 | 1,007 | -- Copyright 2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import style, StyledText from howl.ui
icons = {}
style_name = (icon_name) -> '_icon_font_'..icon_name
define = (name, definition={}) ->
unless definition.text or type(definition) == 'string'
error "Definition must be string or contain field 'text'"
if type(definition) == 'string'
icons[name] = definition
else
style.define style_name(name),
font: definition.font
icons[name] = {:name, text: definition.text, font: definition.font}
define_default = (name, definition) ->
define(name, definition) unless icons[name]
get = (name, icon_style = 'icon') ->
icon = name
while type(icon) == 'string'
name = icon
icon = icons[name]
error "Invalid icon '#{name}'", 2 unless icon
icon_style = style_name(name) .. ':' .. icon_style
text = icon.text
return StyledText(text, {1, icon_style, #text + 1})
{
:define
:define_default
:get
}
| 25.820513 | 79 | 0.673287 |
187993f95e6aa12af2dfb294b6fcf261b9d99b16 | 1,320 | discount = require "discount"
lapis = require "lapis"
file = require "pl.file"
oleg = require "lib/oleg"
path = require "pl.path"
postutil = require "lib/post"
stringx = require "pl.stringx"
util = require "lapis.util"
dir = require "pl.dir"
split = require "util"
class Blog extends lapis.Application
["blog.index": "/blog"]: =>
@doc = oleg.cache "caches", "blog-index", ->
local data
with io.open "static/markdown/blog.html", "r"
data = \read "*a"
\close!
data
@title = "Blog"
@page = "blog"
render: true
["blog.post": "/blog/:name"]: =>
@name = util.slugify @params.name
unless path.exists "blog/#{@name}.markdown"
return render: "notfound", status: 404
@doc = oleg.cache "blogposts", @name, ->
local data
do
fin = io.open "blog/#{@name}.markdown", "r"
fin\read "*l"
fin\read "*l"
fin\read "*l"
data = fin\read "*a"
fin\close!
discount data, "toc", "nopants", "autolink"
with io.open "blog/#{@name}.markdown", "r"
@title = \read "*l"
\close!
@page = "blog"
render: true
["blog.rss": "/blog.rss"]: =>
@posts = postutil.getPosts!
render: true, layout: false, content_type: "application/rss+xml; charset=UTF-8" | 23.571429 | 83 | 0.561364 |
665e6f34cbd6ba5a24471353780f59f7c195af45 | 1,354 | import Widget from require "lapis.html"
config = (require "lapis.config").get!
class RegisterWithKey extends Widget
content: =>
h1 "Register account"
form action: @url_for("lazuli_modules_usermanagement_register_do"), method: "post", class: "pure-form pure-form-aligned", ->
input type: "hidden", name: "csrf_token", value: @modules.user_management.csrf_token
fieldset ->
div class: "pure-control-group", ->
label for: "username", "Username:"
input id: "username",name: "username", value: @params.uname or "", readonly: @params.uname and "readonly" or nil
div class: "pure-control-group", ->
label for: "password", "Password:"
input id: "password", type: "password", name: "password"
div class: "pure-control-group", ->
label for: "password_repeat", "Repeat:"
input id: "password_repeat", type: "password",name: "password_repeat"
if config.projectStage=="alpha" or config.projectStage=="beta"
div class: "pure-control-group", ->
label for: "key", "Invitation Key ("..config.projectStage.."):"
input id: "key", name: "key", value: @params.key or "", readonly: @params.key and "readonly" or nil
div class: "pure-controls", ->
input type: "submit", class: "pure-button pure-button-primary"
| 54.16 | 128 | 0.631462 |
882566e1d134244489b82838c74f4bbe3a690546 | 1,593 | export ^
love.graphics.setDefaultFilter "nearest", "nearest"
Gamera = require "lib.gamera"
Flux = require "lib.flux"
St8 = require "lib.st8"
Vec = require "lib.hump-vec"
Sti = require "lib.sti"
Bump = require "lib.bump"
import Sprite, Animation from require "sprites"
import Sound from require "sound"
SCREEN = Vec!
math.randomseed os.time!
for i=1,10 do math.random!
table.find = (val) =>
for i,v in ipairs self
return i if v == val
nil
table.insert = do
_insert = table.insert
(a, b) =>
if b
_insert @, a, b
b
else
_insert @, a
a
math.clamp = (val, min, max) ->
return math.max math.min(val, max or (-min)), min
math.sign = (val) ->
if val > 0 then 1 else -1
math.choice = (table, ...) ->
if type(table) ~= "table"
table = {table, ...}
return table[math.random #table]
math.raddiff = (a, b) ->
if math.abs(b - a) <= math.pi
b-a
elseif b >= a
b - a - math.pi*2
else
b - a + math.pi*2
math.floor = do
_floor = math.floor
(...) ->
unpack [_floor select i, ... for i=1, select "#", ...]
love.resize = (w, h) ->
SCREEN = Vec w, h
love.load = ->
SCREEN = Vec love.graphics.getDimensions!
love.graphics.setNewFont "assets/font.ttf", 18
St8.order "draw", "bottom"
St8.init require "states.intro"
St8.pause require("states.game")! if arg[#arg] == "game"
Sound.hit, Sound.mutate, Sound.demutate -- preload these
Sound[fullname: "surreal-palace.mp3", typ: "stream"]!\setLooping true
love.mouse.setGrabbed true
love.update = (dt) ->
Flux.update dt
| 20.423077 | 71 | 0.605775 |
66a63cafb243d66fa13c1cfdcb94f609d5e9945c | 2,097 | ffi = require "ffi"
import JPG, has_loaded, version from require "ZJPG.turbojpeg"
import BUFFER from require "ZF.img.buffer"
-- https://github.com/koreader/koreader-base/tree/master/ffi
class LIBJPG
version: "1.0.1"
new: (@filename = filename) =>
unless has_loaded
libError "libjpeg-turbo"
read: =>
file = io.open @filename, "rb"
assert file, "Couldn't open JPEG file"
@rawData = file\read "*a"
file\close!
setArguments: =>
@width = ffi.new "int[1]"
@height = ffi.new "int[1]"
@jpegSubsamp = ffi.new "int[1]"
@colorSpace = ffi.new "int[1]"
decode: (gray) =>
@read!
handle = JPG.tjInitDecompress!
assert handle, "no TurboJPEG API decompressor handle"
@setArguments!
JPG.tjDecompressHeader3 handle, ffi.cast("const unsigned char*", @rawData), #@rawData, @width, @height, @jpegSubsamp, @colorSpace
assert @width[0] > 0 and @height[0] > 0, "Image dimensions"
buffer = gray and BUFFER(@width[0], @height[0], 1) or BUFFER @width[0], @height[0], 4
format = gray and JPG.TJPF_GRAY or JPG.TJPF_RGB
err = JPG.tjDecompress2(handle, ffi.cast("unsigned char*", @rawData), #@rawData, ffi.cast("unsigned char*", buffer.data), @width[0], buffer.pitch, @height[0], format, 0) == -1
assert not err, "Decoding error"
JPG.tjDestroy handle
@rawData = buffer
@width = buffer\get_width!
@height = buffer\get_height!
@bit_depth = buffer\get_bpp!
@getPixel = (x, y) => buffer\get_pixel x, y
@getData = =>
@data = ffi.new "color_RGBA[?]", @width * @height
for y = 0, @height - 1
for x = 0, @width - 1
i = y * @width + x
with @getPixel(x, y)\get_color_32!
@data[i].r = .r
@data[i].g = .g
@data[i].b = .b
@data[i].a = .alpha
return @data
return @
{:LIBJPG} | 29.957143 | 183 | 0.53505 |
f9f9de0799c13a81bdc563aedd6031d69a3445d9 | 6,271 |
-- 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.
-- CTakeDamageInfo/AddDamage
-- CTakeDamageInfo/GetAmmoType
-- CTakeDamageInfo/GetAttacker
-- CTakeDamageInfo/GetBaseDamage
-- CTakeDamageInfo/GetDamage
-- CTakeDamageInfo/GetDamageBonus
-- CTakeDamageInfo/GetDamageCustom
-- CTakeDamageInfo/GetDamageForce
-- CTakeDamageInfo/GetDamagePosition
-- CTakeDamageInfo/GetDamageType
--
-- CTakeDamageInfo/GetInflictor
-- CTakeDamageInfo/GetMaxDamage
-- CTakeDamageInfo/GetReportedPosition
-- CTakeDamageInfo/IsBulletDamage
-- CTakeDamageInfo/IsDamageType
-- CTakeDamageInfo/IsExplosionDamage
-- CTakeDamageInfo/IsFallDamage
-- CTakeDamageInfo/ScaleDamage
-- CTakeDamageInfo/SetAmmoType
-- CTakeDamageInfo/SetAttacker
--
-- CTakeDamageInfo/SetDamage
-- CTakeDamageInfo/SetDamageBonus
-- CTakeDamageInfo/SetDamageCustom
-- CTakeDamageInfo/SetDamageForce
-- CTakeDamageInfo/SetDamagePosition
-- CTakeDamageInfo/SetDamageType
-- CTakeDamageInfo/SetInflictor
-- CTakeDamageInfo/SetMaxDamage
-- CTakeDamageInfo/SetReportedPosition
-- CTakeDamageInfo/SubtractDamage
damageTypes = {
{DMG_CRUSH, 'Crush'},
{DMG_BULLET, 'Bullet'},
{DMG_SLASH, 'Slash'},
{DMG_SLASH, 'Slashing'},
{DMG_BURN, 'Burn'},
{DMG_BURN, 'Fire'},
{DMG_BURN, 'Flame'},
{DMG_VEHICLE, 'Vehicle'},
{DMG_FALL, 'Fall'},
{DMG_BLAST, 'Blast'},
{DMG_CLUB, 'Club'},
{DMG_SHOCK, 'Shock'},
{DMG_SONIC, 'Sonic'},
{DMG_ENERGYBEAM, 'EnergyBeam'},
{DMG_ENERGYBEAM, 'Laser'},
{DMG_DROWN, 'Drown'},
{DMG_PARALYZE, 'Paralyze'},
{DMG_NERVEGAS, 'Gaseous'},
{DMG_NERVEGAS, 'NergeGas'},
{DMG_NERVEGAS, 'Gas'},
{DMG_POISON, 'Poision'},
{DMG_ACID, 'Acid'},
{DMG_AIRBOAT, 'Airboat'},
{DMG_BUCKSHOT, 'Buckshot'},
{DMG_DIRECT, 'Direct'},
{DMG_DISSOLVE, 'Dissolve'},
{DMG_DROWNRECOVER, 'DrownRecover'},
{DMG_PHYSGUN, 'Physgun'},
{DMG_PLASMA, 'Plasma'},
{DMG_RADIATION, 'Radiation'},
{DMG_SLOWBURN, 'Slowburn'},
}
class DLib.LTakeDamageInfo
for {dtype, dname} in *damageTypes
@__base['Is' .. dname .. 'Damage'] = => @IsDamageType(dtype)
TypesArray: => [dtype for {dtype, dname} in *damageTypes when @IsDamageType(dtype)]
@__base.MetaName = 'LTakeDamageInfo'
new: (copyfrom) =>
@damage = 0
@baseDamage = 0
@maxDamage = 0
@ammoType = 0
@damageBonus = 0
@damageCustomFlags = 0
@damageForce = Vector()
@reportedPosition = Vector()
@damagePosition = Vector()
@damageType = DMG_GENERIC
@attacker = NULL
@inflictor = NULL
@recordedInflictor = NULL
DLib.LTakeDamageInfo.CopyInto(copyfrom, @) if copyfrom
RecordInflictor: =>
if @inflictor ~= @attacker or not @attacker.GetActiveWeapon
@recordedInflictor = @inflictor
return
weapon = @attacker\GetActiveWeapon()
if not IsValid(weapon)
@recordedInflictor = @inflictor
return
@recordedInflictor = weapon
AddDamage: (damageNum = 0) => @damage = math.clamp(@damage + damageNum, 0, 0x7FFFFFFF)
SubtractDamage: (damageNum = 0) => @damage = math.clamp(@damage - damageNum, 0, 0x7FFFFFFF)
GetDamageType: => @damageType
GetAttacker: => @attacker
GetInflictor: => @inflictor
GetRecordedInflictor: => @recordedInflictor
GetBaseDamage: => @damage
GetAmmoType: => @ammoType
GetDamage: => @damage
GetDamageBonus: => @damageBonus
GetDamageCustom: => @damageCustomFlags
GetDamageForce: => @damageForce
GetDamagePosition: => @damagePosition
GetReportedPosition: => @reportedPosition
GetDamageForce: => @damageForce
GetDamageType: => @damageType
GetMaxDamage: => @maxDamage
GetBaseDamage: => @baseDamage
IsDamageType: (dtype) => @damageType\band(dtype) == dtype
IsBulletDamage: => @IsDamageType(DMG_BULLET)
IsExplosionDamage: => @IsDamageType(DMG_BLAST)
IsFallDamage: => @IsDamageType(DMG_FALL)
ScaleDamage: (scaleBy) => @damage = math.clamp(@damage * scaleBy, 0, 0x7FFFFFFF)
SetAmmoType: (ammotype) => @ammoType = ammotype
SetAttacker: (attacker) => @attacker = assert(isentity(attacker) and attacker, 'Invalid attacker')
SetInflictor: (attacker) => @inflictor = assert(isentity(attacker) and attacker, 'Invalid inflictor')
SetRecordedInflictor: (attacker) => @recordedInflictor = assert(isentity(attacker) and attacker, 'Invalid recorded inflictor')
SetDamage: (dmg) => @damage = math.clamp(dmg, 0, 0x7FFFFFFF)
SetDamageBonus: (dmg) => @damageBonus = math.clamp(dmg, 0, 0x7FFFFFFF)
SetMaxDamage: (dmg) => @maxDamage = math.clamp(dmg, 0, 0x7FFFFFFF)
SetDamageCustom: (dmg) => @damageCustomFlags = dmg
SetDamageType: (dmg) => @damageType = dmg
SetDamagePosition: (pos) => @damagePosition = pos
SetReportedPosition: (pos) => @reportedPosition = pos
SetDamageForce: (force) => @damageForce = force
SetBaseDamage: (damage) => @baseDamage = damage
Copy: => DLib.LTakeDamageInfo(@)
DLib.LTakeDamageInfo.CopyInto = (objectSource, self) ->
with objectSource
@SetAmmoType(\GetAmmoType())
@SetAttacker(\GetAttacker())
@SetBaseDamage(\GetBaseDamage()) if @SetBaseDamage and .SetBaseDamage
@SetDamage(\GetDamage())
@SetDamageBonus(\GetDamageBonus())
@SetDamageCustom(\GetDamageCustom())
@SetDamageForce(\GetDamageForce())
@SetDamagePosition(\GetDamagePosition())
@SetDamageType(\GetDamageType())
@SetInflictor(\GetInflictor())
@SetMaxDamage(\GetMaxDamage())
@SetReportedPosition(\GetReportedPosition())
return self
| 34.456044 | 127 | 0.743582 |
8858d05b78182d78d16d2d340aa464dfab4ad5d4 | 43 | e.house = { "position", "size", "sprite" }
| 21.5 | 42 | 0.55814 |
726381c5cb3a22f4709a84344cb5f3408713891a | 275 | monitor_dimensions!
mainPage = MainPage!
mp.add_key_binding(options.keybind, "display-webm-encoder", mainPage\show, {repeatable: false})
mp.register_event("file-loaded", mainPage\setupStartAndEndTimes)
msg.verbose("Loaded mpv-webm script!")
emit_event("script-loaded") | 39.285714 | 96 | 0.785455 |
08ed682bb1bb39b4a2ed8b332d470230a76f5820 | 692 | M = {}
me = ...
split = (str, symbol="%s") -> [x for x in string.gmatch(str, "([^"..symbol.."]+)")]
root1 = (split me, ".")[1]
tail = require(root1..".".."._lists._tail")["tail"]
-- append an item a list
M.append = (list, ...) ->
items = {...}
return list if #items == 0
return items if (type list) != "table" and #items != 0
return table if (type list) == "table" and #items == 0
return {} if (type list) != "table" and #items == 0
-- note: a = b in Lua means let a have the address of list b
-- Thus deep copy must be done explicitly
output = [x for x in *list]
for item in *items
output[#output+1] = item
return output
return M | 32.952381 | 83 | 0.550578 |
5f1b1b161df7237ad3bda04208c292be243fd862 | 1,307 | module "moonscript.compile", package.seeall
util = require "moonscript.util"
data = require "moonscript.data"
import itwos from util
import Set, ntype from data
import concat, insert from table
export indent_char, default_return, moonlib, cascading, non_atomic, has_value, is_non_atomic
export count_lines, is_slice, user_error
indent_char = " "
user_error = (...) ->
error {"user-error", ...}
manual_return = Set{"foreach", "for", "while"}
default_return = (exp) ->
t = ntype exp
if t == "chain" and exp[2] == "return"
-- extract the return
items = {"explist"}
insert items, v for v in *exp[3][2]
{"return", items}
elseif manual_return[t]
exp
else
{"return", exp}
moonlib =
bind: (tbl, name) ->
concat {"moon.bind(", tbl, ".", name, ", ", tbl, ")"}
cascading = Set{ "if", "with" }
-- an action that can't be completed in a single line
non_atomic = Set{ "update" }
-- does this always return a value
has_value = (node) ->
if ntype(node) == "chain"
ctype = ntype(node[#node])
ctype != "call" and ctype != "colon"
else
true
is_non_atomic = (node) ->
non_atomic[ntype(node)]
is_slice = (node) ->
ntype(node) == "chain" and ntype(node[#node]) == "slice"
count_lines = (str) ->
count = 1
count += 1 for _ in str\gmatch "\n"
count
| 21.783333 | 92 | 0.635807 |
bfc82f5b6024bf010cf9e990c9f2d5a0c557e54b | 359 | -- typekit.parser.error
-- Error reporting for the parser
import style from require "ansikit.style"
typeError = (msg, details={}) ->
print style "%{bold red}typekit (type) $%{notBold} #{msg}"
if #details > 0
print style "%{ red}=============================="
for detail in *details
print style "%{ } #{detail}"
error!
{ :typeError } | 27.615385 | 60 | 0.573816 |
5af06a706bafee81e5aefaf10b92027be2d0100d | 418 |
class Util
replace_special_chars: (str) ->
return vim.api.nvim_replace_termcodes(str, true, false, true)
-- Similar to vim.cmd('normal! x')
normal_bang: (keys) ->
vim.api.nvim_feedkeys(
Util.replace_special_chars(keys), 'nx', true)
-- recursive version of normal
-- aka vim.cmd('normal x')
rnormal: (keys) ->
vim.api.nvim_feedkeys(
Util.replace_special_chars(keys), 'mx', true)
| 24.588235 | 65 | 0.667464 |
0ff0deb02177c6e00ee6d0243f71358ce05cbaba | 293 | -- international phonetic alphabet
{:simplehttp, :urlEncode, :json} = require'util'
PRIVMSG:
'^%pipa (.*)$': (source, destination, input) =>
simplehttp "http://rhymebrain.com/talk?function=getWordInfo&word=#{urlEncode input}", (data) ->
data = json.decode(data)
say data.ipa
| 36.625 | 99 | 0.668942 |
72bbc9a508b4fedb737bec432a2ca449d384490f | 660 | -- Copyright 2018 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
require 'ljglibs.cdefs.glib'
core = require 'ljglibs.core'
{ :catch_error } = require 'ljglibs.glib'
C, ffi_gc = ffi.C, ffi.gc
core.define 'GMappedFile', {
properties: {
length: => tonumber C.g_mapped_file_get_length @
contents: => C.g_mapped_file_get_contents @
}
new: (path, writable = false) ->
ffi_gc catch_error(C.g_mapped_file_new, path, writable), C.g_mapped_file_unref
unref: =>
ffi_gc @, nil
C.g_mapped_file_unref @
meta: {
__len: => @.length
}
}, (t, ...) -> t.new ...
| 22.758621 | 82 | 0.666667 |
4dde9709b579a841d22b0468d8cd14382a287efb | 5,562 | {:delegate_to} = howl.util.table
background = '#002451'
current = '#00346e'
selection = '#0066cc'
foreground = '#ffffff'
comment = '#7285b7'
red = '#ff9da4'
orange = '#ffc58f'
yellow = '#ffeead'
green = '#d1f1a9'
aqua = '#99ffff'
blue = '#bbdaff'
purple = '#ebbbff'
border_color = '#333333'
embedded_bg = '#25384f'
-- General styling for context boxes (editor, command_line)
content_box = {
background:
color: background
border:
width: 1
color: border_color
border_right:
width: 3
color: border_color
border_bottom:
width: 3
color: border_color
header:
background:
gradient:
type: 'linear'
direction: 'horizontal'
stops: { '#000022', '#003080' }
border_bottom:
color: border_color
color: brown
font: bold: true
padding: 1
footer:
background:
color: '#002471'
border_top:
color: border_color
color: brown
font: bold: true
padding: 1
}
return {
window:
background:
image:
path: theme_file('dark_back.png')
status:
font: bold: true, italic: true
color: grey
info: color: blue
warning: color: orange
'error': color: red
:content_box
popup:
background:
color: '#00346e'
editor: delegate_to content_box, {
scrollbars:
slider:
color: '#00549e'
indicators:
default:
color: blue
title:
font: bold: true, italic: true
vi:
color: purple
current_line:
background: current
gutter:
color: comment
background:
color: background
alpha: 0.4
}
flairs:
indentation_guide:
type: flair.PIPE,
foreground: comment,
:background,
line_width: 1
indentation_guide_1:
type: flair.PIPE,
foreground: blue,
foreground_alpha: 0.5
line_width: 1
indentation_guide_2:
type: flair.PIPE,
foreground: green,
foreground_alpha: 0.5
line_width: 1
indentation_guide_3:
type: flair.PIPE,
foreground: green,
foreground_alpha: 0.3
line_width: 1
edge_line:
type: flair.PIPE,
foreground: blue,
foreground_alpha: 0.3,
line_width: 0.5
search:
type: highlight.ROUNDED_RECTANGLE
foreground: black
foreground_alpha: 1
background: green
text_color: darkgreen
height: 'text'
search_secondary:
type: flair.ROUNDED_RECTANGLE
background: lightblue
text_color: black
height: 'text'
replace_strikeout:
type: flair.ROUNDED_RECTANGLE
foreground: black
background: red
text_color: black
height: 'text'
brace_highlight:
type: flair.RECTANGLE
text_color: foreground
background: '#0064b1'
height: 'text'
brace_highlight_secondary:
type: flair.RECTANGLE
foreground: '#0064b1'
text_color: foreground
line_width: 1
height: 'text'
list_selection:
type: flair.RECTANGLE
background: white
background_alpha: 0.4
list_highlight:
type: highlight.UNDERLINE
foreground: white
text_color: white
line_width: 2
cursor:
type: flair.RECTANGLE
background: foreground
width: 2
height: 'text'
block_cursor:
type: flair.ROUNDED_RECTANGLE,
background: foreground
text_color: background
height: 'text',
min_width: 'letter'
selection:
type: highlight.ROUNDED_RECTANGLE
background: selection
background_alpha: 0.6
min_width: 'letter'
styles:
default:
color: foreground
red: color: red
green: color: green
yellow: color: yellow
blue: color: blue
magenta: color: purple
cyan: color: aqua
popup:
background: '#00346e'
color: foreground
comment:
font: italic: true
color: comment
variable: color: yellow
label:
color: orange
font: italic: true
key:
color: blue
font: bold: true
fdecl:
color: blue
font: bold: true
keyword:
color: purple
font: bold: true
class:
color: yellow
font: bold: true
type_def:
color: yellow
font:
bold: true
size: 'large'
family: 'Purisa,Latin Modern Sans'
definition: color: yellow
function:
color: blue
font: bold: true
char: color: green
number: color: orange
operator: color: aqua
preproc: color: aqua
special: color: purple
tag: color: purple
type: color: yellow
member: color: red
info: color: blue
constant:
color: yellow
string: color: green
regex:
color: green
background: embedded_bg
embedded:
color: '#aadaff'
background: embedded_bg
-- Markup and visual styles
error:
font: italic: true
color: white
background: darkred
warning:
font: italic: true
color: orange
h1:
color: white
background: '#005491'
h2:
color: green
font: bold: true
h3:
color: purple
background: current
font: italic: true
emphasis:
font:
bold: true
italic: true
strong: font: italic: true
link_label: color: aqua
link_url: color: comment
table:
color: blue
background: embedded_bg
underline: true
addition: color: green
deletion: color: red
change: color: yellow
}
| 17.273292 | 59 | 0.593671 |
5aee5a950c4a183bb02b28b33f830e71e84900f4 | 733 | fill_inv = ->
for i=1,16
turtle.select i
turtle.suck!
dump_inv = ->
for i=1,16
turtle.select i
turtle.dropDown!
running = true
print "Good day to you! I'm ready to ferry your goods between two stations."
while running
if turtle.detect!
print "Dumping inventory..."
dump_inv!
if turtle.getFuelLevel! < 1000
print "Fuel low, refueling..."
turtle.suckUp!
turtle.refuel!
io.write "Refueled. Fuel level: "
print turtle.getFuelLevel!
print "Filling inventory..."
fill_inv!
turtle.turnLeft!
turtle.turnLeft!
print "And I'm off!"
while not turtle.detect!
turtle.forward!
| 24.433333 | 76 | 0.57708 |
0da14c586f1389f284aa1f06b5b634fc3597dc17 | 196 | moonbuild = require 'moonbuild'
tasks:
build: => moonbuild j: true
run: => moonbuild 'run', j: true
clean: => moonbuild 'clean'
mrproper: => moonbuild 'mrproper'
defs: => moonbuild 'fnlist'
| 21.777778 | 34 | 0.673469 |
50d8193a79f343f661b6aed5d24b0f7c08e759c0 | 2,648 |
import insert from table
local *
config_cache = {} -- the final merged config by environment
configs = {} -- lists of fns/tables to build config by environment
default_config = {
port: "8080"
secret: "please-change-me"
session_name: "lapis_session"
code_cache: "off"
num_workers: "1"
logging: {
queries: true
requests: true
}
}
merge_set = (t, k, v) ->
existing = t[k]
if type(v) == "table"
if type(existing) != "table"
existing = {}
t[k] = existing
for sub_k, sub_v in pairs v
merge_set existing, sub_k, sub_v
else
t[k] = v
set = (conf, k, v) ->
if type(k) == "table"
for sub_k, sub_v in pairs k
merge_set conf, sub_k, sub_v
else
if type(v) == "function"
conf[k] = run_with_scope v, {}
else
merge_set conf, k, v
scope_meta = {
__index: (name) =>
val = _G[name]
return val unless val == nil
with val = switch name
when "set"
(...) -> set @_conf, ...
when "unset"
(...) ->
for k in *{...}
@_conf[k] = nil
when "include"
(fn) -> run_with_scope fn, @_conf
else
(v) -> set @_conf, name, v
@[name] = val
}
config = (environment, fn) ->
if type(environment) == "table"
for env in *environment
config env, fn
return
configs[environment] or= {}
table.insert configs[environment], fn
nil
reset = (env) ->
if env == true
for k in pairs configs
configs[k] = nil
for k in pairs config_cache
config_cache[k] = nil
else
configs[env] = nil
config_cache[env] = nil
run_with_scope = (fn, conf) ->
old_env = getfenv fn
env = setmetatable { _conf: conf }, scope_meta
setfenv fn, env
fn!
setfenv fn, old_env
conf
get_env = ->
os.getenv"LAPIS_ENVIRONMENT" or require("lapis.cmd.util").default_environment!
get = do
loaded_config = false
(name=get_env!) ->
error "missing environment name" unless name
unless loaded_config
loaded_config = true
success, err = pcall -> require "config"
unless success or err\match "module 'config' not found"
error err
return config_cache[name] if config_cache[name]
conf = { k,v for k,v in pairs(default_config) }
conf._name = name
if fns = configs[name]
for fn in *fns
switch type(fn)
when "function"
run_with_scope fn, conf
when "table"
set conf, fn
config_cache[name] = conf
conf
setmetatable {
:get, :config, :merge_set, :default_config, :reset
}, {
__call: (...) => config ...
}
| 20.850394 | 80 | 0.577039 |
7801c9cd94b11cb63529e594bf6447750f10c78a | 2,160 | Vector = req(..., 'lib.geo.vector')
moon = require('moon')
Enum = req(..., 'lib.enum')
_ = req(..., 'lib.lodash')
class Direction extends Vector
@headings: { 'EAST', 'SOUTH_EAST', 'SOUTH', 'SOUTH_WEST', 'WEST', 'NORTH_WEST', 'NORTH', 'NORTH_EAST' }
---
-- Gets the closest heading for a vector
--
-- @method getHeadingName
-- @static
-- @param {Vector} vector
-- @param {Boolean} [allowIntermediate=false] - Whether to return intermediate headings
-- @return {StdDirection}
--
@getHeadingName: (vector, allowIntermediate = false) =>
if not vector or vector.x == 0 and vector.y == 0 then return 'NONE'
angle = math.atan2(vector.y, vector.x)
octants = if allowIntermediate then 8 else 4
octant = _.round(octants * angle / (2 * math.pi) + octants) % octants
if octants == 4 then octant *= 2
octant += 1
return @headings[octant]
---
-- Aligns a vector to the closest standard heading
--
-- @method align
-- @static
-- @param {Vector} vector
-- @param {Boolean} [allowIntermediate=false] - Whether to return intermediate headings
-- @return {Vector} - A new vector with the same magnitude, but aligned to a standard direction
--
@align: (vector, allowIntermediate = false) =>
heading = @getHeadingName(vector, allowIntermediate)
return Vector(@[heading], #vector)
---
-- Returns whether a vector is a standard direction
--
-- @method isStandard
-- @static
-- @param {Vector} vector
-- @return {Boolean}
--
@isStandard: (vector) =>
x = math.abs(vector.x)
y = math.abs(vector.y)
return (x == 1 or x == 0) and (y == 1 or y == 0)
new: (x, y) =>
-- @param {String}
if _.isString(x)
direction = @@[x]
x = direction.x
y = direction.y
-- @param {Vector}
if _.isTable(x) then y = 1
super(x, y)
length = #@
if length != 0 and length != 1 then @normalize()
toVector: () => Vector(@x, @y)
moon.mixin(Direction, Enum, {
NORTH: Direction(0, -1),
SOUTH: Direction(0, 1),
WEST: Direction(-1, 0),
EAST: Direction(1, 0),
NORTH_WEST: Direction(-1, -1),
NORTH_EAST: Direction(1, -1),
SOUTH_WEST: Direction(-1, 1),
SOUTH_EAST: Direction(1, 1),
NONE: Direction(0, 0)
})
return Direction
| 25.714286 | 104 | 0.641667 |
0985834b610ffd7e5eba43dc34d46efa6566d4aa | 160 | M = {}
__ = ...
case = require __.."._".."case"
M.main = () ->
case.main {"a/b/c"}, {"a/b"}, "case 1"
case.main {"a\\b\\c"}, {"a\\b"}, "case 2"
return M | 22.857143 | 45 | 0.43125 |
e40ef784f2302fd13d3823ef036bf1cc337b5dd4 | 1,580 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import style from howl.ui
style.define 'jade_element', 'keyword'
style.define 'jade_id', 'constant'
howl.aux.lpeg_lexer ->
dq_string = capture 'string', span('"', '"', '\\')
-- sq_string = capture 'string', span("'", "'")
-- string = any dq_string, sq_string
blank_plus = capture 'whitespace', space^1
blank = capture 'whitespace', space^0
ident = alpha^1 * any(digit, alpha)^0
indented_text_block = capture('operator', '.') * capture('default', scan_through_indented!)
js_eval_to_eol = capture('operator', P'!'^-1 * '=') * blank * sub_lex('javascript', eol)
id = capture 'jade_id', "#" * ident
clz = capture('class', '.' * ident)
attribute = sequence {
blank,
capture('key', alpha^1 * any(digit, alpha, S'_-')^0),
blank,
capture('operator', '='),
blank,
dq_string
}
attr_delimiter = any {
blank_plus,
sequence {
blank,
capture('operator', ','),
blank
}
}
attributes = sequence {
capture('operator', '('),
(attribute * (attr_delimiter * attribute)^0)^0,
capture('operator', ')')^-1
}
element = sequence {
line_start,
blank,
capture('jade_element', ident),
any(id, clz)^-1,
attributes^-1,
any({
indented_text_block,
js_eval_to_eol
})^-1
}
operator = sequence {
line_start,
blank,
capture('operator', S'|=')
}
any {
element,
line_start * blank * js_eval_to_eol
operator,
}
| 22.253521 | 93 | 0.605063 |
82251135d8136ab0b634f0b84edfd8d6df7ee270 | 5,628 | import Buffer from howl
describe 'BufferMarkers', ->
local buffer, markers
names = (ms) ->
n = [m.name for m in *ms]
table.sort n
n
before_each ->
buffer = Buffer {}
markers = buffer.markers
describe 'add(markers)', ->
it 'raises an error if <.name> is missing', ->
assert.raises 'name', -> markers\add { {start_offset: 1, end_offset: 2} }
it 'raises an error if <.start_offset> is missing', ->
buffer.text = '12'
assert.raises 'start_offset', -> markers\add { {name: 'test', end_offset: 2} }
it 'raises an error if <.end_offset> is missing', ->
buffer.text = '12'
assert.raises 'end_offset', -> markers\add { {name: 'test', start_offset: 2} }
it 'raises an error if <.start_offset> is out of bounds', ->
buffer.text = '12'
assert.raises 'offset', ->
markers\add { {name: 'test', start_offset: 4, end_offset: 4} }
assert.raises 'offset', ->
markers\add { {name: 'test', start_offset: 0, end_offset: 2} }
it 'raises an error if <.end_offset> is out of bounds', ->
buffer.text = '12'
assert.raises 'offset', ->
markers\add { {name: 'test', start_offset: 1, end_offset: 4} }
assert.raises 'offset', ->
markers\add { {name: 'test', start_offset: 1, end_offset: 0} }
it 'adds the specified marker for the designated span', ->
buffer.text = 'åäöx'
mks = { {name: 'test', start_offset: 2, end_offset: 4} }
markers\add mks
assert.same {}, markers\at(1)
assert.same mks, markers\at(2)
assert.same mks, markers\at(3)
assert.same {}, markers\at(4)
it 'allows specifying bytes offsets using byte_{start,end}_offset', ->
buffer.text = 'åäöx'
mks = { {name: 'test', byte_start_offset: 3, byte_end_offset: 5} }
adjusted = { {name: 'test', start_offset: 2, end_offset: 3} }
markers\add mks
assert.same {}, markers\at(1)
assert.same adjusted, markers\at(2)
assert.same {}, markers\at(3)
describe 'for_range(start_offset, end_offset)', ->
it 'returns all markers that intersects with the specified span', ->
buffer.text = 'åäö€ᛖ'
markers\add { {name: 'test1', start_offset: 2, end_offset: 5} }
markers\add { {name: 'test2', start_offset: 4, end_offset: 6} }
assert.same {'test1'}, names(markers\for_range(1, 4))
assert.same {'test1', 'test2'}, names(markers\for_range(1, 5))
assert.same {'test1', 'test2'}, names(markers\for_range(4, 5))
assert.same {'test2'}, names(markers\for_range(5, 5))
assert.same {'test2'}, names(markers\for_range(5, 10))
assert.same {'test1', 'test2'}, names(markers\for_range(1, 6))
describe 'find(selector)', ->
it 'finds all markers matching the selector', ->
buffer.text = 'åäö€ᛖ'
markers\add { {name: 'test1', start_offset: 1, end_offset: 2} }
markers\add { {name: 'test2', start_offset: 3, end_offset: 5} }
assert.same {
{name: 'test1', start_offset: 1, end_offset: 2}
}, markers\find name: 'test1'
assert.same {
{name: 'test2', start_offset: 3, end_offset: 5}
}, markers\find name: 'test2'
assert.same {}, markers\find foo: 'bar'
describe 'remove(selector)', ->
it 'removes all markers matching the selector', ->
buffer.text = 'åäö€ᛖ'
markers\add { {name: 'test1', start_offset: 2, end_offset: 3, foo: 'bar'} }
markers\add { {name: 'test2', start_offset: 5, end_offset: 6, foo: 'frob'} }
markers\remove foo: 'frob'
assert.same {'test1'}, names(markers\for_range(1, 7))
markers\remove!
assert.same {}, markers\for_range(1, 7)
describe 'remove_for_range(start_offset, end_offset, selector)', ->
it 'removes all markers within the range', ->
buffer.text = 'åäö€ᛖ'
markers\add { {name: 'test1', start_offset: 2, end_offset: 3} }
markers\add { {name: 'test2', start_offset: 5, end_offset: 6} }
markers\remove_for_range 1, 4
assert.same {}, markers\at(2)
markers\remove_for_range 4, 10
assert.same {}, markers\at(5)
describe 'when <selector> is specified', ->
it 'only removes markers matching the selector', ->
buffer.text = 'åäö€ᛖ'
markers\add { {name: 'test1', start_offset: 2, end_offset: 3, foo: 'bar'} }
markers\add { {name: 'test2', start_offset: 5, end_offset: 6, foo: 'frob'} }
markers\remove_for_range 1, 6, foo: 'frob'
assert.same {'test1'}, names(markers\for_range(1, 7))
describe 'upon buffer modifications', ->
it 'markers move with inserts', ->
buffer.text = 'åäö€ᛖ'
markers\add { {name: 'test1', start_offset: 2, end_offset: 3} }
buffer\insert '∀', 1
assert.same {
{ name: 'test1', start_offset: 3, end_offset: 4 }
}, markers.all
it 'markers expand with inserts', ->
buffer.text = 'åäö€ᛖ'
markers\add { {name: 'test1', start_offset: 2, end_offset: 4} }
buffer\insert '∀', 3
assert.same {
{ name: 'test1', start_offset: 2, end_offset: 5 }
}, markers.all
it 'markers move with deletes', ->
buffer.text = 'åäö€ᛖ'
markers\add { {name: 'test1', start_offset: 3, end_offset: 5} }
buffer\delete 2, 2
assert.same {
{ name: 'test1', start_offset: 2, end_offset: 4 }
}, markers.all
it 'markers shrink with deletes', ->
buffer.text = 'åäö€ᛖ'
markers\add { {name: 'test1', start_offset: 2, end_offset: 5} }
buffer\delete 3, 3
assert.same {
{ name: 'test1', start_offset: 2, end_offset: 4 }
}, markers.all
| 37.271523 | 84 | 0.600924 |
a9c72d159d34ae246485fcc230536702d362bb5e | 610 | export modinfo = {
type: "function"
id: "OnChatted"
func: (Msg) ->
Spawn ->
for Name, Command in pairs ConfigSystem("Get", "Commands")
if Msg\sub(1,#Command.Command+1)\lower! == string.format("%s%s",Command.Command\lower!, ConfigSystem("Get", "Blet"))
Ran,Error = ypcall(Command.Func,Msg\sub(#Command.Command+2),LocalPlayer)
Output Error, {Colors.Red} unless Ran
return
-- if ConfigSystem "Get", "EnableGuiChat" == true
-- Chat Msg
-- else
-- tar = LocalPlayer.Character or Probe
-- pcall ->
-- Service"Chat"\Chat tar,Msg,"Green"
ChatPixelRevision2 Msg
}
| 29.047619 | 120 | 0.642623 |
967ecca5fc0646d514363a4ac847deecddf2d853 | 5,873 | class Raster extends Item
_applyMatrix: false
-- Raster doesn't make the distinction between the different bounds,
-- so use the same name for all of them
_boundsGetter: "getBounds"
_boundsSelected: true
_serializeFields:
source: null
new: (object, position) =>
-- Support two forms of item initialization: Passing one object literal
-- describing all the different properties to be set, or an image
-- (object) and a point where it should be placed (point).
super(position isnt nil and Point.read(arg, 1)
-- If we can handle setting properties through object literal, we're all
-- set. Otherwise we need to check the type of object:
if object and not @_set(object)
if object.getContext()
@setCanvas object
else if typeof(object) is 'String'
-- Both data-urls and normal urls are supported here!
@setSource object
else
@setImage object
@_size = Size() if !@_size
clone: =>
element = @_image
if !element
-- If the Raster contains a Canvas object, we need to create
-- a new one and draw this raster's canvas on it.
element = CanvasProvider\getCanvas(@_size)
element\getContext("2d")\drawImage @_canvas, 0, 0
copy = Raster(element)
@_clone copy
getSize: =>
@_size
setSize: =>
size = Size\read(arg)
if @_size.equals(size)
-- Get reference to image before changing canvas
element = @getElement()
-- Setting canvas internally sets _size
@setCanvas CanvasProvider\getCanvas(size)
-- Draw element back onto new canvas
@getContext(true)\drawImage element, 0, 0, size.width, size.height if element
getWidth: =>
@_size.width
getHeight: =>
@_size.height
isEmpty: =>
@_size.width is 0 and @_size.height is 0
getPPI: =>
matrix = @_matrix
orig = Point(0, 0)\transform(matrix)
u = Point(1, 0)\transform(matrix)\subtract(orig)
v = Point(0, 1)\transform(matrix)\subtract(orig)
Size(72 / u\getLength(), 72 / v\getLength())
getContext: =>
@_context = @getCanvas()\getContext("2d") if !@_context
-- Support a hidden parameter that indicates if the context will be used
-- to modify the Raster object. We can notify such changes ahead since
-- they are only used afterwards for redrawing.
if arg[0]
-- Also set _image to null since the Raster stops representing it.
-- NOTE: This should theoretically be in our own _changed() handler
-- for ChangeFlag.PIXELS, but since it's only happening in one place
-- this is fine:
@_image = nil
@_changed Change.PIXELS
@_context
setContext: (context) =>
@_context = context
getCanvas: =>
if @_canvas
ctx = CanvasProvider\getContext(@_size)
ctx.drawImage @_image, 0, 0 if @_image
@_canvas = ctx.canvas
@_canvas
setCanvas: (canvas) =>
CanvasProvider\release @_canvas if @_canvas
@_canvas = canvas
@_size = Size(canvas.width, canvas.height)
@_image = nil
@_context = nil
@_changed Change.GEOMETRY | Change.PIXELS
getImage: =>
@_image
setImage: (image) =>
CanvasProvider\release @_canvas if @_canvas
@_image = image
if options.browser
@_size = Size(image.naturalWidth, image.naturalHeight)
else @_size = Size(image.width, image.height) if options.node
@_canvas = nil
@_context = nil
@_changed Change.GEOMETRY
getSource: =>
@_image and @_image.src or @toDataURL()
setSource: (src) ->
-- TODO
getElement: ->
@_canvas or @_image
getSubImage: (rect) =>
rect = Rectangle\read(arg)
ctx = CanvasProvider\getContext(rect\getSize())
ctx\drawImage @getCanvas(), rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height
ctx\canvas
drawImage: (image, point) =>
point = Point\read(arg, 1)
@getContext(true)\drawImage image, point.x, point.y
getPixel: (point) =>
point = Point\read(arg)
data = @getContext()\getImageData(point.x, point.y, 1, 1).data
-- Alpha is separate now:
Color("rgb", [data[0] / 255, data[1] / 255, data[2] / 255], data[3] / 255)
setPixel: (point, color) =>
_point = Point\read(arg)
_color = Color\read(arg)
components = _color\_convert("rgb")
alpha = _color._alpha
ctx = @getContext(true)
imageData = ctx\createImageData(1, 1)
data = imageData.data
data[0] = components[0] * 255
data[1] = components[1] * 255
data[2] = components[2] * 255
data[3] = (if alpha? then alpha * 255 else 255)
ctx\putImageData imageData, _point.x, _point.y
createImageData: (size) =>
size = Size\read(arg)
@getContext()\createImageData size.width, size.height
getImageData: (rect) =>
rect = Rectangle\read(arg)
rect = Rectangle(@getSize()) if rect\isEmpty()
@getContext()\getImageData rect.x, rect.y, rect.width, rect.height
setImageData: (data, point) =>
point = Point\read(arg, 1)
@getContext(true)\putImageData data, point.x, point.y
_getBounds: (getter, matrix) =>
rect = Rectangle(@_size)\setCenter(0, 0)
(if matrix then matrix\_transformBounds(rect) else rect)
_hitTest: (point, options) =>
if @_contains(point)
that = @
HitResult("pixel", that,
offset: point\add(that._size.divide(2))\round()
-- Inject as Bootstrap accessor, so #toString renders well too
color:
get: ->
that.getPixel @offset
)
_draw: (ctx) =>
element = @getElement()
if element
-- Handle opacity for Rasters separately from the rest, since
-- Rasters never draw a stroke. See Item#draw().
ctx.globalAlpha = @_opacity
ctx\drawImage element, -@_size.width / 2, -@_size.height / 2
| 27.966667 | 102 | 0.633577 |
5e3558a5b3ff0d96a02625bb7aec35d7bfdc9264 | 314 | import push, pop from require "lapis.environment"
import set_backend, init_logger from require "lapis.db.mysql"
setup_db = (opts) ->
push "test", {
mysql: {
user: "root"
database: "lapis_test"
}
}
set_backend "luasql"
init_logger!
teardown_db = ->
pop!
{:setup_db, :teardown_db}
| 15.7 | 61 | 0.646497 |
1d63aa0651c8500eeb7b38b71bcb86cb987b82ea | 3,461 |
import setmetatable, getmetatable, tostring from _G
class DBRaw
raw = (val) -> setmetatable {tostring val}, DBRaw.__base
is_raw = (val) -> getmetatable(val) == DBRaw.__base
class DBList
list = (items) -> setmetatable {items}, DBList.__base
is_list = (val) -> getmetatable(val) == DBList.__base
unpack = unpack or table.unpack
-- is item a value we can insert into a query
is_encodable = (item) ->
switch type(item)
when "table"
switch getmetatable(item)
when DBList.__base, DBRaw.__base
true
else
false
when "function", "userdata", "nil"
false
else
true
TRUE = raw"TRUE"
FALSE = raw"FALSE"
NULL = raw"NULL"
import concat from table
import select from _G
format_date = (time) ->
os.date "!%Y-%m-%d %H:%M:%S", time
build_helpers = (escape_literal, escape_identifier) ->
append_all = (t, ...) ->
for i=1, select "#", ...
t[#t + 1] = select i, ...
flatten_set = (set) ->
escaped_items = [escape_literal item for item in set[2]]
assert escaped_items[1], "can't flatten empty set"
"(#{table.concat escaped_items, ", "})"
-- replace ? with values
interpolate_query = (query, ...) ->
values = {...}
i = 0
(query\gsub "%?", ->
i += 1
if values[i] == nil
error "missing replacement #{i} for interpolated query"
escape_literal values[i])
-- (col1, col2, col3) VALUES (val1, val2, val3)
encode_values = (t, buffer) ->
assert next(t) != nil, "encode_values passed an empty table"
have_buffer = buffer
buffer or= {}
append_all buffer, "("
tuples = [{k,v} for k,v in pairs t]
for pair in *tuples
append_all buffer, escape_identifier(pair[1]), ", "
buffer[#buffer] = ") VALUES ("
for pair in *tuples
append_all buffer, escape_literal(pair[2]), ", "
buffer[#buffer] = ")"
concat buffer unless have_buffer
-- col1 = val1, col2 = val2, col3 = val3
encode_assigns = (t, buffer) ->
assert next(t) != nil, "encode_assigns passed an empty table"
join = ", "
have_buffer = buffer
buffer or= {}
for k,v in pairs t
append_all buffer, escape_identifier(k), " = ", escape_literal(v), join
buffer[#buffer] = nil
concat buffer unless have_buffer
-- { hello: "world", cat: db.NULL" } -> "hello" = 'world' AND "cat" IS NULL
encode_clause = (t, buffer) ->
assert next(t) != nil, "encode_clause passed an empty table"
join = " AND "
have_buffer = buffer
buffer or= {}
for k,v in pairs t
if v == NULL
append_all buffer, escape_identifier(k), " IS NULL", join
else
op = is_list(v) and " IN " or " = "
append_all buffer, escape_identifier(k), op, escape_literal(v), join
buffer[#buffer] = nil
concat buffer unless have_buffer
interpolate_query, encode_values, encode_assigns, encode_clause
gen_index_name = (...) ->
-- pass index_name: "hello_world" to override generated index name
count = select "#", ...
last_arg = select count, ...
if type(last_arg) == "table" and not is_raw(last_arg)
return last_arg.index_name if last_arg.index_name
parts = for p in *{...}
if is_raw p
p[1]\gsub("[^%w]+$", "")\gsub("[^%w]+", "_")
elseif type(p) == "string"
p
else
continue
concat(parts, "_") .. "_idx"
{
:NULL, :TRUE, :FALSE, :raw, :is_raw, :list, :is_list, :is_encodable, :format_date, :build_helpers, :gen_index_name
}
| 25.07971 | 116 | 0.611673 |
3d8e6a2e7e6abfa27562df8cb5f7a51ae3404074 | 5,967 | import java, Font, Image, Quad from smaug
Constants = require "smaug/wrappers"
Color = java.require "com.badlogic.gdx.graphics.Color"
Gdx = java.require "com.badlogic.gdx.Gdx"
GL20 = java.require "com.badlogic.gdx.graphics.GL20"
Matrix4 = java.require "com.badlogic.gdx.math.Matrix4"
SmaugVM = java.require "smaug.SmaugVM"
OrthographicCamera = java.require "com.badlogic.gdx.graphics.OrthographicCamera"
ShapeRender = java.require "com.badlogic.gdx.graphics.glutils.ShapeRenderer"
SpriteBatch = java.require "com.badlogic.gdx.graphics.g2d.SpriteBatch"
shader = SpriteBatch\createDefaultShader!
batch = java.new SpriteBatch, 1000, shader
shapes = java.new ShapeRender
font = Font!
shapes\setAutoShapeType true
matrix = java.new Matrix4
color = java.new Color, 1, 1, 1, 1
background = java.new Color 0, 0, 0, 1
blending = "alphas"
batch\setColor color
shapes\setColor color
font.font\setColor color
camera = java.new OrthographicCamera
camera\setToOrtho true
batch\setProjectionMatrix camera.combined
shapes\setProjectionMatrix camera.combined
matrix_dirty = false
check = (texture_based) ->
if texture_based
if matrix_dirty
batch\setTransformMatrix matrix
matrix_dirty = false
if shapes\isDrawing!
SmaugVM.util\endShapes shapes
unless batch\isDrawing!
batch\begin!
else
if matrix_dirty
shapes\setTransformMatrix matrix
matrix_dirty = false
if batch\isDrawing!
SmaugVM.util\endBatch batch
unless shapes\isDrawing!
shapes\begin!
arc = (mode, x, y, radius, a1, a2) ->
check false
shapes\set Constants.shapes[mode]
shapes\arc x, y, radius, (math.deg a1), math.deg a2
circle = (mode, x, y, radius) ->
check false
shapes\set Constants.shapes[mode]
shapes\circle x, y, radius
clear = ->
Gdx.gl\glClearColor background.r, background.g, background.b
Gdx.gl\glClear GL20.GL_COLOR_BUFFER_BIT
draw = (image, x = 0, y = 0, r = 0, sx = 1, sy = 1, ox = 0, oy = 0) ->
check true
w = image\getWidth!
h = image\getHeight!
src_x = 0
src_y = 0
src_w = w
src_h = h
x -= ox
y -= oy
batch\draw image.texture, x, y, ox, oy, w, h, sx, sy, r, srx_x, srx_y, src_w, src_h, false, true
draw_q = (image, quad, x = 0, y = 0, r = 0, sx = 1, sy = 1, ox = 0, oy = 0) ->
check true
w = quad.width
h = quad.height
src_x = quad.x
src_y = quad.y
src_w = quad.sw
src_h = quad.sh
x -= ox
y -= oy
batch\draw image.texture, x, y, ox, oy, w, h, sx, sy, r, src_x, src_y, src_w, src_h, false, true
ellipse = (mode, x, y, width, height) ->
check false
shapes\set Constants.shapes[mode]
shapes\ellipse x, y, width, height
line = (x1, y1, x2, y2) ->
check false
shapes\line x1, y1, x2, y2
origin = ->
matrix\idt!
matrix_dirty = true
point = (x, y) ->
check false
shapes\point x, y, 0
polygon = (mode, ...) ->
check false
shapes\set Constants.shapes[mode]
args = table.pack ...
if type args[1] == "table"
shapes\polygon args[1]
else
shapes\polygon args
present = ->
if shapes\isDrawing!
SmaugVM.util\endShapes shapes
if batch\isDrawing!
SmaugVM.util\endBatch batch
print = (text, x = 0, y = 0, r = 0, sx = 1, sy = 1, ox = 0, oy = 0) ->
check true
local tmp
unless r == 0
tmp = batch\getTransformMatrix!
translate x, y
rotate r
translate -x, -y
batch\setTransformMatrix matrix
matrix_dirty = false
font.font\getData!\setScale sx, sy
font.font\draw batch, text, x - ox * sx, y - oy * sy
unless r == 0
translate x, y
rotate -r
translate -x, -y
batch\setTransformMatrix tmp
matrix_dirty = false
prin_f = (text, width = 0, align = "left", x = 0, y = 0, r = 0, sx = 1, sy = 1, ox = 0, oy = 0) ->
check true
tmp = nil
unless r == 0
tmp = batch\getTransformMatrix!
translate x, y
rotate r
translate -x, -y
batch\setTransformMatrix matrix
matrix_dirty = false
font.font\getData!\setScale sx, -sy
font.font\draw batch, text, x - ox * sx, y - oy * sy, width, Constants.aligns[align], true
unless r == 0
translate x, y
rotate -r
translate -x, -y
batch\setTransformMatrix tmp
matrix_dirty = false
rectangle = (mode, x, y, width, height) ->
check false
shapes\set Constants.shapes[mode]
shapes\rect x, y, width, height
reset = ->
shader = SpriteBatch\createDefaultShader!
batch\setShader shader
background\set 0.4, 0.3, 0.4, 1
color\set 1, 1, 1, 1
batch\setColor color
shapes\setColor color
font.font\setColor color
matrix\idt!
matrix_dirty = true
translate = (x, y) ->
matrix\translate x, y
matrix_dirty = true
rotate = (radians) ->
matrix\rotate 0, 0, 1, math.deg radians
matrix_dirty = true
scale = (sx, sy) ->
matrix\scale sx, sy, 1
matrix_dirty = true
get_background_color = ->
background.r * 255, background.g * 255, background.b * 255
get_blend_mode = ->
blending
get_color = ->
color.r * 255, color.g * 255, color.b * 255, color.a * 255
get_font = ->
font
set_background_color = (r, g, b, a = 255) ->
background\set r / 255, g / 255, b / 255, a / 255
set_blend_mode = (mode) ->
blending = mode
blend_mode = Constants[blending]
batch\setBlendFunction blend_mode[1], blend_mode[2]
set_font = (v) ->
font = v
set_new_font = (path, size, f_type) ->
font = new_font path, size, f_type
new_font = (path, size, f_type) ->
(Font path, size, f_type)
new_image = (path, format, f_type) ->
(Image path, format, f_type)
new_quad = (x, y, width, height, sx, sy) ->
(Quad x, y, width, height, sx, sy)
{
:arc
:circle
:clear
:draw
:draw_q
:ellipse
:get_background_color
:get_blendMode
:get_color
:get_font
:line
:origin
:point
:polygon
:present
:print
:print_f
:rectangle
:reset
:translate
:rotate
:scale
:set_background_color
:set_blend_mode
:set_color
:set_font
:set_new_font
:new_font
:new_image
:new_quad
}
| 20.158784 | 98 | 0.655438 |
1acfcf9d817b89159e8a76a8a933aa3da7c33495 | 6,037 | export class Actor extends Entity
new: (maxHealth) =>
super!
@layer = Settings.layers.entity.actors
@faceDirection = "left"
-- health
@maxHealth = maxHealth
@health = @maxHealth
@isAlive = true
@canTakeDamage = true
-- moving
@movement = nil
@isMoving = false
@moveDirection = x: 0, y: 0
-- grid
@currentGrid = x: 0, y: 0
-- turn
@isWaiting = true
@hasEndedTurn = false
@canTurn = true
sceneAdded: (scene) =>
super(scene)
@currentGrid.x, @currentGrid.y = @scene.grid\transformToGridPos(@x, @y)
cell = @currentCell!
if (cell == nil or cell.thing != nil)
@die!
return
cell.thing = @
beforeUpdate: =>
super!
update: (dt) =>
super(dt)
if (not @isAlive or @movement == nil)
return
if (@isMoving and not @movement.hasTargetPosition)
@isMoving = false
@moveDirection.x = 0
@moveDirection.y = 0
lateUpdate: =>
super!
[email protected], @currentGrid.y = @scene.grid\transformToGridPos(@x, @y)
if (not @isAlive)
return
curentCell = @currentCell!
if (currentCell != nil)
-- check if current tile isn't walkable (impossible situation, but actor dies)
if (not currentCell.walkable)
@die!
draw: =>
super!
if (@movement == nil or (@movement.targetPosition.x == 0 and @movement.targetPosition.y == 0))
return
--love.graphics.setColor(1, 0, 0, .7)
--love.graphics.line(@x, @y, @movement.targetPosition.x, @movement.targetPosition.y)
--love.graphics.setColor(1, 1, 1, .7)
-- turn
startTurn: (turn) =>
@isWaiting = false
print "start #{@@__name} turn"
updateTurn: (dt, turn) =>
endTurn: (turn) =>
print "end #{@@__name} turn"
finishTurn: =>
if (@isWaiting)
return
@hasEndedTurn = true
@isWaiting = true
-- movement
move: (x, y) =>
if (@isMoving or (x == 0 and y == 0))
return false
if (x > 0)
@turnTo("right")
elseif (x < 0)
@turnTo("left")
elseif (y < 0)
@turnTo("up")
elseif (y > 0)
@turnTo("down")
nextGrid =
x: @currentGrid.x + x
y: @currentGrid.y + y
nextCell = @scene.grid\cellAt(nextGrid.x, nextGrid.y)
-- check if next tile is walkable
if (nextCell == nil or not nextCell.walkable)
if (@onCollideCell(nextCell))
return false
elseif (nextCell.thing != nil)
if (@onCollideCell(nextCell))
return false
-- moving
cell = @currentCell!
cell.thing = nil
nextCell.thing = @
@currentGrid.x = nextGrid.x
@currentGrid.y = nextGrid.y
@isMoving = true
@moveDirection.x = x
@moveDirection.y = y
@movement\moveTo(
@x + @moveDirection.x * Settings.tileSize.width
@y + @moveDirection.y * Settings.tileSize.height
)
return true
moveUp: (tiles=1) =>
@move(0, -tiles)
moveRight: (tiles=1) =>
@move(tiles, 0)
moveDown: (tiles=1) =>
@move(0, tiles)
moveLeft: (tiles=1) =>
@move(-tiles, 0)
turnTo: (direction) =>
@faceDirection = direction
if (@graphic != nil)
faceX, faceY = Helper.directionToVector(@faceDirection)
if (faceX != 0)
@graphic.flip.h = (faceX > 0)
-- health
changeHealth: (amount) =>
@health = Lume.clamp(@health + amount, 0, @maxHealth)
takeDamage: (amount) =>
if (amount == 0 or not @isAlive)
return
if (amount < 0)
@takeHeal(math.abs(amount))
return
@changeHealth(-amount)
if (not @onTakeDamage!)
@changeHealth(amount)
return
if (@health == 0)
@die!
takeHeal: (amount) =>
if (amount == 0 or not @isAlive)
return
if (amount < 0)
@takeDamage(math.abs(amount))
return
@changeHealth(amount)
if (not @onTakeHeal!)
@changeHealth(-amount)
return
onTakeDamage: =>
print "#{@@__name} take damage [#{@health}/#{@maxHealth}]"
return true
onTakeHeal: =>
print "#{@@__name} take heal [#{@health}/#{@maxHealth}]"
return true
die: =>
if (not @isAlive)
return
@isAlive = false
print "#{@@__name} dies"
@health = 0
@onDeath!
onDeath: =>
@removeSelf!
-- grid cell
currentCell: =>
@scene.grid\cellAt(@currentGrid.x, @currentGrid.y)
neighborCell: (x, y) =>
@scene.grid\cellAt(@currentGrid.x + x, @currentGrid.y + y)
facingCell: =>
faceX, faceY = Helper.directionToVector(@faceDirection)
@neighborCell(faceX, faceY)
dirToCell: (cellX, cellY) =>
if (cellX != @currentGrid.x and cellY != @currentGrid.y)
return { x: 0, y: 0 }
return { x: Lume.clamp((cellX - @currentGrid.x), -1, 1), y: Lume.clamp(cellY - @currentGrid.y, -1, 1) }
-- collision
onCollideCell: (cell) =>
if (cell == nil or not cell.walkable)
return true
elseif (cell.thing != nil and cell.thing.__class.__parent != nil)
if (@onCollideThing(cell.thing))
return true
return false
onCollideThing: (thing) =>
return true
| 24.843621 | 112 | 0.486169 |
cc0acf1e27abf99ccfd6905749787cbd3ff48880 | 5,479 | -- Expand the capabilities of the built-in strings
{:List, :Dict} = require "containers"
{:reverse, :upper, :lower, :find, :byte, :match, :gmatch, :gsub, :sub, :format, :rep, :char} = string
isplit = (sep='%s+')=>
step = (i)=>
start = @pos
return unless start
i += 1
nl = find(@str, @sep, start)
@pos = nl and (nl+1) or nil
line = sub(@str, start, nl and (nl-1) or #@str)
return i, line, start, (nl and (nl-1) or #@str)
return step, {str:@, pos:1, :sep}, 0
lua_keywords = {
["and"]:true, ["break"]:true, ["do"]:true, ["else"]:true, ["elseif"]:true, ["end"]:true,
["false"]:true, ["for"]:true, ["function"]:true, ["goto"]:true, ["if"]:true,
["in"]:true, ["local"]:true, ["nil"]:true, ["not"]:true, ["or"]:true, ["repeat"]:true,
["return"]:true, ["then"]:true, ["true"]:true, ["until"]:true, ["while"]:true
}
is_lua_id = (str)->
match(str, "^[_a-zA-Z][_a-zA-Z0-9]*$") and not lua_keywords[str]
-- Convert an arbitrary text into a valid Lua identifier. This function is injective,
-- but not idempotent. In logic terms: (x != y) => (as_lua_id(x) != as_lua_id(y)),
-- but not (as_lua_id(a) == b) => (as_lua_id(b) == b).
as_lua_id = (str)->
-- Escape 'x' (\x78) when it precedes something that looks like an uppercase hex sequence.
-- This way, all Lua IDs can be unambiguously reverse-engineered, but normal usage
-- of 'x' won't produce ugly Lua IDs.
-- i.e. "x" -> "x", "oxen" -> "oxen", but "Hex2Dec" -> "Hex782Dec" and "He-ec" -> "Hex2Dec"
str = gsub str, "x([0-9A-F][0-9A-F])", "x78%1"
-- Map spaces to underscores, and everything else non-alphanumeric to hex escape sequences
str = gsub str, "%W", (c)->
if c == ' ' then '_'
else format("x%02X", byte(c))
unless is_lua_id(match(str, "^_*(.*)$"))
str = "_"..str
return str
-- from_lua_id(as_lua_id(str)) == str, but behavior is unspecified for inputs that
-- did not come from as_lua_id()
from_lua_id = (str)->
unless is_lua_id(match(str, "^_*(.*)$"))
str = sub(str,2,-1)
str = gsub(str, "_", " ")
str = gsub(str, "x([0-9A-F][0-9A-F])", (hex)-> char(tonumber(hex, 16)))
return str
Text = {
:isplit, uppercase:upper, lowercase:lower, reversed:reverse, :is_lua_id
capitalized: => (gsub(@, '%l', upper, 1))
byte: byte, as_a_number: tonumber, as_a_base_1_number: tonumber,
bytes: (i, j)=> List{byte(@, i or 1, j or -1)}
split: (sep)=> List[chunk for i,chunk in isplit(@, sep)]
starts_with: (s)=> sub(@, 1, #s) == s
ends_with: (s)=> #@ >= #s and sub(@, #@-#s, -1) == s
lines: => List[line for i,line in isplit(@, '\n')]
line: (line_num)=>
for i, line, start in isplit(@, '\n')
return line if i == line_num
line_info_at: (pos)=>
assert(type(pos) == 'number', "Invalid string position")
for i, line, start, stop in isplit(@, '\n')
if stop+1 >= pos
return line, i, (pos-start+1)
indented: (indent=" ")=>
indent..(gsub(@, "\n", "\n"..indent))
as_lua: =>
escaped = gsub(@, "\\", "\\\\")
escaped = gsub(escaped, "\n", "\\n")
escaped = gsub(escaped, '"', '\\"')
escaped = gsub(escaped, "[^ %g]", (c)-> format("\\%03d", byte(c, 1)))
return '"'..escaped..'"'
as_nomsu: => @as_lua!
formatted_with:format, byte:byte,
position_of:((...)->(find(...))), position_of_1_after:((...)->(find(...))),
as_a_lua_identifier: as_lua_id, is_a_lua_identifier: is_lua_id,
as_lua_id: as_lua_id, as_a_lua_id: as_lua_id, is_a_lua_id: is_lua_id,
is_lua_id: is_lua_id, from_lua_id: from_lua_id,
bytes_1_to: (start, stop)=> List{byte(@, start, stop)}
[as_lua_id "with 1 ->"]: (...)-> (gsub(...))
bytes: => List{byte(@, 1, -1)},
wrapped_to: (maxlen=80, margin=8)=>
lines = {}
for line in *@lines!
while #line > maxlen
chunk = sub(line, 1, maxlen)
split = find(chunk, ' ', maxlen-margin, true) or maxlen
chunk = sub(line, 1, split)
line = sub(line, split+1, -1)
lines[#lines+1] = chunk
lines[#lines+1] = line
return table.concat(lines, "\n")
line_at: (i)=> (@line_info_at(i))
line_number_at: (i)=> select(2, @line_info_at(i))
line_position_at: (i)=> select(3, @line_info_at(i))
matches: (patt)=> match(@, patt) and true or false
matching: (patt)=> (match(@, patt))
matching_groups: (patt)=> List{match(@, patt)}
[as_lua_id "* 1"]: (n)=> rep(@, n)
all_matches_of: (patt)=>
result = {}
stepper,x,i = gmatch(@, patt)
while true
tmp = List{stepper(x,i)}
break if #tmp == 0
i = tmp[1]
result[#result+1] = (#tmp == 1) and tmp[1] or tmp
return List(result)
from_1_to: sub, from: sub,
character: (i)=> sub(@, i, i)
}
for k,v in pairs(string) do Text[k] or= v
_1_as_text = (x)->
if x == true then return "yes"
if x == false then return "no"
return tostring(x)
setmetatable Text,
__call: (...)=>
ret = {...}
for i=1,select("#", ...)
ret[i] = _1_as_text(ret[i])
return table.concat(ret)
debug.setmetatable "",
__type: "Text"
__index: (k)=> Text[k] or (type(k) == 'number' and sub(@, k, k) or nil)
__add: (x)=> _1_as_text(@).._1_as_text(x)
return Text
| 38.584507 | 101 | 0.539697 |
545c1e84db75cf3f3a91622e1e9e683d22bad549 | 3,381 | {:cimport, :internalize, :eq, :ffi, :lib, :cstr, :to_cstr} = require 'test.unit.helpers'
require 'lfs'
env = cimport './src/nvim/os/os.h'
NULL = ffi.cast 'void*', 0
describe 'env function', ->
os_setenv = (name, value, override) ->
env.os_setenv (to_cstr name), (to_cstr value), override
os_getenv = (name) ->
rval = env.os_getenv (to_cstr name)
if rval != NULL
ffi.string rval
else
NULL
describe 'os_setenv', ->
OK = 0
it 'sets an env variable and returns OK', ->
name = 'NEOVIM_UNIT_TEST_SETENV_1N'
value = 'NEOVIM_UNIT_TEST_SETENV_1V'
eq nil, os.getenv name
eq OK, (os_setenv name, value, 1)
eq value, os.getenv name
it "dosn't overwrite an env variable if overwrite is 0", ->
name = 'NEOVIM_UNIT_TEST_SETENV_2N'
value = 'NEOVIM_UNIT_TEST_SETENV_2V'
value_updated = 'NEOVIM_UNIT_TEST_SETENV_2V_UPDATED'
eq OK, (os_setenv name, value, 0)
eq value, os.getenv name
eq OK, (os_setenv name, value_updated, 0)
eq value, os.getenv name
describe 'os_getenv', ->
it 'reads an env variable', ->
name = 'NEOVIM_UNIT_TEST_GETENV_1N'
value = 'NEOVIM_UNIT_TEST_GETENV_1V'
eq NULL, os_getenv name
-- need to use os_setenv, because lua dosn't have a setenv function
os_setenv name, value, 1
eq value, os_getenv name
it 'returns NULL if the env variable is not found', ->
name = 'NEOVIM_UNIT_TEST_GETENV_NOTFOUND'
eq NULL, os_getenv name
describe 'os_getenvname_at_index', ->
it 'returns names of environment variables', ->
test_name = 'NEOVIM_UNIT_TEST_GETENVNAME_AT_INDEX_1N'
test_value = 'NEOVIM_UNIT_TEST_GETENVNAME_AT_INDEX_1V'
os_setenv test_name, test_value, 1
i = 0
names = {}
found_name = false
name = env.os_getenvname_at_index i
while name != NULL
table.insert names, ffi.string name
if (ffi.string name) == test_name
found_name = true
i += 1
name = env.os_getenvname_at_index i
eq true, (table.getn names) > 0
eq true, found_name
it 'returns NULL if the index is out of bounds', ->
huge = ffi.new 'size_t', 10000
maxuint32 = ffi.new 'size_t', 4294967295
eq NULL, env.os_getenvname_at_index huge
eq NULL, env.os_getenvname_at_index maxuint32
if ffi.abi '64bit'
-- couldn't use a bigger number because it gets converted to
-- double somewere, should be big enough anyway
-- maxuint64 = ffi.new 'size_t', 18446744073709551615
maxuint64 = ffi.new 'size_t', 18446744073709000000
eq NULL, env.os_getenvname_at_index maxuint64
describe 'os_get_pid', ->
it 'returns the process ID', ->
stat_file = io.open '/proc/self/stat'
if stat_file
stat_str = stat_file\read '*l'
stat_file\close!
pid = tonumber (stat_str\match '%d+')
eq pid, tonumber env.os_get_pid!
else
-- /proc is not avaliable on all systems, test if pid is nonzero.
eq true, (env.os_get_pid! > 0)
describe 'os_get_hostname', ->
it 'returns the hostname', ->
handle = io.popen 'hostname'
hostname = handle\read '*l'
handle\close!
hostname_buf = cstr 255, ''
env.os_get_hostname hostname_buf, 255
eq hostname, (ffi.string hostname_buf)
| 31.018349 | 88 | 0.641822 |
54c807338712d1ed3fb1e480db6e6717950b1d66 | 225 | TK = require "PackageToolkit"
M = {}
me = ...
name = "test_directory"
members = {
"test_path"
"test_cart2"
"test_cart"
"test_chop"
}
T = TK.module.submodules me, members
M[name] = () -> TK.test.self T
return M | 17.307692 | 36 | 0.617778 |
bb0ae750e49e3ad41fa31c644f3da227713b07d5 | 1,211 |
tonumber = tonumber
parse_size_str = (str, src_w, src_h) ->
w, h, rest = str\match "^(%d*%%?)x(%d*%%?)(.*)$"
return nil, "failed to parse string (#{str})" unless w
w = if p = w\match "(%d+)%%"
unless src_w
return nil, "missing source width for percentage scale"
tonumber(p) / 100 * src_w
else
tonumber w
h = if p = h\match "(%d+)%%"
unless src_h
return nil, "missing source height for percentage scale"
tonumber(p) / 100 * src_h
else
tonumber h
center_crop = rest\match"#" and true
crop_x, crop_y = rest\match "%+(%d+)%+(%d+)"
if crop_x
crop_x = tonumber crop_x
crop_y = tonumber crop_y
else
-- by default we use the dimensions as max sizes
if w and h and not center_crop and src_w and src_h
unless rest\match"!"
if src_w/src_h > w/h
h = nil
else
w = nil
{
:w, :h
:crop_x, :crop_y
:center_crop
}
make_thumb = (load_image) ->
thumb = (img, size_str, output) ->
if type(img) == "string"
img = assert load_image img
img\thumb size_str
ret = if output
img\write output
else
img\get_blob!
ret
thumb
{:parse_size_str, :make_thumb}
| 19.852459 | 62 | 0.582164 |
007de78ed206a2dcdbd0805e036a0c6bddb09d52 | 6,746 | -- Light mode colors based on:
-- http://www.colourlovers.com/palette/2060305/Hatsune_Mikus_hair
-- http://www.color-hex.com/color-palette/9535
-- http://vocaloidcolorpalette.tumblr.com/
-- Dark mode colors were sampled directly from the VOCALOID character images
return (light) ->
window = '#06757f'
background = '#00ddc0'
current = '#00346e'
foreground = '#ffffff'
comment = '#d8e500'
red = '#5e292c'
darkred = '#9b2126'
orange = comment
yellow = '#ead400'
green = '#6ed663'
aqua = '#35bdbd'
blue = '#1a2b87'
purple = '#e6b3cc'
keyword = red
border_color = background
selection = background
embedded_bg = '#03363a'
if not light
window = '#1e1f27'
background = '#11111b'
current = '#303035'
foreground = '#e6e9f3'
comment = '#fedb49'
red = '#cc404b'
darkred = '#8e1e22'
orange = comment
yellow = '#f5da5b'
green = '#66a44d'
aqua = '#0095aa'
blue = '#4b76b8'
purple = '#776691'
keyword = red
border_color = background
selection = '#6c6669'
embedded_bg = '#0f4965'
{
window:
background:
color: window
image:
-- alpha: 0.07
alpha: if light then 0.07 else 0.03
path: theme_file 'assets/background.png'
position: 'center'
status:
font: bold: true, italic: true
color: blue
content_box:
background:
color: window
border:
width: 1
color: border_color
alpha: 0.4
editor:
border:
width: 1
color: border_color
alpha: 0.4
border_right:
width: 3
color: border_color
alpha: 0.4
border_bottom:
width: 3
color: border_color
alpha: 0.4
header:
background:
color: border_color
alpha: 0.4
border_bottom:
color: border_color
alpha: 0.4
color: border_color
font: bold: true
padding: 1
footer:
background:
color: border_color
alpha: 0.4
border_top:
color: border_color
alpha: 0.4
color: border_color
font: bold: true
padding: 1
alpha: 0.4
scrollbars:
slider:
color: blue
indicators:
default:
color: blue
title:
font: bold: true, italic: true
vi:
color: blue
current_line:
background: current
gutter:
color: if light then border_color else blue
background:
color: if light then blue else window
alpha: 0.4
flairs:
indentation_guide:
type: flair.PIPE,
foreground: aqua,
foreground_alpha: if light then 1 else 0.2,
:background,
line_width: 1
edge_line:
type: flair.PIPE,
foreground: blue,
foreground_alpha: 0.3,
line_width: 0.5
search:
type: highlight.ROUNDED_RECTANGLE
foreground: black
foreground_alpha: 1
background: green
text_color: darkgreen
height: 'text'
search_secondary:
type: flair.ROUNDED_RECTANGLE
background: lightblue
text_color: black
height: 'text'
replace_strikeout:
type: flair.ROUNDED_RECTANGLE
foreground: black
background: red
text_color: black
height: 'text'
brace_highlight:
type: flair.RECTANGLE
text_color: foreground
background: '#0064b1'
height: 'text'
brace_highlight_secondary:
type: flair.RECTANGLE
foreground: '#0064b1'
text_color: foreground
line_width: 1
height: 'text'
list_selection:
type: flair.RECTANGLE
background: selection
background_alpha: if light then 0.4 else 0.2
list_highlight:
type: highlight.UNDERLINE
foreground: white
text_color: white
line_width: 2
cursor:
type: flair.RECTANGLE
background: foreground
width: 2
height: 'text'
block_cursor:
type: flair.ROUNDED_RECTANGLE,
background: foreground
text_color: background
height: 'text',
min_width: 'letter'
selection:
type: highlight.ROUNDED_RECTANGLE
background: selection
background_alpha: if light then 0.6 else 0.35
min_width: 'letter'
styles:
default:
color: foreground
red: color: red
green: color: green
yellow: color: yellow
blue: color: blue
magenta: color: purple
cyan: color: aqua
popup:
background: '#00346e'
color: foreground
comment:
font: italic: true
color: comment
variable: color: yellow
label:
color: orange
font: italic: true
key:
color: blue
font: bold: true
fdecl:
color: blue
font: bold: true
keyword:
color: keyword
font: bold: true
class:
color: yellow
font: bold: true
type_def:
color: yellow
font:
bold: true
size: 'large'
family: 'Purisa,Latin Modern Sans'
definition: color: yellow
function:
color: blue
font: bold: true
char: color: green
number: color: orange
operator: color: aqua
preproc: color: aqua
special: color: purple
tag: color: purple
type: color: yellow
member: color: red
info: color: blue
constant:
color: yellow
string: color: green
regex:
color: green
background: embedded_bg
background_alpha: if light then 0.5 else 0.4
embedded:
color: '#aadaff'
background: embedded_bg
background_alpha: if light then 0.5 else 0.4
error:
font: italic: true
color: white
background: darkred
background_alpha: 0.8
warning:
font: italic: true
color: orange
h1:
color: white
background: '#005491'
h2:
color: green
font: bold: true
h3:
color: purple
background: current
font: italic: true
emphasis:
font:
bold: true
italic: true
strong: font: italic: true
link_label: color: aqua
link_url: color: comment
table:
color: blue
background: embedded_bg
background_alpha: 0.5
underline: true
addition: color: green
deletion: color: red
change: color: yellow
}
| 20.017804 | 76 | 0.551141 |
773c4e411e94b734aa1427744af54947a0e33343 | 482 | html = require "lapis.html"
class extends html.Widget
content: =>
html_5 ->
head ->
title @title or "Derezzy"
link rel: "stylesheet", href: @build_url "static/css/style.css"
link rel: "stylesheet", href: "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css"
script src: @build_url "static/js/jquery-3.5.1.min.js"
body ->
@content_for "inner"
| 37.076923 | 122 | 0.547718 |
9a9f569048ec10609181b666d1cfca4b89cf95ba | 2,024 | import filter from require'opeth.common.utils'
import rtype, rcst from require'opeth.opeth.common.constant'
import cst_lookup, cst_add, removeins, swapins from require'opeth.opeth.common.utils'
import get_block from require'opeth.common.blockrealm'
import du_chain, this_def from require'opeth.opeth.common.du_chain'
(fnblock) ->
fnblock.optdebug\start_rec!
du_cfg = du_chain fnblock
ins_idx = 1
hoisting = (to_idx, from_ins, ra) ->
fnblock.instruction[to_idx] = {ra, from_ins[2], from_ins[3], op: from_ins.op}
fnblock.optdebug.modified += 1
du_cfg = du_chain fnblock
while fnblock.instruction[ins_idx]
ins = fnblock.instruction[ins_idx]
{RA, RB, RC, :op} = ins
if op == MOVE
if RA == RB
removeins fnblock.instruction, ins_idx
fnblock.optdebug.modified += 1
du_cfg = du_chain fnblock
continue
blk = get_block nil, ins_idx, du_cfg
if d_rb = this_def blk, ins_idx, RB
if #d_rb.used == 1 and #d_rb.used[1].defined == 1
moved_idx = d_rb.line
if pins = fnblock.instruction[moved_idx]
{pRA, pRB, pRC, op: pop} = pins
switch pop
when ADD, SUB, MUL, DIV, MOD, IDIV, BAND, BXOR, BOR, SHL, SHR, POW
typeRB = rtype fnblock, moved_idx, pRB, du_cfg
typeRC = rtype fnblock, moved_idx, pRB, du_cfg
if typeRB == "number" and typeRC == "number"
if d_rb.def
if #(filter (=> (@reg == pRB or @reg == pRC) and moved_idx < @line and @line < ins_idx), d_rb.def) == 0
hoisting ins_idx, pins, RA
when MOVE
if d_rb.def and #(filter (=> @reg == pRB and moved_idx < @line and @line < ins_idx), d_rb.def) == 0
hoisting ins_idx, pins, RA
when LOADK
hoisting ins_idx, pins, RA
-- TODO: consider of closed variables
-- when CLOSURE
-- hoisting fnblock, ins_idx, moved_idx, pins, RA
-- proto = fnblock.prototype[pRB + 1]
-- for u in *proto.upvalue
-- if u.instack == 1 and u.reg == pRA
-- u.reg = RA
ins_idx += 1
| 31.625 | 114 | 0.637846 |
bdd7b6af696079ffa0cfa7b15c6169b65fd786e6 | 411 | export state = require "lib/state"
love.graphics.setBackgroundColor 255, 255, 255
love.keypressed = (key, isrepeat) =>
state\press key
love.keyreleased = (key, isrepeat) =>
state\release key
love.load = ->
love.graphics.setDefaultFilter "nearest", "nearest"
state\set "src"
state\load!
love.update = (dt) ->
state\update dt
love.draw = ->
love.graphics.setColor 255, 255, 255
state\draw!
| 17.869565 | 53 | 0.693431 |
d0fdcf59f92c0493df45033e384f6829879f456e | 1,818 | --
-- rich interpolation
--
Renderer = require 'kernel'
import resolve from require 'path'
-- TODO: get rid of globality
_defs = {}
-- root of partials
Renderer.root = ''
-- setup renderer helpers
extend Renderer.helpers, {
X: (x, name, filename, offset) ->
if type(x) == 'function'
return '{{' .. name .. ':FUNCTION}}'
if type(x) == 'table'
return '{{' .. name .. ':TABLE}}'
if x == nil
return '{{' .. name .. ':NIL}}'
return x
PARTIAL: (name, locals, callback) ->
if not callback
callback = locals
locals = {}
Renderer.compile resolve(Renderer.root, name), (err, template) ->
if err
callback nil, '{{' .. (err.message or err) .. '}}'
else
template locals, callback
IF: (condition, block, callback) ->
if condition
block {}, callback
else
callback nil, ''
LOOP: (array, block, callback) ->
left = 1
parts = {}
done = false
for i, value in ipairs array
left = left + 1
--value.index = i
block value, (err, result) ->
return if done
if err
done = true
return callback err
parts[i] = result
left = left - 1
if left == 0
done = true
callback nil, join parts
left = left - 1
if left == 0 and not done
done = true
callback nil, join parts
ESC: (value, callback) ->
if callback
callback nil, value\escape()
else
return value\escape()
DEF: (name, block, callback) ->
_defs[name] = block
callback nil, ''
USE: (name, locals, callback) ->
if not callback
callback = locals
locals = {}
_defs[name] locals, callback
}
-- module
return {
render: Renderer.helpers.PARTIAL
set_root: (path) -> Renderer.root = path
}
| 20.659091 | 69 | 0.552805 |
96fc0547bb597b1c5fe38f108a5f7f112d66508b | 852 | import unpack from _G
import Signal from "novacbn/novautils/sources/Signal"
import pack from "novacbn/novautils/utilities"
-- Transform::Transform()
-- Represents a generic Transform dispatcher, useful for progressive dispatch returns
-- export
export Transform = Signal\extend {
-- Transform::dispatch(any ...) -> any ...
-- Dispatches the varargs to all the currently attached listeners, progressively modifiying the input varargs
dispatch: (...) =>
-- Pack the varargs to be transformed
varRet = pack(...)
-- Dispatch to each listener function, modifiying the input varargs
local tempRet
for node in self\iter()
tempRet = pack(node.value(unpack(varRet)))
varRet = tempRet if #tempRet > 0
-- Return the unmodified dispatch vararg
return unpack(varRet)
} | 35.5 | 113 | 0.67723 |
76d960a7f048b7e8220bd8b017f6912735765f2f | 400 | import Entity from require "LunoPunk.Entity"
import Image from require "LunoPunk.graphics.Image"
import Input from require "LunoPunk.utils.Input"
import Key from require "LunoPunk.utils.Key"
class Block extends Entity
new: (x, y) =>
super x, y
@graphic Image "graphics/block.png"
update: =>
@moveBy -2, 0 if Input.check Key.LEFT
@moveBy 2, 0 if Input.check Key.RIGHT
super!
{ :Block }
| 23.529412 | 51 | 0.725 |
fc8e6f78a16a2d0d7abe70bf94e9861523d01f1c | 1,616 | import respond_to, yield_error, capture_errors from require "lapis.application"
--[[ Used to extend Lapis with an Action system ]]
class Action
new: =>
execute: =>
--[[ Used to extend request handlig capabilities ]]
handle_request = (tab) ->
capture_errors {
--[[ Allows to respond on request errors ]]
on_error: =>
result = render: require 'views.general.error'
result = (tab.on_error @) if tab.on_error
result
--[[ Allows to respond on GET and POST events ]]
respond_to {
before: tab.before
GET: tab.GET
POST: =>
result = tab.POST @
if result and result.action
action = result.action
unless action.__class.__parent == Action
yield_error "Actions need to derive from the 'Action' class."
--[[ This metatable allows us to access action fields if existing ]]
--[[ * If no such thing exist it will fallback to the 'request' object for lookup ]]
action_request = setmetatable { request:@, action:action }, {
__index: (self, key) ->
action = rawget self, 'action'
return action[key] if action[key] ~= nil
request = rawget self, 'request'
request_value = request[key]
if (type request_value) == 'function'
return (...) => request_value request, ...
else
return request_value
}
-- Run the action
result = action_request\execute!
-- Returns the action result
result
}
}
{ :handle_request, :Action }
| 31.076923 | 94 | 0.581064 |
8678362f887fb32f66434faa4f9cbc00d27099f0 | 4,106 | options = require 'mp.options'
utils = require 'mp.utils'
-- script namespace for options
script_name = 'torque-progressbar'
mp.get_osd_size = mp.get_osd_size or mp.get_screen_size
-- This is here instead of in settings.moon because it would conflict with the
-- default settings generator tool if it were placed in settings, and this is
-- the only file that goes before settings.
settings = { _defaults: { } }
-- These methods are jammed in a metatable so that they can't be overridden from
-- the configuration file.
settingsMeta = {
_reload: =>
-- Shallow copy should be good. This is necessary to reset values to the
-- defaults so that removing a configuration key has an effect.
for key, value in pairs @_defaults
settings[key] = value
options.read_options @, script_name .. '/main'
if @['bar-height-inactive'] <= 0
@['bar-hide-inactive'] = true
-- This is set to 1 so that we don't end up with libass spamming messages
-- about failing to stroke zero-height object.
@['bar-height-inactive'] = 1
_migrate: =>
pathSep = package.config\sub( 1, 1 )
onWindows = pathSep == '\\'
mv = (oldFile, newFile) ->
cmd = { args: { 'mv', oldConfig, newConfig } }
if onWindows
oldfile = oldFile\gsub( '/', pathSep )
newFile = newFile\gsub( '/', pathSep )
cmd = { args: { 'cmd', '/Q', '/C', 'move', '/Y', oldfile, newFile } }
return utils.subprocess cmd
mkdir = (directory) ->
cmd = { args: { 'mkdir', '-p', directory } }
if onWindows
directory = directory\gsub( '/', pathSep )
cmd = { args: { 'cmd', '/Q', '/C', 'mkdir', directory } }
return utils.subprocess cmd
settingsDirectories = { 'script-opts', 'lua-settings' }
oldConfigFiles = [ '%s/%s.conf'\format dir, script_name for dir in *settingsDirectories ]
newConfigFiles = [ '%s/%s/main.conf'\format dir, script_name for dir in *settingsDirectories ]
oldConfig = nil
oldConfigIndex = 1
newConfigFile = nil
newConfig = nil
for idx, file in ipairs oldConfigFiles
log.debug 'checking for old config "%s"'\format file
oldConfig = mp.find_config_file file
if oldConfig
log.debug 'found "%s"'\format oldConfig
oldConfigIndex = idx
break
unless oldConfig
log.debug 'No old config file found. Migration finished.'
return
for file in *newConfigFiles
log.debug 'checking for new config "%s"'\format file
newConfig = mp.find_config_file file
if newConfig
log.debug 'found "%s"'\format newConfig
newConfigFile = file
break
if oldConfig and not newConfig
log.debug 'Found "%s". Processing migration.'\format oldConfig
newConfigFile = newConfigFiles[oldConfigIndex]
baseConfigFolder, _ = utils.split_path oldConfig
configDir = utils.join_path baseConfigFolder, script_name
newConfig = utils.join_path configDir, 'main.conf'
log.info 'Old configuration detected. Attempting to migrate "%s" -> "%s"'\format oldConfig, newConfig
dirExists = mp.find_config_file configDir
if dirExists and not utils.readdir configDir
log.warn 'Configuration migration failed. "%s" exists and does not appear to be a folder'\format configDir
return
else if not dirExists
log.debug 'Attempting to create directory "%s"'\format configDir
res = mkdir configDir
if res.error or res.status != 0
log.warn 'Making directory "%s" failed.'\format configDir
return
log.debug 'successfully created directory.'
else
log.debug 'Directory "%s" already exists. Continuing.'\format configDir
log.debug 'Attempting to move "%s" -> "%s"'\format oldConfig, newConfig
res = mv oldConfig, newConfig
if res.error or res.status != 0
log.warn 'Moving file "%s" -> "%s" failed.'\format oldConfig, newConfig
return
if mp.find_config_file newConfigFile
log.info 'Configuration successfully migrated.'
else
log.warn 'Cannot find "%s". Migration mysteriously failed?'\format newConfigFile
__newindex: ( key, value ) =>
@_defaults[key] = value
rawset @, key, value
}
settingsMeta.__index = settingsMeta
setmetatable settings, settingsMeta
settings\_migrate!
| 33.382114 | 110 | 0.696298 |
eba2f6f3fed5fbf4e424e35cbc7feeea6827ca1b | 4,427 | import validate_handler from require "gimlet.utils"
class Route
new: (method, pattern, handlers) =>
@method = method
@pattern = pattern
@handlers = handlers
-- This next part gets the parameters from the pattern
-- It grabs the location for the two pattern sets and puts them into
-- a table. It then reindexes them from 1. Once that this is all done,
-- The pattern to pass to the string.{match,find,etc} functions is
-- constructed. This then allows the named and numbered parameters to
-- be looked up in the @params table when the path matches.
-- Get a list of named parameters
tmp_params = {}
-- The maximum index match of the pattern
tmp_params_max = 0
for i, n in string.gmatch pattern, '():([^/#?]+)' do
tmp_params[i] = n
tmp_params_max = i if i > tmp_params_max
-- Get a list of numbered parameters
idx = 1
for i in string.gmatch pattern, '()%*%*' do
tmp_params[i] = idx
tmp_params_max = i if i > tmp_params_max
idx += 1
-- fill out the table so ipairs works across the table
empty = {}
for i=1, tmp_params_max
tmp_params[i] = empty if tmp_params[i] == nil
-- Squash the parameters into the correct order
@params = [ n for n in *tmp_params when n != empty ]
-- Escape some valid parts of the url
@str_match = string.gsub pattern, '[-.]', '%%%1'
-- Add an optional / at the end of the url
@str_match ..= "/?"
-- Change the named parameters to a normal capture
@str_match = string.gsub @str_match, ':([^/#?]+)', '([^/#?]+)'
-- Change the numbered parameters into normal captures
@str_match = string.gsub @str_match, '(%*%*)', '([^#?]*)'
validate: =>
validate_handler h for h in *@handlers
match_method: (method) =>
return @method == '*' or method == @method or (method == 'HEAD' and @method == 'GET')
match: (method, path) =>
return nil unless @match_method method
matches = { string.find path, @str_match }
if #matches > 0 and string.sub(path, matches[1], matches[2]) == path
-- skip matches 1 & 2 since those are the path substring
return {@params[i-2], match for i, match in ipairs matches when i > 2}
return nil
handle: (mapped) =>
for handler in *@handlers
options, output = handler(mapped)
if type(options) == 'string'
mapped.response\write options
else
mapped.response\set_options options if type(options) == 'table'
mapped.response\status options if type(options) == 'number'
mapped.response\write output if type(output) == 'string'
class Router
new: =>
@routes = {}
@groups = {}
@not_founds = {}
add_route: (method, pattern, handler) =>
if #@groups > 0
group_pattern = ""
h = {}
for g in *@groups
group_pattern ..= g.pattern
table.insert h, g.handler
pattern = group_pattern .. pattern
table.insert h, handler
handler = h
handler = {handler} unless type(handler) == 'table'
route = Route method, pattern, handler
route\validate!
table.insert @routes, route
route
group: (pattern, fn, handler) =>
table.insert @groups, {:pattern, :handler}
fn @
get: (pattern, handler) =>
@add_route 'GET', pattern, handler
post: (pattern, handler) =>
@add_route 'POST', pattern, handler
put: (pattern, handler) =>
@add_route 'PUT', pattern, handler
delete: (pattern, handler) =>
@add_route 'DELETE', pattern, handler
patch: (pattern, handler) =>
@add_route 'PATCH', pattern, handler
options: (pattern, handler) =>
@add_route 'OPTIONS', pattern, handler
head: (pattern, handler) =>
@add_route 'HEAD', pattern, handler
any: (pattern, handler) =>
@add_route 'ANY', pattern, handler
-- Add handlers
not_found: (...) =>
@not_founds = { ... }
-- Goes through added routes and calls the handler on matches
-- @param response Should have a \write method for writting to the response
-- @param method the HTTP method to check for a match. Assumed to be all uppercase letters
-- @param path the path portion of the URL to check for a match
handle: (mapped, method, path) =>
for route in *@routes
params = route\match method, path
if params
mapped.params = params
route\handle mapped
return
-- No routes matched, 404
mapped.response\status 404
for h in *@not_founds
if type(h) == 'function'
r = h mapped, method, path
mapped.response\write r if type(r) == 'string'
return
-- Boring default message
mapped.response\write "Not found"
{:Route, :Router}
| 28.746753 | 91 | 0.663203 |
2bd70da6265cb0be66fb06e5e165d1533785f793 | 5,959 |
--
-- 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.CMessage(PPM2, 'PPM2')
do
randomColor = (a = 255) -> Color(math.random(0, 255), math.random(0, 255), math.random(0, 255), a)
PPM2.Randomize = (object, ...) ->
mane, manelower, tail = math.random(PPM2.MIN_UPPER_MANES_NEW, PPM2.MAX_UPPER_MANES_NEW), math.random(PPM2.MIN_LOWER_MANES_NEW, PPM2.MAX_LOWER_MANES_NEW), math.random(PPM2.MIN_TAILS_NEW, PPM2.MAX_TAILS_NEW)
irisSize = math.random(PPM2.MIN_IRIS * 10, PPM2.MAX_IRIS * 10) / 10
with object
\SetGenderSafe(math.random(0, 1), ...)
\SetRaceSafe(math.random(0, 3), ...)
\SetPonySizeSafe(math.random(85, 110) / 100, ...)
\SetNeckSizeSafe(math.random(92, 108) / 100, ...)
\SetLegsSizeSafe(math.random(90, 120) / 100, ...)
\SetWeightSafe(math.random(PPM2.MIN_WEIGHT * 10, PPM2.MAX_WEIGHT * 10) / 10, ...)
\SetTailTypeSafe(tail, ...)
\SetTailTypeNewSafe(tail, ...)
\SetManeTypeSafe(mane, ...)
\SetManeTypeLowerSafe(manelower, ...)
\SetManeTypeNewSafe(mane, ...)
\SetManeTypeLowerNewSafe(manelower, ...)
\SetBodyColorSafe(randomColor(), ...)
\SetEyeIrisTopSafe(randomColor(), ...)
\SetEyeIrisBottomSafe(randomColor(), ...)
\SetEyeIrisLine1Safe(randomColor(), ...)
\SetEyeIrisLine2Safe(randomColor(), ...)
\SetIrisSizeSafe(irisSize, ...)
\SetManeColor1Safe(randomColor(), ...)
\SetManeColor2Safe(randomColor(), ...)
\SetManeDetailColor1Safe(randomColor(), ...)
\SetManeDetailColor2Safe(randomColor(), ...)
\SetUpperManeColor1Safe(randomColor(), ...)
\SetUpperManeColor2Safe(randomColor(), ...)
\SetUpperManeDetailColor1Safe(randomColor(), ...)
\SetUpperManeDetailColor2Safe(randomColor(), ...)
\SetLowerManeColor1Safe(randomColor(), ...)
\SetLowerManeColor2Safe(randomColor(), ...)
\SetLowerManeDetailColor1Safe(randomColor(), ...)
\SetLowerManeDetailColor2Safe(randomColor(), ...)
\SetTailColor1Safe(randomColor(), ...)
\SetTailColor2Safe(randomColor(), ...)
\SetTailDetailColor1Safe(randomColor(), ...)
\SetTailDetailColor2Safe(randomColor(), ...)
\SetSocksAsModelSafe(math.random(1, 2) == 1, ...)
\SetSocksColorSafe(randomColor(), ...)
return object
entMeta = FindMetaTable('Entity')
entMeta.GetPonyRaceFlags = =>
return 0 if not @IsPonyCached()
data = @GetPonyData()
return 0 if not data
return data\GetPonyRaceFlags()
entMeta.IsPony = =>
model = @GetModel()
@__ppm2_lastmodel = @__ppm2_lastmodel or model
if @__ppm2_lastmodel ~= model
data = @GetPonyData()
if data and data.ModelChanges
oldModel = @__ppm2_lastmodel
@__ppm2_lastmodel = model
data\ModelChanges(oldModel, model)
switch model
when 'models/ppm/player_default_base.mdl'
return true
when 'models/ppm/player_default_base_new.mdl'
return true
when 'models/ppm/player_default_base_new_nj.mdl'
return true
when 'models/ppm/player_default_base_nj.mdl'
return true
when 'models/cppm/player_default_base.mdl'
return true
when 'models/cppm/player_default_base_nj.mdl'
return true
else
return false
entMeta.IsNJPony = =>
model = @GetModel()
@__ppm2_lastmodel = @__ppm2_lastmodel or model
if @__ppm2_lastmodel ~= model
data = @GetPonyData()
if data and data.ModelChanges
oldModel = @__ppm2_lastmodel
@__ppm2_lastmodel = model
data\ModelChanges(oldModel, model)
switch model
when 'models/ppm/player_default_base_new_nj.mdl'
return true
when 'models/ppm/player_default_base_nj.mdl'
return true
when 'models/cppm/player_default_base_nj.mdl'
return true
else
return false
entMeta.IsNewPony = =>
model = @GetModel()
@__ppm2_lastmodel = @__ppm2_lastmodel or model
if @__ppm2_lastmodel ~= model
data = @GetPonyData()
if data and data.ModelChanges
oldModel = @__ppm2_lastmodel
@__ppm2_lastmodel = model
data\ModelChanges(oldModel, model)
return model == 'models/ppm/player_default_base_new.mdl' or model == 'models/ppm/player_default_base_new_nj.mdl'
entMeta.IsPonyCached = =>
switch @__ppm2_lastmodel
when 'models/ppm/player_default_base.mdl'
return true
when 'models/ppm/player_default_base_new.mdl'
return true
when 'models/ppm/player_default_base_new_nj.mdl'
return true
when 'models/ppm/player_default_base_nj.mdl'
return true
when 'models/cppm/player_default_base.mdl'
return true
when 'models/cppm/player_default_base_nj.mdl'
return true
else
return false
entMeta.IsNewPonyCached = =>
switch @__ppm2_lastmodel
when 'models/ppm/player_default_base_new.mdl'
return true
when 'models/ppm/player_default_base_new_nj.mdl'
return true
else
return false
entMeta.IsNJPonyCached = =>
switch @__ppm2_lastmodel
when 'models/ppm/player_default_base_new_nj.mdl'
return true
when 'models/ppm/player_default_base_nj.mdl'
return true
when 'models/cppm/player_default_base_nj.mdl'
return true
else
return false
entMeta.HasPonyModel = entMeta.IsPony
| 35.052941 | 207 | 0.735023 |
c168b239daaf606e69ca5068162193fec637042a | 568 | --- toml mode for howl from [ta-toml](https://bitbucket.org/a_baez/ta-toml)
-- See @{README.md} for details on usage.
-- @author [Alejandro Baez](https://keybase.io/baez)
-- @copyright 2016
-- @license MIT (see LICENSE)
-- @module mode
import style from howl.ui
style.define 'tab', 'preproc'
style.define 'timestamp', 'constant'
{
lexer: bundle_load('toml_lexer')
comment_syntax: '#'
auto_pairs: {
'(': ')'
'[': ']'
'{': '}'
'"': '"'
"'": "'"
}
default_config:
use_tabs: false
tab_width: 4
indent: 4
edge_column: 99
}
| 18.933333 | 75 | 0.596831 |
ba30956fc3210ddb08991cdbe8fd5436af3bf3b4 | 672 | formats = {}
-- A basic format class, which specifies some fields to be set by child classes.
class Format
new: =>
@displayName = "Basic"
@supportsTwopass = true
@videoCodec = ""
@audioCodec = ""
@outputExtension = ""
-- A kinda weird flag, but... whatever, I don't have a better name for it.
@acceptsBitrate = true
-- Filters that should be applied before the transformations we do (crop, scale)
-- Should be a array of ffmpeg filters e.g. {"colormatrix=bt709", "sub"}.
getPreFilters: => {}
-- Similar to getPreFilters, but after our transformations.
getPostFilters: => {}
-- A list of flags, to be appended to the command line.
getFlags: => {}
| 29.217391 | 81 | 0.681548 |
34e99231e6af8971390ce11d01c2c81b9fb12e06 | 1,359 | package.path = "./modules/?.lua;" .. package.path
file_util = require"file_util"
ast_util = require"ast_util"
ms = require "moonscript.base"
CmdsMod = file_util.find("src", "*.mod.moon")
appendFS = (...) ->
dirs = {...}
return table.concat(dirs, "/")
ast_get_modinfo = (ast) ->
local function_name, function_function
for i, v in ipairs(ast)
if v.tag == "Set"
if v[1][1].tag == "Id"
if v[2][1].tag == "Table"
if v[1][1][1] == "modinfo"
return v[2][1]
for i, v in pairs(CmdsMod)
moon_lua, err = ms.to_lua(file_util.readfile(v)) --currently linemapping not support
if not moon_lua
print v .. ": " .. err
os.exit(1)
ast = ast_util.code_to_ast(moon_lua)
modtype = nil
moddesc = nil
modalias = nil
modfunc = nil
for i, v in ast_util.ast_pairs(ast_get_modinfo(ast))
if i[1] == "type"
modtype = ast_util.ast_to_obj(v)
elseif i[1] == "desc"
moddesc = ast_util.ast_to_obj(v)
elseif i[1] == "alias"
modalias = ast_util.ast_to_obj(v)
elseif i[1] == "func"
modfunc = v
if modtype ~= "command"
continue
OutAddCommandAst = ast_util.new_ast_node("Call", ast_util.new_ast_node("Id", "AddCommand"), ast_util.new_ast_node("String", moddesc), ast_util.new_ast_node("String", modalias[1]), modfunc)
file_util.writefile(string.format("%s/%s.cmd.lua", arg[1], i .. "_ncmd"), ast_util.ast_to_code(OutAddCommandAst))
| 29.543478 | 189 | 0.664459 |
d1932d5bbdcb7ce80d6cee493f5d913cc059c3ea | 961 | export class Arrow extends Entity
onCollision: (cols) =>
for col in *cols
other = col.other
color = other.sprite.color
switch other.__class
when Undead
other\damage @damage
unless other.__class == Arrow or other.__class == Player or other.__class == Stairs
@destroy color
new: (pos, @dir) =>
super pos.x - 2, pos.y - 2, sprites.arrow
@stuck = false
@speed = 200
@damage = 1
filter: (item, other) ->
switch other.__class
when Player
return "cross"
when Arrow
return "cross"
when Stairs
return "cross"
return "touch"
update: (dt) =>
unless @stuck
@move @dir * @speed * dt
destroy: (color) =>
with player.weapon.psystem
\setDirection (@dir * -1).angle
\setPosition @pos.x, @pos.y
\setColors color[1], color[2], color[3], 1
\emit 3
dungeon.currentRoom\removeEntity @
| 21.840909 | 89 | 0.570239 |
15b8ae1149c6a1059eda922cc97a166a69c0e45c | 2,149 | import Template from gmodproj.api
-- AddonTemplate::AddonTemplate()
-- Represents the project template to create new Garry's Mod addons
-- export
export AddonTemplate = Template\extend {
-- AddonTemplate::createProject() -> void
-- Event called to construct the new project
-- event
createProject: () =>
-- Create the project directories
@createDirectory("addons")
@createDirectory("addons/#{@projectName}")
@createDirectory("addons/#{@projectName}/lua")
@createDirectory("addons/#{@projectName}/lua/autorun")
@createDirectory("addons/#{@projectName}/lua/autorun/client")
@createDirectory("addons/#{@projectName}/lua/autorun/server")
@createDirectory("src")
-- Create the Garry's Mod addon manifest
@writeJSON("addons/#{@projectName}/addon.json", {
title: @projectName
type: ""
tags: {}
description: ""
ignore: {}
})
-- Format a header prefix for brevity
moduleHeader = @projectAuthor.."/"..@projectName
-- Create the project's entry points
-- HACK: gmodproj currently doesn't do lexical lookup of import/dependency statements...
@write("src/client.lua", "imp".."ort('#{moduleHeader}/shared').sharedFunc()\nprint('I was called on the client!')")
@write("src/server.lua", "imp".."ort('#{moduleHeader}/shared').sharedFunc()\nprint('I was called on the server!')")
@write("src/shared.lua", "function sharedFunc()\n\tprint('I was called on the client and server!')\nend")
-- Crepate the project's manifest
@writeProperties(".gmodmanifest", {
name: @projectName
author: @projectAuthor
version: "0.0.0"
repository: "unknown://unknown"
buildDirectory: "addons/#{@projectName}/lua"
projectBuilds: {
"#{moduleHeader}/client": "autorun/client/#{@projectName}_client"
"#{moduleHeader}/server": "autorun/server/#{@projectName}_server"
}
})
} | 41.326923 | 123 | 0.590973 |
ed5172137adddf802dbfecf7422ee981c7c6f83a | 258 | export modinfo = {
type: "command"
desc: "Run normal Script"
alias: {"scr"}
func: (Msg,Speaker) ->
if NewSource(Msg,workspace)
Output("Normal script running",{Colors.Green},Speaker)
else
Output("Normal script not inited",{Colors.Red},Speaker)
} | 25.8 | 58 | 0.689922 |
c7b7a7d9b2b9a702105b75c7e23492cb3966aaa3 | 134 | Z = (f using nil) -> ((x) -> x x) (x) -> f (...) -> (x x) ...
factorial = Z (f using nil) -> (n) -> if n == 0 then 1 else n * f n - 1
| 44.666667 | 71 | 0.402985 |
dd4d1dc6bc9fa3c370cd72e1fe098983d7364c08 | 2,058 | ----------------------------------------------------------------
-- A Block that puts creates a conditional structure.
--
-- @classmod ConditionalBlock
-- @author Richard Voelker
-- @license MIT
----------------------------------------------------------------
local Block
local SpaceBlock
if game
pluginModel = script.Parent.Parent.Parent.Parent
Block = require(pluginModel.com.blacksheepherd.code.Block)
SpaceBlock = require(pluginModel.com.blacksheepherd.code.SpaceBlock)
else
Block = require "com.blacksheepherd.code.Block"
SpaceBlock = require "com.blacksheepherd.code.SpaceBlock"
-- {{ TBSHTEMPLATE:BEGIN }}
class ConditionalBlock extends Block
new: =>
super!
@_conditions = {}
----------------------------------------------------------------
-- Adds a condition to the list of conditions. A new SpaceBlock
-- is added to this Block as well, and any AddChild calls made
-- after will be added to the new SpaceBlock.
--
-- @tparam ConditionalBlock self
-- @tparam string condition[opt=""] The condition of if
-- statement. Leave this blank to add an else statement.
----------------------------------------------------------------
AddCondition: (condition = "") =>
table.insert @_conditions, condition
super\AddChild SpaceBlock!
----------------------------------------------------------------
-- Adds a child Block or Line to the latest conditional Block,
-- as created by @{AddCondition}.
--
-- @tparam ConditionalBlock self
-- @tparam Block/Line child The child to add.
----------------------------------------------------------------
AddChild: (child) =>
@_children[#@_children]\AddChild child
Render: =>
buffer = ""
for i, child in ipairs @_children
lineString = @_conditions[i]
if i == 1
lineString = "if #{lineString} then"
elseif lineString == ""
lineString = "else"
else
lineString = "elseif #{lineString} then"
buffer ..= "#{@_indent}#{lineString}\n"
buffer ..= child\Render! .. "\n"
buffer .. "#{@_indent}end"
-- {{ TBSHTEMPLATE:END }}
return ConditionalBlock
| 29.826087 | 69 | 0.569485 |
25e51d4297250e30b45817ae822c68f9ba93a105 | 21,953 | [
{
name: "Ethereum"
address: "0x0000000000000000000000000000000000000000"
symbol: "ETH"
}
{
name: "FirstBlood"
address: "0xAf30D2a7E90d7DC361c8C4585e9BB7D2F6f15bc7"
symbol: "1ST"
}
{
name: "300 Token"
address: "0xaEc98A708810414878c3BCDF46Aad31dEd4a4557"
symbol: "300"
}
{
name: "AdShares"
address: "0x422866a8F0b032c5cf1DfBDEf31A20F4509562b0"
symbol: "ADST"
}
{
name: "adToken"
address: "0xD0D6D6C5Fe4a677D343cC433536BB717bAe167dD"
symbol: "ADT"
}
{
name: "AdEx"
address: "0x4470BB87d77b963A013DB939BE332f927f2b992e"
symbol: "ADX"
}
{
name: "AirToken"
address: "0x27dce1ec4d3f72c3e457cc50354f1f975ddef488"
symbol: "AIR"
}
{
name: "ALIS"
address: "0xEA610B1153477720748DC13ED378003941d84fAB"
symbol: "ALIS"
}
{
name: "AMIS"
address: "0x949bEd886c739f1A3273629b3320db0C5024c719"
symbol: "AMIS"
}
{
name: "Aragon"
address: "0x960b236A07cf122663c4303350609A66A7B288C0"
symbol: "ANT"
}
{
name: "Aigang"
address: "0x23aE3C5B39B12f0693e05435EeaA1e51d8c61530"
symbol: "APT"
}
{
name: "Arcade Token"
address: "0xAc709FcB44a43c35F0DA4e3163b117A17F3770f5"
symbol: "ARC"
}
{
name: "Aeron"
address: "0xBA5F11b16B155792Cf3B2E6880E8706859A8AEB6"
symbol: "ARN"
}
{
address: "0xfec0cF7fE078a500abf15F1284958F22049c2C7e"
symbol: "ART"
}
{
name: "Aventus"
address: "0x0d88ed6e74bbfd96b831231638b66c05571e824f"
symbol: "AVT"
}
{
name: "Basic Attention Token"
address: "0x0D8775F648430679A709E98d2b0Cb6250d2887EF"
symbol: "BAT"
}
{
name: "DAO.Casino"
address: "0x725803315519de78D232265A8f1040f054e70B98"
symbol: "BET"
}
{
name: "Blockchain Index"
address: "0xce59d29b09aae565feeef8e52f47c3cd5368c663"
symbol: "BLX"
}
{
name: "Blackmoon Crypto"
address: "0xdf6ef343350780bf8c3410bf062e0c015b1dd671"
symbol: "BMC"
}
{
name: "Bancor"
address: "0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C"
symbol: "BNT"
}
{
name: "BRAT"
address: "0x9E77D5a1251b6F7D456722A6eaC6D2d5980bd891"
symbol: "BRAT"
}
{
name: "Bitquence"
address: "0x5Af2Be193a6ABCa9c8817001F45744777Db30756"
symbol: "BQX"
}
{
name: "Change Bank"
address: "0x7d4b8Cce0591C9044a22ee543533b72E976E36C3"
symbol: "CAG"
}
{
name: "BlockCAT"
address: "0x56ba2Ee7890461f463F7be02aAC3099f6d5811A8"
symbol: "CAT"
}
{
name: "CoinDash"
address: "0x177d39AC676ED1C67A2b268AD7F1E58826E5B0af"
symbol: "CDT"
}
{
name: "Cofound.it"
address: "0x12FEF5e57bF45873Cd9B62E9DBd7BFb99e32D73e"
symbol: "CFI"
}
{
name: "Cobinhood"
address: "0xb2f7eb1f2c37645be61d73953035360e768d81e6"
symbol: "COB"
}
{
name: "Creditbit"
address: "0xAef38fBFBF932D1AeF3B808Bc8fBd8Cd8E1f8BC5"
symbol: "CRB"
}
{
name: "Credo"
address: "0x4E0603e2A27A30480E5e3a4Fe548e29EF12F64bE"
symbol: "CREDO"
}
{
name: "Civic"
address: "0x41e5560054824eA6B0732E656E3Ad64E20e94E45"
symbol: "CVC"
}
{
name: "Dalecoin"
address: "0x07d9e49ea402194bf48a8276dafb16e4ed633317"
symbol: "DALC"
}
{
name: "TheDAO"
address: "0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413"
symbol: "DAO"
}
{
name: "DATAcoin"
address: "0x0cf0ee63788a0849fe5297f3407f701e122cc023"
symbol: "DATA (Streamr)"
}
{
name: "DataBroker DAO Token"
address: "0x1b5f21ee98eed48d292e8e2d3ed82b40a9728a22"
symbol: "DATA (DataBrokerDAO)"
}
{
name: "Digital Developers Fund Token "
address: "0xcC4eF9EEAF656aC1a2Ab886743E98e97E090ed38"
symbol: "DDF"
}
{
name: "DENT"
address: "0x3597bfD533a99c9aa083587B074434E61Eb0A258"
symbol: "DENT"
}
{
name: "DGD"
address: "0xE0B7927c4aF23765Cb51314A0E0521A9645F0E2A"
symbol: "DGD"
}
{
name: "DICE"
address: "0x2e071D2966Aa7D8dECB1005885bA1977D6038A65"
symbol: "DICE"
}
{
name: "district0x"
address: "0x0AbdAce70D3790235af448C88547603b945604ea"
symbol: "DNT"
}
{
name: "Droplex"
address: "0x3c75226555FC496168d48B88DF83B95F16771F37"
symbol: "DROP"
}
{
name: "DA Power Play Token"
address: "0x01b3Ec4aAe1B8729529BEB4965F27d008788B0EB"
symbol: "DPP"
}
{
name: "DCORP"
address: "0x621d78f2EF2fd937BFca696CabaF9A779F59B3Ed"
symbol: "DRP"
}
{
name: "EtherCarbon"
address: "0xa578aCc0cB7875781b7880903F4594D13cFa8B98"
symbol: "ECN"
}
{
name: "Eidoo Token"
address: "0xced4e93198734ddaff8492d525bd258d49eb388e"
symbol: "EDO"
}
{
name: "EasyHomes"
address: "0xf9F0FC7167c311Dd2F1e21E9204F87EBA9012fB2"
symbol: "EHT"
}
{
name: "Edgeless"
address: "0x08711D3B02C8758F2FB3ab4e80228418a7F8e39c"
symbol: "EDG"
}
{
name: "elixir"
address: "0xc8C6A31A4A806d3710A7B38b7B296D2fABCCDBA8"
symbol: "ELIX"
}
{
name: "EthereumMovieVenture"
address: "0xB802b24E0637c2B87D2E8b7784C055BBE921011a"
symbol: "EMV"
}
{
name: "EnjinCoin"
address: "0xF629cBd94d3791C9250152BD8dfBDF380E2a3B9c"
symbol: "ENJ"
}
{
name: "EOS"
address: "0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0"
symbol: "EOS"
}
{
name: "EthBits ETBS Token "
address: "0x1b9743f556d65e757c4c650b4555baf354cb8bd3"
symbol: "ETBS"
}
{
name: "FARAD"
address: "0x190e569bE071F40c704e15825F285481CB74B6cC"
symbol: "FAM"
}
{
name: "FinTech Coin"
address: "0xe6f74dcfa0e20883008d8c16b6d9a329189d0c30"
symbol: "FTC"
}
{
name: "Fuel Token"
address: "0xEA38eAa3C86c8F9B751533Ba2E562deb9acDED40"
symbol: "FUEL"
}
{
name: "FundYourselfNow"
address: "0x419D0d8BdD9aF5e606Ae2232ed285Aff190E711b"
symbol: "FUN"
}
{
name: "HelloGold Gold Backed Token"
address: "0x7585F835ae2d522722d2684323a0ba83401f32f5"
symbol: "GBT"
}
{
name: "SGelderGER"
address: "0x24083Bb30072643C3bB90B44B7285860a755e687"
symbol: "GELD"
}
{
name: "Gnosis"
address: "0x6810e776880C02933D47DB1b9fc05908e5386b96"
symbol: "GNO"
}
{
name: "Golem"
address: "0xa74476443119A942dE498590Fe1f2454d7D4aC0d"
symbol: "GNT"
}
{
name: "Game.com Token"
address: "0xB70835D7822eBB9426B56543E391846C107bd32C"
symbol: "GTC"
}
{
name: "GoldenTickets"
address: "0x025abAD9e518516fdaAFBDcdB9701b37fb7eF0FA"
symbol: "GTKT"
}
{
name: "Guppy"
address: "0xf7B098298f7C69Fc14610bf71d5e02c60792894C"
symbol: "GUP"
}
{
name: "H2O Token"
address: "0xFeeD1a53bd53FFE453D265FC6E70dD85f8e993b6"
symbol: "H2O"
}
{
name: "HelloGold"
address: "0xba2184520A1cC49a6159c57e61E1844E085615B6"
symbol: "HGT"
}
{
name: "HackerGold"
address: "0x14F37B574242D366558dB61f3335289a5035c506"
symbol: "HKG"
}
{
name: "Humaniq"
address: "0xcbCC0F036ED4788F63FC0fEE32873d6A7487b908"
symbol: "HMQ"
}
{
name: "Decision Token"
address: "0x554C20B7c486beeE439277b4540A434566dC4C02"
symbol: "HST"
}
{
name: "IDICE"
address: "0x5a84969bb663fb64F6d015DcF9F622Aedc796750"
symbol: "ICE"
}
{
name: "ICONOMI"
address: "0x888666CA69E0f178DED6D75b5726Cee99A87D698"
symbol: "ICN"
}
{
name: "ICOS"
address: "0x014B50466590340D41307Cc54DCee990c8D58aa8"
symbol: "ICOS"
}
{
name: "IDEA Token"
address: "0x814cafd4782d2e728170fda68257983f03321c58"
symbol: "IDEA"
}
{
name: "Feed"
address: "0x7654915a1b82d6d2d0afc37c52af556ea8983c7e"
symbol: "IFT"
}
{
name: "Digital Zone of Immaterial Pictorial Sensibility"
address: "0x88AE96845e157558ef59e9Ff90E766E22E480390"
symbol: "IKB"
}
{
name: "Immortal"
address: "0x22E5F62D0FA19974749faa194e3d3eF6d89c08d7"
symbol: "IMT"
}
{
name: "Indorse"
address: "0xf8e386EDa857484f5a12e4B5DAa9984E06E73705"
symbol: "IND"
}
{
name: "Intelligent Trading Technologies"
address: "0x0aeF06DcCCC531e581f0440059E6FfCC206039EE"
symbol: "ITT"
}
{
name: "iXledger"
address: "0xfca47962d45adfdfd1ab2d972315db4ce7ccf094"
symbol: "IXT"
}
{
name: "JET (new)"
address: "0x8727c112C712c4a03371AC87a74dD6aB104Af768"
symbol: "JET (new)"
}
{
name: "JET (old)"
address: "0xc1E6C6C681B286Fb503B36a9dD6c1dbFF85E73CF"
symbol: "JET (old)"
}
{
name: "JetCoins"
address: "0x773450335eD4ec3DB45aF74f34F2c85348645D39"
symbol: "JetCoins"
}
{
name: "KickCoin"
address: "0x27695E09149AdC738A978e9A678F99E4c39e9eb9"
symbol: "KICK"
}
{
name: "Kin"
address: "0x818Fc6C2Ec5986bc6E2CBf00939d90556aB12ce5"
symbol: "KIN"
}
{
name: "KyberNetwork"
address: "0xdd974D5C2e2928deA5F71b9825b8b646686BD200"
symbol: "KNC"
}
{
name: "Kaizen"
address: "0x9541FD8B9b5FA97381783783CeBF2F5fA793C262"
symbol: "KZN"
}
{
name: "PureLifeCoin"
address: "0xff18dbc487b4c2e3222d115952babfda8ba52f5f"
symbol: "LIFE"
}
{
name: "ChainLink Token"
address: "0x514910771af9ca656af840dff83e8264ecf986ca"
symbol: "LINK"
}
{
name: "LookRev"
address: "0x21aE23B882A340A22282162086bC98D3E2B73018"
symbol: "LOK"
}
{
name: "Lencer Token"
address: "0x63e634330A20150DbB61B15648bC73855d6CCF07"
symbol: "LNC"
}
{
name: "Loopring"
address: "0xEF68e7C694F40c8202821eDF525dE3782458639f"
symbol: "LRC"
}
{
name: "LUCKY"
address: "0xFB12e3CcA983B9f59D90912Fd17F8D745A8B2953"
symbol: "LUCK"
}
{
name: "Lunyr"
address: "0xfa05A73FfE78ef8f1a739473e462c54bae6567D9"
symbol: "LUN"
}
{
name: "Decentraland"
address: "0x0F5D2fB29fb7d3CFeE444a200298f468908cC942"
symbol: "MANA"
}
{
name: "Embers"
address: "0x386467f1f3ddbe832448650418311a479eecfc57"
symbol: "MBRS"
}
{
name: "MCAP"
address: "0x93E682107d1E9defB0b5ee701C71707a4B2E46Bc"
symbol: "MCAP"
}
{
name: "Musiconomi"
address: "0x138A8752093F4f9a79AaeDF48d4B9248fab93c9C"
symbol: "MCI"
}
{
name: "Monaco"
address: "0xB63B606Ac810a52cCa15e44bB630fd42D8d1d83d"
symbol: "MCO"
}
{
name: "Moeda Loyalty Points"
address: "0x51DB5Ad35C671a87207d88fC11d593AC0C8415bd"
symbol: "MDA"
}
{
name: "MobileGo"
address: "0x40395044Ac3c0C57051906dA938B54BD6557F212"
symbol: "MGO"
}
{
name: "Mainstreet"
address: "0xe23cd160761f63FC3a1cF78Aa034b6cdF97d3E0C"
symbol: "MIT"
}
{
name: "MKR - Maker"
address: "0xC66eA802717bFb9833400264Dd12c2bCeAa34a6d"
symbol: "MKR"
}
{
name: "Melon"
address: "0xBEB9eF514a379B997e0798FDcC901Ee474B6D9A1"
symbol: "MLN"
}
{
name: "minereum"
address: "0x1a95B271B0535D15fa49932Daba31BA612b52946"
symbol: "MNE"
}
{
name: "Macroverse Token"
address: "0xAB6CF87a50F17d7F5E1FEaf81B6fE9FfBe8EBF84"
symbol: "MRV"
}
{
name: "Mothership"
address: "0x68AA3F232dA9bdC2343465545794ef3eEa5209BD"
symbol: "MSP"
}
{
name: "Monetha"
address: "0xaF4DcE16Da2877f8c9e00544c93B62Ac40631F16"
symbol: "MTH"
}
{
name: "Metal"
address: "0xF433089366899D83a9f26A773D59ec7eCF30355e"
symbol: "MTL"
}
{
name: "MatryxToken"
address: "0x7FC408011165760eE31bE2BF20dAf450356692Af"
symbol: "MTR"
}
{
name: "MyEtherWalet Donations Tokens"
address: "0xf7e983781609012307f2514f63D526D83D24F466"
symbol: "MYD"
}
{
name: "Mysterium"
address: "0xa645264C5603E96c3b0B078cdab68733794B0A71"
symbol: "MYST"
}
{
name: "NimiqNetwork"
address: "0xcfb98637bcae43C13323EAa1731cED2B716962fD"
symbol: "NET"
}
{
name: "Numerai"
address: "0x1776e1F26f98b1A5dF9cD347953a26dd3Cb46671"
symbol: "NMR"
}
{
name: "Nexium"
address: "0x45e42D659D9f9466cD5DF622506033145a9b89Bc"
symbol: "NxC"
}
{
name: "Nexxus"
address: "0x5c6183d10A00CD747a6Dbb5F658aD514383e9419"
symbol: "NXX"
}
{
name: "NIMFA Token"
address: "0xe26517A9967299453d3F1B48Aa005E6127e67210"
symbol: "NIMFA"
}
{
name: "OpenANX"
address: "0x701C244b988a513c945973dEFA05de933b23Fe1D"
symbol: "OAX"
}
{
name: "Ohni"
address: "0x7F2176cEB16dcb648dc924eff617c3dC2BEfd30d"
symbol: "OHNI"
}
{
name: "OmiseGO"
address: "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07"
symbol: "OMG"
}
{
name: "oneK"
address: "0xb23be73573bc7e03db6e5dfc62405368716d28a8"
symbol: "ONEK"
}
{
name: "Opus"
address: "0x4355fC160f74328f9b383dF2EC589bB3dFd82Ba0"
symbol: "OPT"
}
{
name: "TenXPay"
address: "0xB97048628DB6B661D4C2aA833e95Dbe1A905B280"
symbol: "PAY"
}
{
name: "PIX"
address: "0x8eFFd494eB698cc399AF6231fCcd39E08fd20B15"
symbol: "PIX"
}
{
name: "Herocoin"
address: "0xE477292f1B3268687A29376116B0ED27A9c76170"
symbol: "PLAY"
}
{
name: "Polybius"
address: "0x0AfFa06e7Fbe5bC9a764C979aA66E8256A631f02"
symbol: "PLBT"
}
{
name: "PILLAR"
address: "0xe3818504c1B32bF1557b16C238B2E01Fd3149C17"
symbol: "PLR"
}
{
name: "Pluton"
address: "0xD8912C10681D8B21Fd3742244f44658dBA12264E"
symbol: "PLU"
}
{
name: "Po.et"
address: "0x0e0989b1f9b8a38983c2ba8053269ca62ec9b195"
symbol: "POE"
}
{
name: "StakePool"
address: "0x779B7b713C86e3E6774f5040D9cCC2D43ad375F8"
symbol: "POOL"
}
{
name: "PoSToken"
address: "0xee609fe292128cad03b786dbb9bc2634ccdbe7fc"
symbol: "POS"
}
{
name: "Populous"
address: "0xd4fa1460F537bb9085d22C7bcCB5DD450Ef28e3a"
symbol: "PPT"
}
{
name: "Propy"
address: "0x226bb599a12C826476e3A771454697EA52E9E220"
symbol: "PRO"
}
{
name: "Persian"
address: "0x163733bcc28dbf26B41a8CfA83e369b5B3af741b"
symbol: "PRS"
}
{
name: "Prosper"
address: "0x0c04d4f331da8df75f9e2e271e3f3f1494c66c36"
symbol: "PRSP"
}
{
name: "PornToken"
address: "0x66497a283e0a007ba3974e837784c6ae323447de"
symbol: "PT"
}
{
name: "Patientory"
address: "0x8Ae4BF2C33a8e667de34B54938B0ccD03Eb8CC06"
symbol: "PTOY"
}
{
name: "Quantum"
address: "0x671AbBe5CE652491985342e85428EB1b07bC6c64"
symbol: "QAU"
}
{
name: "Qtum"
address: "0x9a642d6b3368ddc662CA244bAdf32cDA716005BC"
symbol: "QTUM"
}
{
name: "QRL"
address: "0x697beac28B09E122C4332D163985e8a73121b97F"
symbol: "QRL"
}
{
name: "REP"
address: "0xE94327D07Fc17907b4DB788E5aDf2ed424adDff6"
symbol: "REP"
}
{
name: "REX - Real Estate Tokens"
address: "0xf05a9382A4C3F29E2784502754293D88b835109C"
symbol: "REX"
}
{
name: "RLC"
address: "0x607F4C5BB672230e8672085532f7e901544a7375"
symbol: "RLC"
}
{
name: "RouletteToken"
address: "0xcCeD5B8288086BE8c38E23567e684C3740be4D48"
symbol: "RLT"
}
{
name: "Relex"
address: "0x4a42d2c580f83dce404acad18dab26db11a1750e"
symbol: "RLX"
}
{
name: "Render Token"
address: "0x0996bfb5d057faa237640e2506be7b4f9c46de0b"
symbol: "RNDR"
}
{
name: "ROUND"
address: "0x4993CB95c7443bdC06155c5f5688Be9D8f6999a5"
symbol: "ROUND"
}
{
name: "RvT"
address: "0x3d1ba9be9f66b8ee101911bc36d3fb562eac2244"
symbol: "RVT"
}
{
name: "Request Token"
address: "0x8f8221aFbB33998d8584A2B05749bA73c37a938a"
symbol: "REQ"
}
{
name: "Salt"
address: "0x4156D3342D5c385a87D264F90653733592000581"
symbol: "SALT"
}
{
name: "SAN"
address: "0x7C5A0CE9267ED19B22F8cae653F198e3E8daf098"
symbol: "SAN"
}
{
name: "SOCIAL"
address: "0xd7631787B4dCc87b1254cfd1e5cE48e96823dEe8"
symbol: "SCL"
}
{
name: "sensatori"
address: "0x4ca74185532dc1789527194e5b9c866dd33f4e82"
symbol: "sense"
}
{
name: "SGELDER"
address: "0xa1ccc166faf0E998b3E33225A1A0301B1C86119D"
symbol: "SGEL"
}
{
name: "StatusGenesis"
address: "0xd248B0D48E44aaF9c49aea0312be7E13a6dc1468"
symbol: "SGT"
}
{
name: "Shitcoin"
address: "0xEF2E9966eb61BB494E5375d5Df8d67B7dB8A780D"
symbol: "SHIT"
}
{
name: "Smart Investment Fund Token"
address: "0x8a187d5285d316bcbc9adafc08b51d70a0d8e000"
symbol: "SIFT"
}
{
name: "SkinCoin"
address: "0x2bDC0D42996017fCe214b21607a515DA41A9E0C5"
symbol: "SKIN"
}
{
name: "SikobaPreSale"
address: "0x4994e81897a920c0FEA235eb8CEdEEd3c6fFF697"
symbol: "SKO1"
}
{
name: "SmartBillions Tokens"
address: "0x6F6DEb5db0C4994A8283A01D6CFeEB27Fc3bBe9C"
symbol: "Smart"
}
{
name: "SunContract"
address: "0xF4134146AF2d511Dd5EA8cDB1C4AC88C57D60404"
symbol: "SNC"
}
{
name: "SNGLS"
address: "0xaeC2E87E0A235266D9C5ADc9DEb4b2E29b54D009"
symbol: "SNGLS"
}
{
name: "SND Token 1.0"
address: "0xf333b2Ace992ac2bBD8798bF57Bc65a06184afBa"
symbol: "SND"
}
{
name: "SONM"
address: "0x983F6d60db79ea8cA4eB9968C6aFf8cfA04B3c63"
symbol: "SNM"
}
{
name: "StatusNetwork"
address: "0x744d70FDBE2Ba4CF95131626614a1763DF805B9E"
symbol: "SNT"
}
{
name: "Science Power and Research Coin"
address: "0x58bf7df57d9DA7113c4cCb49d8463D4908C735cb"
symbol: "SPARC"
}
{
name: "SPARTA"
address: "0x24aef3bf1a47561500f9430d74ed4097c47f51f2"
symbol: "SPARTA"
}
{
name: "Storj"
address: "0xB64ef51C888972c908CFacf59B47C1AfBC0Ab8aC"
symbol: "STORJ"
}
{
name: "StarCredits"
address: "0x46492473755e8dF960F8034877F61732D718CE96"
symbol: "STRC"
}
{
name: "Stox"
address: "0x006BeA43Baa3f7A6f765F14f10A1a1b08334EF45"
symbol: "STX"
}
{
name: "Substratum"
address: "0x12480E24eb5bec1a9D4369CaB6a80caD3c0A377A"
symbol: "SUB"
}
{
name: "SwarmCity"
address: "0xB9e7F8568e08d5659f5D29C4997173d84CdF2607"
symbol: "SWT"
}
{
name: "Synapse"
address: "0x10b123fddde003243199aad03522065dc05827a0"
symbol: "SYN"
}
{
name: "TAAS"
address: "0xE7775A6e9Bcf904eb39DA2b68c5efb4F9360e08C"
symbol: "TaaS"
}
{
name: "TBOT"
address: "0xAFe60511341a37488de25Bef351952562E31fCc1"
symbol: "TBT"
}
{
name: "TrueFlip"
address: "0xa7f976C360ebBeD4465c2855684D1AAE5271eFa9"
symbol: "TFL"
}
{
name: "TheBillionCoin2"
address: "0xFACCD5Fc83c3E4C3c1AC1EF35D15adf06bCF209C"
symbol: "TBC2"
}
{
name: "TIME"
address: "0x6531f133e6DeeBe7F2dcE5A0441aA7ef330B4e53"
symbol: "TIME"
}
{
name: "Blocktix"
address: "0xEa1f346faF023F974Eb5adaf088BbCdf02d761F4"
symbol: "TIX"
}
{
name: "TokenCard"
address: "0xaAAf91D9b90dF800Df4F55c205fd6989c977E73a"
symbol: "TKN"
}
{
name: "timereum"
address: "0xEe22430595aE400a30FFBA37883363Fbf293e24e"
symbol: "TME"
}
{
name: "Tierion Network Token"
address: "0x08f5a9235b08173b7569f83645d2c7fb55e8ccd8"
symbol: "TNT"
}
{
name: "Trustcoin"
address: "0xCb94be6f13A1182E4A4B6140cb7bf2025d28e41B"
symbol: "TRST"
}
{
name: "Unicorns"
address: "0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7"
symbol: "Unicorn 🦄"
}
{
name: "Veritaseum"
address: "0x8f3470A7388c05eE4e7AF3d01D8C722b0FF52374"
symbol: "VERI"
}
{
name: "VeChain Token"
address: "0xD850942eF8811f2A866692A623011bDE52a462C1"
symbol: "VEN"
}
{
name: "Vibe Coin"
address: "0xe8ff5c9c75deb346acac493c463c8950be03dfba"
symbol: "VIBE"
}
{
name: "VIBEX Exchange Token"
address: "0x882448f83d90b2bf477af2ea79327fdea1335d93"
symbol: "VIBEX"
}
{
name: "Vibe"
address: "0x2C974B2d0BA1716E644c1FC59982a89DDD2fF724"
symbol: "VIB"
}
{
name: "VOISE"
address: "0x83eEA00D838f92dEC4D1475697B9f4D3537b56E3"
symbol: "VOISE"
}
{
name: "VRSilver"
address: "0xeDBaF3c5100302dCddA53269322f3730b1F0416d"
symbol: "VRS"
}
{
name: "vSlice"
address: "0x5c543e7AE0A1104f78406C340E9C64FD9fCE5170"
symbol: "VSL"
}
{
name: "VOISE(OLD)"
address: "0x82665764ea0b58157E1e5E9bab32F68c76Ec0CdF"
symbol: "VSM(OLD)"
}
{
name: "We Bet Crypto"
address: "0x03c18d649e743ee0b09f28a81d33575f03af9826"
symbol: "WBC"
}
{
name: "WePower Contribution Token"
address: "0x6a0A97E47d15aAd1D132a1Ac79a480E3F2079063"
symbol: "WCT"
}
{
name: "Wi Coin"
address: "0x5e4ABE6419650CA839Ce5BB7Db422b881a6064bB"
symbol: "WiC"
}
{
name: "Wings"
address: "0x667088b212ce3d06a1b553a7221E1fD19000d9aF"
symbol: "WINGS"
}
{
name: "Xaurum"
address: "0x4DF812F6064def1e5e029f1ca858777CC98D2D81"
symbol: "XAUR"
}
{
name: "Sphre AIR"
address: "0xB110eC7B1dcb8FAB8dEDbf28f53Bc63eA5BEdd84"
symbol: "XID"
}
{
name: "Rialto"
address: "0xB24754bE79281553dc1adC160ddF5Cd9b74361a4"
symbol: "XRL"
}
{
name: "0x"
address: "0xE41d2489571d322189246DaFA5ebDe1F4699F498"
symbol: "ZRX"
}
]
| 22.13004 | 61 | 0.644149 |
35c23ccc6fccf1d6c0b1bf1dd505633d04c6c31c | 2,209 | {:cimport, :internalize, :eq, :ffi, :lib, :cstr, :NULL, :OK, :FAIL} = require 'test.unit.helpers'
users = cimport './src/nvim/os/os.h', 'unistd.h'
garray_new = () ->
ffi.new 'garray_T[1]'
garray_get_len = (array) ->
array[0].ga_len
garray_get_item = (array, index) ->
(ffi.cast 'void **', array[0].ga_data)[index]
describe 'users function', ->
-- will probably not work on windows
current_username = os.getenv 'USER'
describe 'os_get_usernames', ->
it 'returns FAIL if called with NULL', ->
eq FAIL, users.os_get_usernames NULL
it 'fills the names garray with os usernames and returns OK', ->
ga_users = garray_new!
eq OK, users.os_get_usernames ga_users
user_count = garray_get_len ga_users
assert.is_true user_count > 0
current_username_found = false
for i = 0, user_count - 1
name = ffi.string (garray_get_item ga_users, i)
if name == current_username
current_username_found = true
assert.is_true current_username_found
describe 'os_get_user_name', ->
it 'should write the username into the buffer and return OK', ->
name_out = ffi.new 'char[100]'
eq OK, users.os_get_user_name(name_out, 100)
eq current_username, ffi.string name_out
describe 'os_get_uname', ->
it 'should write the username into the buffer and return OK', ->
name_out = ffi.new 'char[100]'
user_id = lib.getuid!
eq OK, users.os_get_uname(user_id, name_out, 100)
eq current_username, ffi.string name_out
it 'should FAIL if the userid is not found', ->
name_out = ffi.new 'char[100]'
-- hoping nobody has this uid
user_id = 2342
eq FAIL, users.os_get_uname(user_id, name_out, 100)
eq '2342', ffi.string name_out
describe 'os_get_user_directory', ->
it 'should return NULL if called with NULL', ->
eq NULL, users.os_get_user_directory NULL
it 'should return $HOME for the current user', ->
home = os.getenv('HOME')
eq home, ffi.string (users.os_get_user_directory current_username)
it 'should return NULL if the user is not found', ->
eq NULL, users.os_get_user_directory 'neovim_user_not_found_test'
| 31.112676 | 97 | 0.669081 |
bfcba84257c3c85be6ba6efca5244d76f9731764 | 1,079 | io.stdout\setvbuf'no'
export DEBUG = false
export statestack
export soundmanager
export wScr, hScr
wScr, hScr = love.graphics.getWidth, love.graphics.getHeight
export startsWith = (str,start) ->
return string.sub(str,1,string.len(start))==start
export lua_mod = (x, m) ->
-- returns a modulo of x usable with 1-based table
return ((x - 1) % m) + 1
love.load = ->
require "states/statestack"
require "states/menus/mainmenu"
require "sound_manager"
statestack = StateStack()
statestack\push(MainMenu())
soundmanager = SoundManager()
current_state = ->
statestack\peek()
love.draw = ->
current_state()\draw()
love.update = (dt) ->
current_state()\update(dt)
love.keypressed = (key) ->
current_state()\keypressed(key)
love.keyreleased = (key) ->
current_state()\keyreleased(key)
love.mousepressed = (x, y, button) ->
current_state()\mousepressed(x, y, button)
love.mousereleased = (x, y, button) ->
current_state()\mousereleased(x, y, button)
love.textinput = (char) ->
current_state()\textinput(char)
| 22.020408 | 60 | 0.676552 |
47e1c8b693f3c8d736dce50689ea7267d0aa846d | 6,343 | class Option
-- If optType is a "bool" or an "int", @value is the boolean/integer value of the option.
-- Additionally, when optType is an "int":
-- - opts.step specifies the step on which the values are changed.
-- - opts.min specifies a minimum value for the option.
-- - opts.max specifies a maximum value for the option.
-- - opts.altDisplayNames is a int->string dict, which contains alternative display names
-- for certain values.
-- If optType is a "list", @value is the index of the current option, inside opts.possibleValues.
-- opts.possibleValues is a array in the format
-- {
-- {value, displayValue}, -- Display value can be omitted.
-- {value}
-- }
-- setValue will be called for the constructor argument.
new: (optType, displayText, value, opts) =>
@optType = optType
@displayText = displayText
@opts = opts
@value = 1
self\setValue(value)
-- Whether we have a "previous" option (for left key)
hasPrevious: =>
switch @optType
when "bool"
return true
when "int"
if @opts.min
return @value > @opts.min
else
return true
when "list"
return @value > 1
-- Analogous of hasPrevious.
hasNext: =>
switch @optType
when "bool"
return true
when "int"
if @opts.max
return @value < @opts.max
else
return true
when "list"
return @value < #@opts.possibleValues
leftKey: =>
switch @optType
when "bool"
@value = not @value
when "int"
@value -= @opts.step
if @opts.min and @opts.min > @value
@value = @opts.min
when "list"
@value -= 1 if @value > 1
rightKey: =>
switch @optType
when "bool"
@value = not @value
when "int"
@value += @opts.step
if @opts.max and @opts.max < @value
@value = @opts.max
when "list"
@value += 1 if @value < #@opts.possibleValues
getValue: =>
switch @optType
when "bool"
return @value
when "int"
return @value
when "list"
{value, _} = @opts.possibleValues[@value]
return value
setValue: (value) =>
switch @optType
when "bool"
@value = value
when "int"
-- TODO Should we obey opts.min/max? Or just trust the script to do the right thing(tm)?
@value = value
when "list"
set = false
for i, possiblePair in ipairs @opts.possibleValues
{possibleValue, _} = possiblePair
if possibleValue == value
set = true
@value = i
break
if not set
msg.warn("Tried to set invalid value #{value} to #{@displayText} option.")
getDisplayValue: =>
switch @optType
when "bool"
return @value and "yes" or "no"
when "int"
if @opts.altDisplayNames and @opts.altDisplayNames[@value]
return @opts.altDisplayNames[@value]
else
return "#{@value}"
when "list"
{value, displayValue} = @opts.possibleValues[@value]
return displayValue or value
draw: (ass, selected) =>
if selected
ass\append("#{bold(@displayText)}: ")
else
ass\append("#{@displayText}: ")
-- left arrow unicode
ass\append("◀ ") if self\hasPrevious!
ass\append(self\getDisplayValue!)
-- right arrow unicode
ass\append(" ▶") if self\hasNext!
ass\append("\\N")
class EncodeOptionsPage extends Page
new: (callback) =>
@callback = callback
@currentOption = 1
-- TODO this shouldn't be here.
scaleHeightOpts =
possibleValues: {{-1, "no"}, {144}, {240}, {360}, {480}, {540}, {720}, {1080}, {1440}, {2160}}
filesizeOpts =
step: 250
min: 0
altDisplayNames:
[0]: "0 (constant quality)"
crfOpts =
step: 1
min: -1
altDisplayNames:
[-1]: "disabled"
fpsOpts =
possibleValues: {{-1, "source"}, {15}, {24}, {30}, {48}, {50}, {60}, {120}, {240}}
-- I really dislike hardcoding this here, but, as said below, order in dicts isn't
-- guaranteed, and we can't use the formats dict keys.
formatIds = {"webm-vp8", "webm-vp9", "mp4", "mp4-nvenc", "raw", "mp3", "gif"}
formatOpts =
possibleValues: [{fId, formats[fId].displayName} for fId in *formatIds]
-- This could be a dict instead of a array of pairs, but order isn't guaranteed
-- by dicts on Lua.
@options = {
{"output_format", Option("list", "Output Format", options.output_format, formatOpts)}
{"twopass", Option("bool", "Two Pass", options.twopass)},
{"apply_current_filters", Option("bool", "Apply Current Video Filters", options.apply_current_filters)}
{"scale_height", Option("list", "Scale Height", options.scale_height, scaleHeightOpts)},
{"strict_filesize_constraint", Option("bool", "Strict Filesize Constraint", options.strict_filesize_constraint)},
{"write_filename_on_metadata", Option("bool", "Write Filename on Metadata", options.write_filename_on_metadata)},
{"target_filesize", Option("int", "Target Filesize", options.target_filesize, filesizeOpts)},
{"crf", Option("int", "CRF", options.crf, crfOpts)},
{"fps", Option("list", "FPS", options.fps, fpsOpts)},
}
@keybinds =
"LEFT": self\leftKey
"RIGHT": self\rightKey
"UP": self\prevOpt
"DOWN": self\nextOpt
"ENTER": self\confirmOpts
"ESC": self\cancelOpts
getCurrentOption: =>
return @options[@currentOption][2]
leftKey: =>
(self\getCurrentOption!)\leftKey!
self\draw!
rightKey: =>
(self\getCurrentOption!)\rightKey!
self\draw!
prevOpt: =>
@currentOption = math.max(1, @currentOption - 1)
self\draw!
nextOpt: =>
@currentOption = math.min(#@options, @currentOption + 1)
self\draw!
confirmOpts: =>
for _, optPair in ipairs @options
{optName, opt} = optPair
-- Set the global options object.
options[optName] = opt\getValue!
self\hide!
self.callback(true)
cancelOpts: =>
self\hide!
self.callback(false)
draw: =>
window_w, window_h = mp.get_osd_size()
ass = assdraw.ass_new()
ass\new_event()
self\setup_text(ass)
ass\append("#{bold('Options:')}\\N\\N")
for i, optPair in ipairs @options
opt = optPair[2]
opt\draw(ass, @currentOption == i)
ass\append("\\N▲ / ▼: navigate\\N")
ass\append("#{bold('ENTER:')} confirm options\\N")
ass\append("#{bold('ESC:')} cancel\\N")
mp.set_osd_ass(window_w, window_h, ass.text)
| 29.09633 | 117 | 0.622261 |
6ee1567ebe8e25794aac241267b108a07deff37a | 3,577 | make = (x, y) ->
player = {
:x
:y
w: 16
h: 16
direction: 1,
dx: 0
dy: 0,
speed: 20
friction: 5
weapon: {}
tag: "player"
}
player.input = (dt) =>
dx, dy = 0, 0
if love.keyboard.isDown "w"
dy = -1
elseif love.keyboard.isDown "s"
dy = 1
if love.keyboard.isDown "a"
dx = -1
elseif love.keyboard.isDown "d"
dx = 1
if dy != 0 and dy != 0
len = math.sqrt dx^2 + dy^2
@dx += (dx / len) * @speed * dt
@dy += (dy / len) * @speed * dt
else
@dx += dx * @speed * dt
@dy += dy * @speed * dt
@direction = -math.sign @dx unless 0 == math.sign @dx
player.update = (dt) =>
@input dt
@x, @y, collisions = world\move @, @x + @dx, @y + @dy
for c in *collisions
if c.normal.x != 0
@dx = 0
if c.normal.y != 0
@dy = 0
@dx = math.lerp @dx, 0, dt * @friction
@dy = math.lerp @dy, 0, dt * @friction
with game.camera
.x = math.lerp .x, @x - love.graphics.getWidth! / 2 / game.camera.sx, dt * 5
.y = math.lerp .y, @y - love.graphics.getHeight! / 2 / game.camera.sy, dt * 5
-- light_world\setTranslation -@x * 5 + love.graphics.getWidth! / 2, -@y * 5 + love.graphics.getHeight! / 2, 5
with light_world
.l = math.lerp .l, -@x * game.zoom + love.graphics.getWidth! / 2, dt * game.zoom
.t = math.lerp .t, -@y * game.zoom + love.graphics.getHeight! / 2, dt * game.zoom
.s = game.zoom
mouse_x = game.camera.x + love.mouse.getX! / game.camera.sx
mouse_y = game.camera.y + love.mouse.getY! / game.camera.sy
@weapon.left\update dt, mouse_x, mouse_y if @weapon.left
@weapon.right\update dt, mouse_x, mouse_y if @weapon.right
light_player\setPosition @x + @w / 2, @y + @h / 2
player.draw = =>
if @weapon.right.flip == 1
@weapon.right\draw! if @weapon.right
else
@weapon.left\draw! if @weapon.left
with love.graphics
.setColor 1, 1, 1
w = sprites.player\getWidth!
h = sprites.player\getHeight!
.draw sprites.player, @x + @w / 2, @y + @h / 2, 0, @weapon.right.flip * @w / w, @h / h, w / 2, h / 2
if @weapon.right.flip == -1
@weapon.right\draw! if @weapon.right
else
@weapon.left\draw! if @weapon.left
player.weapon_pos_right = =>
if @weapon.right.flip == 1
@x + @w / 5, @y + @h / 1.35
else
@x + @w / 2, @y + @h / 1.25
player.weapon_pos_left = =>
if @weapon.left.flip == -1
@x + @w / 1.6, @y + @h / 1.45
else
@x + @w / 2, @y + @h / 1.25
player.mousepressed = (x, y, button) =>
if button == 1
mouse_x = game.camera.x + love.mouse.getX! / game.camera.sx
mouse_y = game.camera.y + love.mouse.getY! / game.camera.sy
@weapon.left\shoot mouse_x, mouse_y if @weapon.left
@weapon.right\shoot mouse_x, mouse_y if @weapon.right
elseif button == 2
game.spawn "enemy", @x, @y, "tony"
world\add player, x, y, player.w, player.h
player.weapon.right = weapons.gun.make player, "regular", true
player.weapon.left = weapons.gun.make player, "regular", false
player
{
:make
} | 29.319672 | 122 | 0.484205 |
62a5d9c5a1a0a37ca39a1a651b8a48d931930b81 | 871 | unpack = unpack or table.unpack
export class EventHandler
new: (eventName, callbacks) =>
@callbacks = callbacks or { }
if (type eventName == "String")
_G[eventName] = (...) ->
@processEvent ...
addCallback: (filter, fn, owner) =>
sameParams = (v) -> v.filter == filter and v.fn == fn and v.owner == owner
if not Util.trueInTable @callbacks, sameParams
table.insert @callbacks, { :filter, :fn, :owner }
return true
false
removeCallback: (fn, owner) =>
sameParams = (v) -> v.fn == fn and v.owner == owner
i = Util.trueInTable @callbacks, sameParams
if i
table.remove @callbacks, i
return true
false
processEvent: (...) =>
args = {...}
i, v = Util.trueInTable @callbacks, (v) -> v.filter unpack args
if i
if v.owner
v.fn v.owner, ...
else
v.fn ...
| 26.393939 | 78 | 0.576349 |
f7fa98de99de354925c0afc6352a703050c3ee42 | 304 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
core = require 'ljglibs.core'
require 'ljglibs.cdefs.cairo'
ffi = require 'ffi'
C, ffi_string, ffi_gc, ffi_new = ffi.C, ffi.string, ffi.gc, ffi.new
core.auto_loading 'cairo', {
}
| 27.636364 | 79 | 0.733553 |
84746a5e79867ba5d3d62c843a4db2f079a0d3fd | 2,905 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:app, :interact, :timer} = howl
{:List, :ListWidget} = howl.ui
{:Matcher} = howl.util
class SelectionList
run: (@finish, @opts) =>
@command_line = app.window.command_line
if not (@opts.matcher or @opts.items) or (@opts.matcher and @opts.items)
error 'One of "matcher" or "items" required'
@command_line.prompt = @opts.prompt
@command_line.title = @opts.title
matcher = @opts.matcher or Matcher @opts.items
@list = List matcher,
on_selection_change: @\_handle_change
reverse: @opts.reverse
explain: @opts.explain
@list.columns = @opts.columns
@list_widget = ListWidget @list, never_shrink: true
@list_widget.max_height_request = math.floor app.window.allocated_height * 0.5
@showing_list = false
if not @opts.hide_until_tab
@show_list!
@quick_selections = {}
if @opts.items
for item in *@opts.items
if item.quick_select
if type(item.quick_select) == 'table'
for quick_select in *item.quick_select
@quick_selections[quick_select] = item
else
@quick_selections[item.quick_select] = item
if @opts.text
@command_line\write @opts.text
@on_update @opts.text
else
spillover = @command_line\pop_spillover!
@command_line\write spillover
if @opts.selection
@list\update spillover
@list.selection = @opts.selection
timer.asap -> @_handle_change!
else
@on_update spillover
refresh: => @list\update @command_line.text, true
show_list: =>
@command_line\add_widget 'completion_list', @list_widget
@showing_list = true
on_update: (text) =>
if @quick_selections[text]
self.finish
selection: @quick_selections[text]
:text
quick: true
return
@_change_triggered = false
@list\update text
@_handle_change! unless @_change_triggered
_handle_change: =>
@_change_triggered = true
if @opts.on_change
@opts.on_change @list.selection, @command_line.text, @list.items
submit: =>
if @list.selection
self.finish
selection: @list.selection
text: @command_line.text
elseif @opts.allow_new_value
self.finish text: @command_line.text
else
log.error 'Invalid selection'
keymap:
enter: => @submit!
escape: => self.finish!
tab: =>
if not @showing_list
@show_list!
space: =>
return false unless @opts.submit_on_space
if @command_line.text.is_empty
@show_list!
else
@submit!
handle_back: =>
if @opts.cancel_on_back
self.finish back: true
interact.register
name: 'select'
description: 'Get selection made by user from a list of items'
factory: SelectionList
| 26.651376 | 82 | 0.650602 |
bbb770119287d50754c2b1910d7d50d90c50aeec | 170 | require "test"
require "axel.library"
require "point_test"
require "rectangle_test"
require "vector_test"
require "entity_test"
require "group_test"
require "scratchpad" | 18.888889 | 24 | 0.805882 |
ab316728fdfc2e3cef6443ccaeab0bf259849f8a | 8,797 | -- fasty CMS
sass = require 'sass'
lapis = require 'lapis'
stringy = require 'stringy'
shell = require 'resty.shell'
encoding = require 'lapis.util.encoding'
app_config = require "lapis.config"
config = app_config.get!
db_config = app_config.get("db_#{config._name}")
import aqls from require 'lib.aqls'
import basic_auth, is_auth from require 'lib.basic_auth'
import after_dispatch from require 'lapis.nginx.context'
import write_content, read_file from require 'lib.service'
import uuid, check_valid_lang, define_content_type, table_deep_merge from require 'lib.utils'
import auth_arangodb, aql, list_databases from require 'lib.arango'
import trim, from_json, to_json, unescape from require 'lapis.util'
import dynamic_replace, dynamic_page, page_info, splat_to_table
load_page_by_slug, load_redirection, prepare_bindvars from require 'lib.concerns'
jwt = {}
global_data = {}
all_domains = nil
settings = {}
no_db = {}
sub_domain = ''
last_db_connect = os.time(os.date("!*t"))
app_config "development", -> measure_performance true
--------------------------------------------------------------------------------
define_subdomain = ()=>
sub_domain = @req.headers['x-app'] or stringy.split(@req.headers.host, '.')[1]
--------------------------------------------------------------------------------
load_settings = ()=>
if (os.time(os.date("!*t")) - last_db_connect) > (config.db_ttl and config.db_ttl or 10) -- reconnect each 10 seconds
jwt[sub_domain] = nil
last_db_connect = os.time(os.date("!*t"))
jwt[sub_domain] = auth_arangodb(sub_domain, db_config) if jwt[sub_domain] == nil or all_domains == nil
all_domains = list_databases! if all_domains == nil
if all_domains["db_#{sub_domain}"] == nil
no_db[sub_domain] = true
else
global_data[sub_domain] = aql("db_#{sub_domain}", aqls.settings)[1]
global_data[sub_domain]['partials'] = {}
settings[sub_domain] = global_data[sub_domain].settings[1]
--------------------------------------------------------------------------------
lua_files = (path)=>
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
f = path..'/'..file
attr = lfs.attributes (f)
if(type(attr) ~= "nil")
assert(type(attr) == "table")
if(attr.mode == "directory")
lua_files(@, f)
else
if stringy.split(file, ".")[2] == "lua"
path = stringy.split(f, ".")[1]\gsub("/", ".")
@include path
--------------------------------------------------------------------------------
class extends lapis.Application
@before_filter=>
start_time = os.clock!
define_subdomain(@)
after_dispatch ->
if config.measure_performance
print to_json(ngx.ctx.performance)
print to_json("#{(os.clock! - start_time) * 1000}ms")
handle_error: (err, trace)=>
if config._name == 'production' then
print(to_json(err) .. to_json(trace))
@err = err
display_error_page(@, 500)
else
super err, trace
@enable 'etlua'
@include 'applications.uploads'
@include 'applications.services'
@include 'applications.assets'
lua_files(@, "git/lua") if os.rename("git/lua", "git/lua")
layout: false -- we don't need a layout, it will be loaded dynamically
------------------------------------------------------------------------------
display_error_page = (status=500, headers={})=>
error_page = from_json(settings[sub_domain].home)["error_#{status}"]
if error_page ~= nil then
display_page(@, error_page, 404)
else
render: "error_#{status}" , status: status, headers: headers
------------------------------------------------------------------------------
display_page = (slug=nil, status=200)=>
db_name = "db_#{sub_domain}"
asset = ngx.location.capture("/git/#{db_name}/public/#{@req.parsed_url.path}")
if asset.status == 200
content_type: define_content_type(@req.parsed_url.path), status: 200, asset.body
else
slug = @params.slug if slug == nil
slug = unescape(slug)
page_content_type = define_content_type(slug)
slug = slug\gsub(".pdf", "") if page_content_type == "application/pdf"
@params.lang = check_valid_lang(settings[sub_domain].langs, @params.lang)
@session.lang = @params.lang
redirection = load_redirection(db_name, @params)
current_page = load_page_by_slug(db_name, slug, @params.lang)
used_lang = @params.lang
infos = page_info(db_name, @params.slug, @params.lang)
if current_page == nil then
used_lang = stringy.split(settings[sub_domain].langs, ',')[1]
infos = page_info(db_name, @params.slug, used_lang)
current_page = load_page_by_slug(db_name, slug, used_lang)
html = ''
if @params.splat and table.getn(stringy.split(@params.splat, '/')) % 2 == 1
@params.splat = "slug/#{@params.splat}"
if infos == nil
infos = { 'page': {}, 'folder': {} }
else
current_page.item = table_deep_merge(current_page.item, infos.page)
if infos.page.og_aql and infos.page.og_aql[@params.lang] and infos.page.og_aql[@params.lang] != ''
splat = {}
splat = splat_to_table(@params.splat) if @params.splat
bindvars = prepare_bindvars(splat, infos.page.og_aql[@params.lang], @params.lang)
@params.og_data = aql(db_name, infos.page.og_aql[@params.lang], bindvars)[1]
if redirection == nil then
params_lang = @params.lang
@params.lang = used_lang
html = dynamic_page(db_name, current_page, @params, global_data[sub_domain])
@params.lang = params_lang
else
html = redirection
html = dynamic_replace(db_name, html, global_data[sub_domain], {}, @params)
basic_auth(@, settings[sub_domain], infos) -- check if website need a basic auth
if is_auth(@, settings[sub_domain], infos)
if html ~= 'null' and trim(html) != '' then
if page_content_type ~= "application/pdf" then
content_type: page_content_type, html, status: status
else -- convert html data to pdf
filename = "#{uuid!}.html"
write_content "print/#{filename}", html
shell.run "wkhtmltopdf print/#{filename} print/#{filename}.pdf"
pdf = read_file "print/#{filename}.pdf", "rb"
shell.run "rm print/#{filename}"
shell.run "rm print/#{filename}.pdf"
content_type: "application/pdf", pdf, status: status
else
display_error_page(@, 404)
else
status: 401, headers: { 'WWW-Authenticate': 'Basic realm=\"admin\"' }
------------------------------------------------------------------------------
[need_a_db: '/need_a_db']:=> render: true
------------------------------------------------------------------------------
[robots: '/robots.txt']:=>
if no_db[sub_domain] then redirect_to: 'need_a_db'
else
load_settings(@)
@params.lang = @session.lang
@params.all = '-'
@params.slug = 'robots'
display_page(@)
------------------------------------------------------------------------------
[root: '/(:lang)']:=>
if no_db[sub_domain] then redirect_to: 'need_a_db'
else
load_settings(@)
lang = @params.lang or stringy.split(settings[sub_domain].langs, ',')[1]
@session.lang = check_valid_lang(settings[sub_domain].langs, lang)
if @params.lang and @params.lang ~= @session.lang
@params.all = '-'
@params.slug = @params.lang
@params.lang = @session.lang
@session.lang = check_valid_lang(settings[sub_domain].langs, lang)
if @params.slug
display_page(@)
else
home = from_json(settings[sub_domain].home)
@params.lang = @session.lang
@params.all = home['all']
@params.slug = home['slug']
@params.splat = home['splat'] if home['splat']
if type(home['root_redirection']) == 'string'
redirect_to: home['root_redirection']
else
display_page(@)
------------------------------------------------------------------------------
[page_no_lang: '/:all/:slug']:=>
if no_db[sub_domain] then redirect_to: '/need_a_db'
else
load_settings(@)
@params.lang = check_valid_lang(settings[sub_domain].langs, @params.all)
unless @session.lang
@session.lang = stringy.split(settings[sub_domain].langs, ',')[1]
display_page(@)
------------------------------------------------------------------------------
[page: '/:lang/:all/:slug(/*)']:=>
if no_db[sub_domain] then redirect_to: '/need_a_db'
else
load_settings(@)
display_page(@)
-- | 39.986364 | 119 | 0.569285 |
fac350e56fa560a5393bb41f60dbde3222003317 | 876 | Emitter = require 'emitter'
events = require 'wch.events'
sock = require 'wch.sock'
resolve = (path) ->
if path\sub(1, 1) ~= '/'
return os.getenv('PWD')..'/'..path
return path
class WatchStream extends Emitter
new: (dir, query) =>
super!
@dir = resolve dir
@query = query
start: =>
sock\connect!\get!
req = sock\request 'POST', '/watch',
'x-client-id': sock.id
res, err, eno = req\send {dir: @dir, query: @query}
error err if err
assert res.ok
res, err = res\json!
error err if err
@stop = events.on res.id, (file) ->
@emit 'data', file
return self
stop: =>
error 'not started'
----------------------------------
-- EXPORTS
----------------------------------
wch = {}
wch.on = events.on
wch.stream = (dir, query) ->
stream = WatchStream dir, query
return stream\start!
return wch
| 17.52 | 55 | 0.542237 |
8fa637e4d762b6aa1eaa660af56584598cf968a4 | 1,870 | 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 }
unpack = table.unpack or unpack
-- 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.479167 | 71 | 0.572193 |
ec756261a97244ff898b7db0f1e745968b1aaf65 | 12,936 | pi:
are_you_sure: "Are you sure?"
view: "View"
update: "Update"
delete: "Delete"
download: "Download"
warning: "Warning!"
success: "Success!"
since: "Since"
next: "Next"
previous: "Previous"
email:
reset:
subject: "Reset community password"
h1: "Reset your password"
note: "Someone requested a password reset. Simply ignore this email if you didn't request this."
layout:
logout: "Swim th' plank"
homepage:
learn_more: "Be tellin' me more"
browse_resources: "Show me some mor"
main:
first: "Multi Theft Auto be a multiplayer modification fer Rockstar's Grand Theft Auto battle series: a piece 'o software that adapts th' battle in such a way, ye can fight Grand Theft Auto wit' ye buckos online 'n develop ye own gamemodes.",
second: "It was brought into life because 'o th' lackin' multiplayer functionality in th' Grand Theft Auto series 'o games, 'n provides a completely new platform on-top 'o th' original battle, allowin' fer players to fight all sorts 'n types 'o battle-modes anywhere they want, 'n developers to develop usin' our extra powerful scriptin' engine."
resources:
title: "Resources"
latest_resources: "Latest resources"
view_resource: "View resource"
type: "Type"
cast_vote: "Cast vote"
cards:
last_updated: "Last updated"
overview:
most_downloaded: "Most Downloaded"
best_resources: "Best Resources"
recently_uploaded: "Recently Uploaded"
upload:
title: "Upload a new resource"
existing_update_alert: "If you'd like to update an existing resource, visit the manager for the resource."
name_info: "The name of the resource file (admin, editor, freeroam, race, hedit, etc.)"
description_info: "This will be displayed whenever people visit your resource."
publish: "Publish Resource"
table:
name: "Name"
description: "Description"
downloads: "Downloads"
rating: "Rating"
version: "Version"
publish_date: "Publish Date"
changes: "Changes"
title: "Title" -- pretty much just for screenshots
get:
h1: "Downloading %{name} v %{version}"
momentarily: "Your download should start momentarily."
please_click: "Please click"
here: "here"
if_not_start: "if the download did not start."
admin_warning: "Do not give administrator rights to any resource unless you trust it."
dependency_note: "This resource depends on other resources. Please select the resources you would like in your download - you should not need to check resources that you already have. \"%{name}\" will be included in your download."
manage:
title: "Manage"
tab_dashboard: "Dashboard"
tab_details: "Details"
tab_packages: "Packages"
tab_authors: "Authors"
tab_settings: "Settings"
tab_screenshots: "Screenshots"
author:
title:
one: "Author"
many: "Authors"
moderation_invite: "You have an invite to manage this resource!"
accept_invite: "accept"
decline_invite: "decline"
delete_self: "If you delete yourself as an author, you won't be able to use this page anymore. Be careful."
make_invite: "Invite author"
own_permissions: "%{name}'s permissions"
perm_dashboard_note: "All authors can view the resource dashboard"
right: "right"
right_value: "value"
update_perms_button: "Update permissions"
delete_button: "Delete author"
delete_confirm: "Are you sure you want to remove this user as an author?"
invite_button: "Invite..."
authors_list: "List of authors"
authors_list_empty: "This resource has no co-authors."
authors_invited: "Invited authors"
authors_invited_empty: "This resource has no pending invites for authorship."
dashboard:
statistics: "Statistics"
parent_comments: "Parent comments: %{num}"
comment_replies: "Comment replies: %{num}"
not_included_by: "This resource is not included by any other resource."
is_included_by: "This resource is included by: "
screenshot_count: "Screenshots: %{num}"
download_count: "Downloads: %{num}"
details:
title: "Details"
change_description: "Change description"
description: "Description"
description_info: "This will be displayed whenever people visit your resource."
description_button: "Update description"
packages:
update_resource: "Update resource"
description: "Description"
description_info: "What does this update do? What has changed?"
changelog: "Change log"
changelog_info: "What does this update do? What has changed?"
upload: "Upload"
upload_success: "Resource successfully uploaded."
not_including: "This package does not include any other resource."
is_including: "This package includes: "
include_add: "Add include"
include_button: "Add"
include_resource: "resource name"
include_version: "version?"
screenshots:
upload: "Upload screenshot"
title: "Title"
title_info: "Summarise your screenshot"
description: "Description"
optional: "optional"
none_uploaded: "No screenshots are currently uploaded."
settings:
transfer_ownership: "Transfer ownership"
transfer_ownership_info: "You will no longer have access to the management section of this resource. You will have to contact the new owner to be given permissions."
new_owner: "New owner"
rename_resource: "Rename resource"
rename_info_first: "The old resource name becomes available for other people to register. No redirections will be set up."
rename_info_second: "Any existing resources that include your resource will still include your resource for download. These resources will need to be updated to include the new name."
rename_info_third: "Any newly uploaded resources should have the updated name."
rename_name: "Name"
rename_button: "Rename resource..."
delete: "Delete resource"
delete_info: "Deleting your resources removes all comments, screenshots and packages. The resource also becomes available for other people to register."
delete_button: "Delete resource..."
transfer_ownership_confirm: "Are you sure you want to change transfer ownership?"
rename_confirm: "Are you sure you want to rename your resource?"
delete_confirm: "Are you sure you want to delete this resource? This is permanent."
errors:
comment_not_exist: "Comment does not exist"
resource_already_exists: "Resource already exists"
invalid_name: "Invalid resource name"
version_search_fail: "Couldn't find that version with that resource"
package_already_dep: "That package is already a dependency"
no_package: "That's not your package."
not_create_package: "Could not create package"
version_exists: "That version already exists."
no_screenshot: "That screenshot does not exist"
invalid_file_type: "Invalid file type"
not_create_screenshot: "Could not create screenshot"
image_not_served: "An image should have been served. Sorry about that."
not_find_author: "Cannot find author \"%{name}\""
not_existing_author: "\"%{name}\" is not an existing author"
already_author: "\"%{name}\" is already an author"
invite_accept_first: "Please accept your invite first"
invite_already_accepted: "You have already accepted your invite"
errors:
friendly_cast_vote: "We're sorry we couldn't cast that vote for you."
friendly_serve_file: "We're sorry we couldn't serve you that file."
dependencies_unavailable: "One of the resource dependencies you tried to download was unavailable."
comment:
title:
one: "Comment"
many: "Comments"
deleted: "deleted"
reply_message: "Comment reply message"
sr_parent_message: "Comment message:"
message_placeholder: "Place your comment here"
user_replied: "replied"
user_commented: "commented"
user_modified: "modified"
reply: "reply"
errors:
friendly_create: "We're sorry we couldn't make that comment for you."
parent_missing: "Parent comment not found"
cannot_reply_to_reply: "Cannot reply to a comment reply"
login_to: "Log in to leave a comment"
screenshots:
uploaded_since: "uploaded"
users:
action_follow: "Follow"
action_unfollow: "Unfollow"
confirm_follow: "Are you sure you want to follow \"%{name}\"?"
confirm_unfollow: "Are you sure you want to unfollow \"%{name}\"?"
member_for_duration: "Member for %{duration}"
card_follow_time: "Following for %{duration}"
private_profile: "This user's profile is private."
gravatar_alt: "%{name}'s avatar"
tab_resources: "Resources"
tab_followers: "Followers"
tab_following: "Following"
tab_comments: "Comments"
tab_screenshots: "Screenshots"
manage_user: "Manage user"
edit_profile: "Edit profile"
website: "Website"
gang: "Gang"
location: "Location"
cakeday: "Birthday"
profile_buttons: "Profile Buttons"
errors:
not_exist: "User does not exist"
invalid_name: "Invalid username"
account_exists: "Account already exists"
token_not_exist: "Cannot reset password - invalid token"
token_expired: "Password reset token has expired"
friendly_update_profile: "We're sorry we couldn't make those changes."
friendly_delete_account: "We're sorry we couldn't delete your account."
friendly_rename_account: "We're sorry we couldn't rename your account."
friendly_change_password: "We're sorry we couldn't change your password."
old_password_mismatch: "Your old password is incorrect."
password_confirm_mismatch: "Password confirmation incorrect"
cannot_follow_self: "You cannot follow yourself."
already_following: "You are already following this person"
not_currently_following: "You are not following this person"
bad_credentials: "Incorrect username or password."
not_activated: "Your account has not been activated."
banned: "You are banned."
settings:
username: "Username"
profile: "Profile"
account: "Account"
privacy: "Privacy"
public: "Public"
privacy_note: "This only affects your profile page. Everyone will be able to see your comments and see in others' list that they follow you."
following_only: "Following Only"
update_section: "Update Section"
changepass_title: "Change your password"
old_pass: "Old password"
new_pass: "New password"
confirm_new_pass: "Confirm new password"
changepass_button: "Change password"
rename_title: "Change username"
rename_info: "Your old username becomes available for other people to register. No redirections will be set up."
rename_button: "Change username..."
rename_confirm: "Are you sure you want to change your username?"
delete_info: "Deleting your account removes all resources, names from your comments, and screenshots. The username also becomes available for other people to register."
delete_button: "Delete account..."
delete_confirm: "Are you sure you want to delete your account? This is permanent."
auth:
login_title: "Let me in thar"
register_title: "Join th' crew"
reset_title: "Reset your password"
reset_send_email: "Send confirmation email"
reset_email_sent: "An confirmation email has been sent to your address."
username_placeholder: "username"
password_placeholder: "password"
confirm_password_placeholder: "confirm"
email_placeholder: "email address"
register_button: "Join th' crew"
login_button: "Let me in thar"
register_title: "Register an account"
register_success: "Account successfully created. Your account has been automatically activated."
need_logged_in: "You need to be logged in to do that."
search:
title: "Search"
field_placeholder: "short or long name"
sr_field_name: "Name"
in_description: "Search in description"
results_header: "Search Results"
no_results: "No resources match your search query"
errors:
max_filesize: "Max filesize is %{max}. Your file is %{ours} bytes"
bad_request:
title: "Bad Request"
h1: "400: Bad Request"
h3: "This is not the right page you're looking for."
not_authorized:
title: "Not Authorized"
h1: "Sorry, you can't access this page."
not_found:
title: "Page not found"
h1: "404: Sorry, this page isn't available"
h3: "The page doesn't exist, but it might have in the past, and it might in the future!"
method_disallowed:
title: "Error 405"
h1: "405: Sorry, this page isn't available"
h3: "The page doesn't exist, but it might have in the past, and it might in the future!"
server_error:
title: "Oops"
h3: "Something went wrong."
internal_error: "Internal error."
internal_error_output: "Internal error. Give the following information to a codemonkey:"
| 37.172414 | 350 | 0.712894 |
5b5168de4d03ccb682e79236f6be44987e79167c | 251 | path = (...)\gsub(".init$", "") .. '.'
modules = {
'class'
'vectors'
'luax'
'cyclic'
'matrices'
'sets'
'navigation'
}
for m in *modules do require(path .. m)
M = require(path .. 'master')
return {Navigation:M.Navigation}
| 15.6875 | 39 | 0.537849 |
459364bfc9ffcf57ab7fef909a9c5582239aedca | 1,126 | Server = require 'server'
SockJS = require 'sockjs-luvit'
_error = error
error = (...) -> p('BADBADBAD ERROR', ...)
[==[
(req, res, continue) ->
p(req.method)
continue()
]==]
http_stack_layers = () -> {
-- serve chrome page
Server.use('route')({{
'GET /$'
(nxt) =>
p('FOO')
@render 'index.html', @req.context
}})
-- serve static files
Server.use('static')('/public/', 'public/', {
--is_cacheable: (file) -> true
})
-- SockJS servers handlers
SockJS()
}
-- /echo
SockJS('/echo', {
sockjs_url: '/public/sockjs.js'
onconnection: (conn) ->
p('CONNE', conn.sid, conn.id)
conn\on 'message', (m) -> conn\send m
})
-- /close
SockJS('/close', {
sockjs_url: '/public/sockjs.js'
onconnection: (conn) ->
p('CONNC', conn.sid, conn.id)
conn\close 3000, 'Go away!'
})
-- /amplify
SockJS('/amplify', {
sockjs_url: '/public/sockjs.js'
onconnection: (conn) ->
p('CONNA', conn.sid, conn.id)
conn\on 'message', (m) -> conn\send m:rep(2)
})
s1 = Server.run http_stack_layers(), 8080
print 'Server listening at http://localhost:8080/'
require('repl')
| 18.766667 | 50 | 0.581705 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.