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
7aa1c81cfacc2e14437bcf28871795e2518a5d30
425
export modinfo = { type: "function" id: "localScript" func: (Source, Parent) -> return unless CreateLocalScript NewScript = ConfigSystem("Get", "LocalScriptClone")\Clone! NewScript\ClearAllChildren! Souc = CreateInstance"StringValue" Parent: NewScript Name: ConfigSystem "Get", "SourceName" Value: Source NewScript.Disabled = true NewScript.Parent = Parent NewScript.Disabled = false NewScript }
23.611111
60
0.729412
349a1491c3670f605266834ab3f1ad58433122a2
2,731
-- tildeath -- My own dialect of ~ATH -- By daelvn re = require "re" inspect = require "inspect" shorthand = (s) -> s = s\gsub "$(%w+)", [[{:tag: "" -> "%1" :}]] s = s\gsub "&(%w+)", [[{:%1: %1 :}]] s = s\gsub ";(%w+)", [[{:id: %1 :}]] return s grammar = re.compile shorthand [[ -- program program <- chunk -- chunks and blocks block <- ws "{" ws chunk ws "}" chunk <- ws {| $chunk (statement ";" ws)* |} marker <- "->" id -- statements statement <- import / define / bifurcate / execute / die / slabel / loop / directive / run label <- blabel / mlabel / llabel slabel <- llabel / blabel llabel <- {| $label "#" &id {:labeled: loop :} |} blabel <- {| $label "#" &id {:labeled: block :} |} mlabel <- {| $label "#" &id {:labeled: marker :} |} loop <- "~ATH(" ws {| $loop &expr ws ")" ws &block ws &execute |} die <- {| $die &type ":DIE()" |} execute <- "EXECUTE(" ws {| $execute (&type / &statement) |} ws ")" bifurcate <- "bifurcate" rs {| $bifur ;cid ws &list |} import <- "import" rs {| $import {:library:cid:} rs ;cid |} define <- "define" rs {| $define ;cid rs {:value: symbol / string / list :} |} directive <- "==>" ws {| $directive &id (rs &string)? |} run <- "RUN" {| $run &list |} scope <- "->" {| $scope &block |} -- recombine syntax list <- ws "[" ws {| $list tlist |} ws "]" tlist <- (type / string) ("," ws (type / string))* -- types expr <- null / {| $neg "!" type |} / id / list / mlabel type <- null / id / list / mlabel -- primitives string <- {| $string '"' {[^"]*} '"' / "'" {[^']*} "'" |} symbol <- {| $symbol ":" id |} null <- {| $null "NULL" |} cid <- id / mlabel id <- {| $id {%w valid*} |} valid <- [%w'!/@$%^&*<>_~-%.] rs <- (%s / "//" [^%nl]*)+ ws <- (%s / "//" [^%nl]*)* ]] reduce = (t, tint="white") -> switch t.tag when "execute" t = t.type or t.statement when "symbol" t[1] = t[1][1] when "label" tint = string.lower t.id[1] -- tint t.tint = tint -- iterate if "table" == type t for k, v in pairs t continue if k == "tint" if "table" == type v t[k] = reduce v, tint -- return t parse = (s) -> ast = grammar\match s error "Failed to parse: #{s}" unless ast return reduce ast collect = (ast, t={}) -> for i, stat in ipairs ast if stat.tag == "define" -- FIXME make it work for lists (tables) print "Collected -> #{stat.id[1]} = #{stat.value[1]}" t[stat.id[1]] = stat.value[1] t { :NULL :grammar :parse, :reduce :collect }
28.747368
94
0.465763
d396011753d8b3fc811284fe2abc4fd209d4c33c
1,247
export state = require "lib/state" export util = require "lib/util" export shine = require "lib/shine" export bump = require "lib/bump" export world = bump.newWorld! export post_effect = shine.scanlines!\chain (shine.crt!\set "x", 0.05)\set "y", 0.055 with love .graphics.setBackgroundColor 255, 255, 255 .run = -> dt = 0 update_time = 0 target_delta = 1 / 1200 .math.setRandomSeed os.time! if .math .load! if .load .timer.step! if .timer state\set "src/core" state\load! while true update_time += dt if love.event .event.pump! for name, a, b, c, d, e, f in .event.poll! if "quit" == name return a unless .quit or not .event.quit! .handlers[name] a, b, c, d, e, f if .timer .timer.step! dt = .timer.getDelta! if update_time > target_delta state\update dt if .graphics and .graphics.isActive! .graphics.clear .graphics.getBackgroundColor! .graphics.setColor 255, 255, 255 .graphics.origin! post_effect\draw -> state\draw! .graphics.present! .timer.sleep 0.001 if .timer
22.267857
85
0.561347
c74227175fb7fe77eedf225938ec2af3bbe2bc76
630
Dorothy! CharacterSettingView = require "View.Control.Unit.CharacterSetting" ActionChooser = require "Control.AI.ActionChooser" import Struct from require "Lib.Utils" MessageBox = require "Control.Basic.MessageBox" Class CharacterSettingView, __init:=> @actionPanel.itemSource = Struct.Array! @actionPanel\slot "SizeChanged",-> @updateSize! @emit "SizeChanged",@ @actionPanel\slot "AddToList",(items)-> with ActionChooser! \slot "Selected",(file)-> return unless file if items\contains file MessageBox text:"Action Exist!",okOnly:true else items\insert file
27.391304
68
0.701587
2a2070dc682c1e417420cf9ea12afc8bd180d18e
16,977
-- Copyright 2017 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) {:app, :Buffer, :breadcrumbs, :config} = howl {:File} = howl.io {:Window} = howl.ui describe 'breadcrumbs', -> local editor, cursor, old_tolerance buffer = (text) -> with Buffer {} .text = text setup -> app.window = Window! editor = app\new_editor! cursor = editor.cursor app.editor = editor breadcrumbs.init! old_tolerance = config.breadcrumb_tolerance teardown -> config.breadcrumb_tolerance = old_tolerance app.editor = nil app.window\destroy! before_each -> app.editor.buffer = buffer '' config.breadcrumb_tolerance = 0 after_each -> breadcrumbs.clear! describe 'drop(opts)', -> it 'accepts a file and a pos', -> File.with_tmpfile (file) -> breadcrumbs.drop :file, pos: 3 assert.same {:file, pos: 3}, breadcrumbs.previous it 'accepts a file path and a pos', -> File.with_tmpfile (file) -> breadcrumbs.drop :file, pos: 3 assert.same {file: File(file), pos: 3}, breadcrumbs.previous it 'accepts a buffer and a pos', -> File.with_tmpfile (file) -> file.contents = '123456789\nabcdefgh' b = buffer '' b.file = file breadcrumbs.drop buffer: b, pos: 3 assert.equals b.file, breadcrumbs.previous.file assert.equals 3, breadcrumbs.previous.pos assert.not_nil breadcrumbs.previous.buffer_marker context 'when a buffer is present', -> it 'sets a marker in the buffer pointing to the crumb', -> b = buffer '123456789\nabcdefgh' breadcrumbs.drop buffer: b, pos: 3 assert.equals 3, breadcrumbs.previous.pos assert.not_nil breadcrumbs.previous.buffer_marker m = breadcrumbs.previous.buffer_marker marker_buffer = m.buffer markers = marker_buffer.markers\find name: m.name assert.equals 1, #markers assert.equals 3, markers[1].start_offset assert.equals 3, markers[1].end_offset context 'when opts is missing', -> it 'adds a crumb for the current buffer and position', -> File.with_tmpfile (file) -> file.contents = '1234\n6789' editor.buffer.file = file cursor.pos = 7 breadcrumbs.drop! crumb = breadcrumbs.previous assert.equals 7, crumb.pos assert.equals editor.buffer, crumb.buffer_marker.buffer assert.equals file, crumb.file context 'when forward crumbs exists', -> it 'invalidates all such crumbs and buffer markers', -> b = buffer '123456789\nabcdefgh' editor.buffer = b breadcrumbs.drop buffer: b, pos: 3 breadcrumbs.drop buffer: b, pos: 6 breadcrumbs.drop buffer: b, pos: 9 cursor.pos = 10 breadcrumbs.go_back! -- loc 3 assert.equals 4, #breadcrumbs.trail breadcrumbs.go_back! -- loc 2 assert.equals 4, #breadcrumbs.trail assert.is_not_nil breadcrumbs.trail[2] assert.is_not_nil breadcrumbs.trail[3] assert.is_not_nil breadcrumbs.trail[4] assert.equals 2, breadcrumbs.location breadcrumbs.drop buffer: b, pos: 4 assert.equals 4, breadcrumbs.trail[2].pos assert.is_nil breadcrumbs.trail[3] markers = [m.start_offset for m in *b.markers\find({})] table.sort markers assert.same { 3, 4 }, markers context '(tolerance handling)', it 'merges crumbs when their distance is within the tolerance', -> buf = editor.buffer buf.text = string.rep('123456789\n', 10) config.breadcrumb_tolerance = 5 breadcrumbs.drop buffer: buf, pos: 1 breadcrumbs.drop buffer: buf, pos: 6 assert.equals 1, #breadcrumbs.trail assert.equals 6, breadcrumbs.trail[1].pos markers = [m.start_offset for m in *buf.markers\find({})] assert.same { 6 }, markers breadcrumbs.drop buffer: buf, pos: 12 assert.equals 2, #breadcrumbs.trail assert.equals 12, breadcrumbs.trail[2].pos markers = [m.start_offset for m in *buf.markers\find({})] assert.same { 6, 12 }, markers context 'house cleaning according to breadcrumb_limit', -> local old_limit before_each -> old_limit = config.breadcrumb_limit config.breadcrumb_limit = 2 after_each -> config.breadcrumb_limit = old_limit it 'purges old crumbs according to breadcrumb_limit', -> b = buffer '123456789\nabcdefgh' breadcrumbs.drop buffer: b, pos: 1 breadcrumbs.drop buffer: b, pos: 2 breadcrumbs.drop buffer: b, pos: 3 assert.equals 2, #breadcrumbs.trail assert.equals 3, breadcrumbs.location assert.same {2, 3}, [c.pos for c in *breadcrumbs.trail] describe 'crumb cleaning', -> it 'removes duplicate crumbs', -> b = buffer '123456789' breadcrumbs.drop buffer: b, pos: 3 breadcrumbs.drop buffer: b, pos: 3 assert.equals 1, #breadcrumbs.trail markers = b.markers\find {} assert.equals 1, #markers it 'reduces unnecessary loops', -> b = buffer '123456789' breadcrumbs.drop buffer: b, pos: 3 breadcrumbs.drop buffer: b, pos: 6 breadcrumbs.drop buffer: b, pos: 3 breadcrumbs.drop buffer: b, pos: 6 assert.equals 2, #breadcrumbs.trail assert.equals 3, breadcrumbs.location describe 'clear', -> it 'invalidates any existing crumbs (buffer markers and crumbs)', -> b = buffer '123456789\nabcdefgh' breadcrumbs.drop buffer: b, pos: 3 crumb = breadcrumbs.previous breadcrumbs.clear! assert.equals 1, breadcrumbs.location assert.same {}, b.markers\find name: crumb.buffer_marker.name assert.is_nil breadcrumbs.trail[1] describe 'go_back', -> context 'with a buffer and pos available', -> it 'opens the buffer and set the current position', -> b = buffer '123456789\nabcdefgh' breadcrumbs.drop buffer: b, pos: 3 breadcrumbs.go_back! assert.equals 3, cursor.pos assert.equals b, editor.buffer assert.equals 1, breadcrumbs.location it 'uses a buffer marker for positioning to account for updates', -> b = buffer '123456789' breadcrumbs.drop buffer: b, pos: 6 b\insert 'xx', 2 breadcrumbs.go_back! assert.equals 8, cursor.pos context 'with a file and pos available', -> it 'opens the file and sets the current position', -> File.with_tmpfile (file) -> file.contents = '123456789\nabcdefgh' breadcrumbs.drop file: file, pos: 3 breadcrumbs.go_back! assert.equals 3, cursor.pos assert.equals file, editor.buffer.file context 'when the buffer has been collected', -> it 'falls back to the file when available', -> File.with_tmpfile (file) -> file.contents = '1234\n6789' b = buffer '' b.file = file breadcrumbs.drop file: file, buffer: b, pos: 3 b = nil collectgarbage! breadcrumbs.go_back! assert.equals 3, cursor.pos assert.equals file, editor.buffer.file it 'moves to the crumb before if present', -> b1 = buffer 'buffer1' breadcrumbs.drop buffer: b1, pos: 3 b2 = buffer 'buffer2' breadcrumbs.drop buffer: b2, pos: 5 b2 = nil collectgarbage! breadcrumbs.go_back! assert.equals 3, cursor.pos assert.equals b1, editor.buffer assert.equals 1, breadcrumbs.location it 'inserts a crumb if needed before going back', -> b = buffer '123456789' editor.buffer = b cursor.pos = 2 breadcrumbs.drop buffer: b, pos: 3 breadcrumbs.drop buffer: b, pos: 5 cursor.pos = 7 breadcrumbs.go_back! assert.equals 5, cursor.pos -- at pos 5 assert.equals 2, breadcrumbs.location -- at breadcrumbs location 2 assert.equals 3, #breadcrumbs.trail -- with two forward crumbs assert.equals 5, breadcrumbs.trail[2].pos -- the old one assert.equals 7, breadcrumbs.trail[3].pos -- and the newly inserted breadcrumbs.go_back! assert.equals 3, cursor.pos -- at pos 3 assert.equals 1, breadcrumbs.location -- at breadcrumbs location 1 -- we shouldn't have any added crumb added for this case assert.equals 3, #breadcrumbs.trail -- only three forward crumbs assert.same {3, 5, 7}, [c.pos for c in *breadcrumbs.trail] context '(tolerance handling)', -> it 'moves beyond the previous crumb if it is within the distance', -> b = editor.buffer b.text = string.rep('1234567890', 2) config.breadcrumb_tolerance = 2 breadcrumbs.drop buffer: b, pos: 1 breadcrumbs.drop buffer: b, pos: 4 breadcrumbs.drop buffer: b, pos: 7 breadcrumbs.drop buffer: b, pos: 10 cursor.pos = 12 breadcrumbs.go_back! assert.equals 7, cursor.pos breadcrumbs.go_back! assert.equals 4, cursor.pos describe 'go_forward', -> context 'with a buffer and pos available', -> it 'opens the buffer and set the current position', -> b = buffer '123456789\nabcdefgh' breadcrumbs.drop buffer: b, pos: 3 breadcrumbs.drop buffer: b, pos: 7 breadcrumbs.go_back! breadcrumbs.go_back! breadcrumbs.go_forward! assert.equals 7, cursor.pos assert.equals b, editor.buffer it 'uses a buffer marker for positioning to account for updates', -> b = buffer '123456789' breadcrumbs.drop buffer: b, pos: 1 breadcrumbs.drop buffer: b, pos: 6 breadcrumbs.go_back! breadcrumbs.go_back! b\insert 'xx', 2 breadcrumbs.go_forward! assert.equals 8, cursor.pos context 'with a file and pos available', -> it 'opens the file and sets the current position', -> File.with_tmpfile (file) -> file.contents = '123456789\nabcdefgh' breadcrumbs.drop file: file, pos: 3 breadcrumbs.drop file: file, pos: 7 breadcrumbs.go_back! breadcrumbs.go_back! breadcrumbs.go_forward! assert.equals 7, cursor.pos assert.equals file, editor.buffer.file context 'when the buffer has been collected', -> it 'falls back to the file when available', -> File.with_tmpfile (file) -> file.contents = '1234\n6789' b = buffer '' b.file = file breadcrumbs.drop file: file, buffer: b, pos: 3 breadcrumbs.drop file: file, buffer: b, pos: 7 b = nil breadcrumbs.go_back! breadcrumbs.go_back! collectgarbage! breadcrumbs.go_forward! assert.equals 7, cursor.pos assert.equals file, editor.buffer.file it 'moves to the crumb after if present', -> b1 = buffer 'buffer1' breadcrumbs.drop buffer: b1, pos: 3 breadcrumbs.drop buffer: b1, pos: 4 b2 = buffer 'buffer2' breadcrumbs.drop buffer: b2, pos: 5 breadcrumbs.go_back! breadcrumbs.go_back! b1 = nil collectgarbage! breadcrumbs.go_forward! assert.equals 5, cursor.pos assert.equals b2, editor.buffer it 'inserts a crumb if needed before going forward', -> b = buffer '123456789' editor.buffer = b breadcrumbs.drop buffer: b, pos: 3 breadcrumbs.drop buffer: b, pos: 5 breadcrumbs.drop buffer: b, pos: 7 cursor.pos = 7 breadcrumbs.go_back! breadcrumbs.go_back! breadcrumbs.go_back! -- we start out with the three crumbs above, at pos 3 assert.equals 3, cursor.pos assert.equals 3, #breadcrumbs.trail -- with three forward crumbs assert.equals 1, breadcrumbs.location -- at breadcrumbs location 1 -- -- we'll move the cursor some and then go forward cursor.pos = 4 breadcrumbs.go_forward! assert.equals 5, cursor.pos -- at pos 5 -- -- this should have inserted a new crumb at the interim location assert.equals 4, #breadcrumbs.trail -- with two forward crumbs assert.equals 3, breadcrumbs.location -- with location thus = 3 assert.equals 3, breadcrumbs.trail[1].pos -- old back crumb assert.equals 4, breadcrumbs.trail[2].pos -- newly inserted assert.equals 5, breadcrumbs.trail[3].pos -- old forward crumb assert.equals 7, breadcrumbs.trail[4].pos -- old forward crumb -- -- -- forward again, without interim movement breadcrumbs.go_forward! assert.equals 7, cursor.pos -- at pos 5 -- -- -- this should not have introduced any new crumb assert.equals 4, #breadcrumbs.trail assert.equals 4, breadcrumbs.location context '(tolerance handling)', -> it 'moves beyond the next crumb if it is within the distance', -> b = editor.buffer b.text = string.rep('1234567890', 2) config.breadcrumb_tolerance = 2 breadcrumbs.drop buffer: b, pos: 1 breadcrumbs.drop buffer: b, pos: 4 breadcrumbs.drop buffer: b, pos: 7 breadcrumbs.go_back! breadcrumbs.go_back! breadcrumbs.go_back! cursor.pos = 2 breadcrumbs.go_forward! assert.equals 7, cursor.pos describe 'location', -> it 'points to the current crumb position', -> b = editor.buffer b.text = string.rep('1234567890', 2) assert.equals 1, breadcrumbs.location breadcrumbs.drop buffer: b, pos: 1 assert.equals 2, breadcrumbs.location breadcrumbs.drop buffer: b, pos: 4 assert.equals 3, breadcrumbs.location it 'can be assigned to move to a specific location', -> b = editor.buffer b.text = string.rep('1234567890', 2) breadcrumbs.drop buffer: b, pos: 1 breadcrumbs.drop buffer: b, pos: 4 breadcrumbs.drop buffer: b, pos: 8 breadcrumbs.location = 2 assert.equals 2, breadcrumbs.location assert.equals 4, cursor.pos describe '.trail', -> it 'contains a list of breadcrumbs', -> b = buffer '123456789' File.with_tmpfile (file) -> breadcrumbs.drop buffer: b, pos: 3 breadcrumbs.drop :file, pos: 6 crumbs = breadcrumbs.trail assert.equals 3, crumbs[1].pos assert.equals b, crumbs[1].buffer_marker.buffer assert.same {:file, pos: 6}, crumbs[2] it 'is automatically cleaned', -> b1 = buffer '123456789' b2 = buffer '123456789' breadcrumbs.drop buffer: b1, pos: 3 breadcrumbs.drop buffer: b2, pos: 6 b1 = nil collectgarbage! crumbs = breadcrumbs.trail assert.equals 1, #crumbs assert.equals 6, crumbs[1].pos context 'when a buffer is closed', -> it 'removes any crumbs missing a file reference', -> b1 = buffer '123456789' b2 = app\new_buffer! b2.text = '123456789' b2.modified = false breadcrumbs.drop buffer: b1, pos: 3 breadcrumbs.drop buffer: b2, pos: 5 breadcrumbs.drop buffer: b1, pos: 7 assert.equals 3, #breadcrumbs.trail assert.equals 4, breadcrumbs.location app\close_buffer b2 assert.equals 2, #breadcrumbs.trail assert.equals 3, breadcrumbs.location assert.same {3, 7}, [c.pos for c in *breadcrumbs.trail] it 'clears any buffer references for crumbs with a file reference', -> File.with_tmpfile (file) -> file.contents = '123456789' b1 = buffer '123456789' b2 = app\new_buffer! b2.file = file breadcrumbs.drop buffer: b1, pos: 3 breadcrumbs.drop buffer: b2, pos: 5 breadcrumbs.drop buffer: b1, pos: 7 assert.equals 3, #breadcrumbs.trail assert.equals 4, breadcrumbs.location app\close_buffer b2 assert.is_nil breadcrumbs.trail[2].buffer_marker assert.equals 3, #breadcrumbs.trail assert.equals 4, breadcrumbs.location it 'moves the current location down as necessary', -> File.with_tmpfile (file) -> file.contents = '123456789' b1 = buffer '123456789' b2 = app\new_buffer! b2.file = file breadcrumbs.drop buffer: b1, pos: 3 breadcrumbs.drop buffer: b2, pos: 5 breadcrumbs.drop buffer: b2, pos: 7 assert.equals 4, breadcrumbs.location app\close_buffer b2 assert.equals 1, breadcrumbs.location context 'memory management', -> it 'keeps weak references to buffers', -> holder = setmetatable { buffer: buffer '123456789\nabcdefgh' }, __mode: 'v' breadcrumbs.drop buffer: holder.buffer, pos: 3 collectgarbage! assert.is_nil holder.buffer
35.221992
79
0.624315
2fb95e86746aef915077ea3b53a7d969c90731d4
1,837
module "moonscript", package.seeall require "moonscript.compile" require "moonscript.parse" require "moonscript.util" import concat, insert from table import split, dump from util lua = :loadstring export to_lua, moon_chunk, moon_loader, dirsep, line_tables export dofile, loadfile, loadstring dirsep = "/" line_tables = {} -- create moon path package from lua package path create_moonpath = (package_path) -> paths = split package_path, ";" for i, path in ipairs paths p = path\match "^(.-)%.lua$" if p then paths[i] = p..".moon" concat paths, ";" to_lua = (text) -> if "string" != type text t = type text error "expecting string (got ".. t ..")", 2 tree, err = parse.string text if not tree error err, 2 code, ltable, pos = compile.tree tree if not code error compile.format_error(ltable, pos, text), 2 code, ltable moon_loader = (name) -> name_path = name\gsub "%.", dirsep file, file_path = nil, nil for path in *split package.moonpath, ";" file_path = path\gsub "?", name_path file = io.open file_path break if file if file text = file\read "*a" loadstring text, file_path else nil, "Could not find moon file" if not package.moonpath package.moonpath = create_moonpath package.path init_loader = -> insert package.loaders, 2, moon_loader init_loader! if not _G.moon_no_loader loadstring = (str, chunk_name) -> passed, code, ltable = pcall -> to_lua str if not passed error chunk_name .. ": " .. code, 2 line_tables[chunk_name] = ltable if chunk_name lua.loadstring code, chunk_name or "=(moonscript.loadstring)" loadfile = (fname) -> file, err = io.open fname return nil, err if not file text = assert file\read "*a" loadstring text, fname -- throws errros dofile = (fname) -> f = assert loadfile fname f!
21.869048
63
0.677735
3cea9e192b507678cc926f71db3654210386c883
1,282
require "busted" require "tests.mock_love" import List from require "LunoPunk.utils.List" describe "list", -> l = nil before_each -> l = List! l\push i*2 for i=1, 10 it "push/pop/peek/shift/unshift/first/last", -> assert.are.equal 10, l\len! assert.are.equal 20, l\pop! assert.are.equal 18, l\pop! assert.are.equal 8, l\__len! l\push 10 -- last element assert.are.equal 10, l\peek! assert.are.equal 10, l\last! assert.are.equal 2, l\first! assert.are.equal 2, l\shift! assert.are.equal 4, l\first! l\unshift 2 assert.are.equal 2, l\first! it "tostring", -> t = string.format "{ %s }", table.concat {i, i*2 for i=1, 10}, ", " assert.are.equal t, tostring l it "ipairs", -> for i, v in l\ipairs! assert.are.equal i*2, l\index i assert.are.equal 10, l\len! it "ripairs", -> for i, v in l\ripairs! assert.are.equal i*2, l\index i assert.are.equal 10, l\len! it "pairs", -> i = 0 len = l\len! -- original length for v in l\pairs! i += 1 assert.are.equal i*2, l\index i assert.are.equal len, i -- I should be the original length assert.are.equal 10, l\len! it "rpairs", -> i = l\len! for v in l\rpairs! assert.are.equal i*2, l\index i i -= 1 assert.are.equal 0, i assert.are.equal 10, l\len!
21.366667
69
0.627925
5ac2668479d3c6b1740944a699c2d50ed22a4692
601
M = {} TK = require "PackageToolkit" pathsep = (TK.module.import ..., "../_os/_pathsep").pathsep -- chop off the last part of a directory path -- and return a standard version of the directory path -- separated by the OS path separator M.chop = (path) -> if (string.match path, "[/\\%.]") == nil -- if both caller and callee modules live at the root directory return "" else -- example "a.b/c.d" => "a.b/c" result, _ = string.gsub (string.match path, "(.-)[/\\%.]?[^%./\\]+$"), "%.", pathsep() return result return M
35.352941
98
0.549085
d1abfc7b34e1f84ea001a4960e9d6a8ddc3bca70
2,091
import app, signal, config, bindings, command from howl import Editor from howl.ui state = bundle_load 'state' maps = { command: bundle_load 'command_map', state insert: bundle_load 'insert_map', state visual: bundle_load 'visual_map', state } signal_handlers = { 'editor-focused': (args) -> state.change_mode args.editor, state.mode if state.active 'editor-defocused': (args) -> args.editor.indicator.vi.label = '' if state.active 'after-buffer-switch': (args) -> state.change_mode args.editor, 'command' if state.active 'selection-changed': (args) -> if state.active if state.mode == 'visual' state.map.__on_selection_changed args.editor, args.selection elseif not args.selection.empty state.change_mode args.editor, 'visual' 'buffer-saved': (args) -> if state.active and app.editor.buffer == args.buffer state.change_mode app.editor, 'command' } vi_commands = { { name: 'vi-on', description: 'Switches VI mode on' handler: -> state.activate(app.editor) unless state.active } { name: 'vi-off', description: 'Switches VI mode off' handler: -> if state.active state.deactivate! for editor in *howl.app.editors with editor .indicator.vi.label = '' .cursor.style = 'line' .cursor.blink_interval = config.cursor_blink_interval } { name: 'vi-toggle', description: 'Toggles VI mode' handler: -> if state.active then command.vi_off! else command.vi_on! } } unload = -> command.vi_off! for name, handler in pairs signal_handlers signal.disconnect name, handler command.unregister cmd.name for cmd in *vi_commands Editor.unregister_indicator 'vi' -- Hookup Editor.register_indicator 'vi', 'bottom_left' state.init maps, 'command' for name, handler in pairs signal_handlers signal.connect name, handler command.register cmd for cmd in *vi_commands -- state.activate! info = { author: 'The Howl Developers', description: 'VI bundle', license: 'MIT', } return :info, :unload, :maps, :state
24.892857
91
0.677666
731c79206512cf9750bd89e98550d8ddd244e47a
178
Font = require "Lutron/Font/Font" class Sofia24 extends Font new: () => super 'Lutron/Font/Sofia24.png', " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
29.666667
102
0.775281
ae76a66457f32f4515b0ba654d391c2826cd4f75
1,551
import pcall from _G import readFileSync, mkdirSync from require "fs" import decode from "novacbn/properties/exports" import PROJECT_PATH from "novacbn/gmodproj/lib/constants" import enableFileLogging, logError, logFatal from "novacbn/gmodproj/lib/logging" import isDir, isFile from "novacbn/gmodproj/lib/utilities/fs" import ProjectOptions from "novacbn/gmodproj/schemas/ProjectOptions" -- ::configureEnvironment() -> void -- Configures the project's directory environment -- export export configureEnvironment = () -> -- Create the directories needed and enable file logging mkdirSync(PROJECT_PATH.data) unless isDir(PROJECT_PATH.data) mkdirSync(PROJECT_PATH.cache) unless isDir(PROJECT_PATH.cache) mkdirSync(PROJECT_PATH.plugins) unless isDir(PROJECT_PATH.plugins) mkdirSync(PROJECT_PATH.logs) unless isDir(PROJECT_PATH.logs) enableFileLogging() -- ::readManifest() -> table -- Reads the project's manifest file, fatally exits process on errors -- export export readManifest = () -> -- Read the project's manifest file if it exists logFatal(".gmodmanifest is a directory!") if isDir(PROJECT_PATH.manifest) options = {} options = decode(readFileSync(PROJECT_PATH.manifest), {propertiesEncoder: "moonscript"}) if isFile(PROJECT_PATH.manifest) -- Validate the project's manifest, alerting users to any validation errors success, err = pcall(ProjectOptions.new, ProjectOptions, options) unless success logError(err) logFatal("Failed to validate .gmodmanifest!") return err
39.769231
125
0.762089
a810996f4620fb7b99cec5ffac6062ccd48374ac
451
if ngx return { md5: ngx.md5 } local md5 pcall -> digest = require "openssl.digest" hex_char = (c) -> string.format "%02x", string.byte c hex = (str) -> (str\gsub ".", hex_char) md5 = (str) -> hex digest.new("md5")\final str unless md5 pcall -> crypto = require "crypto" md5 = (str) -> crypto.digest "md5", str unless md5 error "Either luaossl (recommended) or LuaCrypto is required to calculate md5" { :md5 }
16.703704
80
0.614191
394c59b1ffe747b6bc7d733567785bd19e32c598
6,127
describe "class", -> it "should make a class with constructor", -> class Thing new: => @color = "blue" instance = Thing! assert.same instance, { color: "blue" } it "should have instance methods", -> class Thing get_color: => @color new: => @color = "blue" instance = Thing! assert.same instance\get_color!, "blue" it "should have base properies from class", -> class Thing color: "blue" get_color: => @color instance = Thing! assert.same instance\get_color!, "blue" assert.same Thing.color, "blue" it "should inherit another class", -> class Base get_property: => @[@property] new: (@property) => class Thing extends Base color: "green" instance = Thing "color" assert.same instance\get_property!, "green" it "should have class properties", -> class Base class Thing extends Base instance = Thing! assert.same Base.__name, "Base" assert.same Thing.__name, "Thing" assert.is_true Thing.__parent == Base assert.is_true instance.__class == Thing it "should have name when assigned", -> Thing = class assert.same Thing.__name, "Thing" it "should not expose class properties on instance", -> class Thing @height: 10 Thing.color = "blue" instance = Thing! assert.same instance.color, nil assert.same instance.height, nil it "should expose new things added to __base", -> class Thing instance = Thing! Thing.__base.color = "green" assert.same instance.color, "green" it "should call with correct receiver", -> local instance class Thing is_class: => assert.is_true @ == Thing is_instance: => assert.is_true @ == instance go: => @@is_class! @is_instance! instance = Thing! instance\go! it "should have class properies take precedence over base properties", -> class Thing @prop: "hello" prop: "world" assert.same "hello", Thing.prop describe "super", -> it "should call super constructor", -> class Base new: (@property) => class Thing extends Base new: (@name) => super "name" instance = Thing "the_thing" assert.same instance.property, "name" assert.same instance.name, "the_thing" it "should call super method", -> class Base _count: 111 counter: => @_count class Thing extends Base counter: => "%08d"\format super! instance = Thing! assert.same instance\counter!, "00000111" it "should call other method from super", -> class Base _count: 111 counter: => @_count class Thing extends Base other_method: => super\counter! instance = Thing! assert.same instance\other_method!, 111 it "should get super class", -> class Base class Thing extends Base get_super: => super instance = Thing! assert.is_true instance\get_super! == Base it "should get a bound method from super", -> class Base count: 1 get_count: => @count class Thing extends Base get_count: => "this is wrong" get_method: => super\get_count instance = Thing! assert.same instance\get_method!!, 1 it "class properties take precedence in super class over base", -> class Thing @prop: "hello" prop: "world" class OtherThing extends Thing assert.same "hello", OtherThing.prop it "gets value from base in super class", -> class Thing prop: "world" class OtherThing extends Thing assert.same "world", OtherThing.prop it "should let parent be replaced on class", -> class A @prop: "yeah" cool: => 1234 plain: => "a" class B @prop: "okay" cool: => 9999 plain: => "b" class Thing extends A cool: => super! + 1 get_super: => super instance = Thing! assert.same "a", instance\plain! assert.same 1235, instance\cool! assert A == instance\get_super!, "expected super to be B" Thing.__parent = B setmetatable Thing.__base, B.__base assert.same "b", instance\plain! assert.same 10000, instance\cool! assert B == instance\get_super!, "expected super to be B" it "should resolve many levels of super", -> class One a: => 1 class Two extends One a: => super! + 2 class Three extends Two a: => super! + 3 i = Three! assert.same 6, i\a! it "should resolve many levels of super with a gap", -> class One a: => 1 class Two extends One class Three extends Two a: => super! + 3 class Four extends Three a: => super! + 4 i = Four! assert.same 8, i\a! it "should call correct class/instance super methods", -> class Base doit: => "instance" @doit: => "class" class One extends Base doit: => super! @doit: => super! assert.same "instance", One!\doit! assert.same "class", One\doit! it "should resolve many levels of super on class methods", -> class One @a: => 1 class Two extends One class Three extends Two @a: => super! + 3 class Four extends Three @a: => super! + 4 assert.same 8, Four\a! it "super should still work when method wrapped", -> add_some = (opts) -> => opts.amount + opts[1] @ class Base value: => 1 class Sub extends Base value: add_some { amount: 12 => super! + 100 } class OtherSub extends Base value: if true => 5 + super! else => 2 + super! assert.same 1 + 100 + 12, Sub!\value! assert.same 6, OtherSub!\value!
20.560403
75
0.558022
b58a3e2f3841f05ebd5d1458ab839cb0fa4cc3a4
693
import Widget from require "lapis.html" filesize = require "filesize" config = require("lapis.config").get! class Edit extends Widget content: => form method: "POST", action: @url_for("edit2", token: @token), -> element "table", -> tr -> td -> input name: "password", type: "password", size: 20 td -> p "Password (required)" tr -> td -> input name: "filename", size: 20, value: @p_filename td -> p "File name (optional)" textarea name: "content", cols: 80, rows: 24, @p_content br! text "Max size: #{filesize(config.max_pasta_size)} bytes" br! br! input type: "submit", value: "Update"
30.130435
69
0.577201
508ecdabb8329e5c4baf97ba52b408f4690292bb
1,366
for impl in *{'pure', 'native'} do mtype = require('mtype.'..impl).type describe "#{impl}:", -> for value in *{ true, false, 42, 'aloha!', {}, -> 'hi!' } do context type(value), -> it 'returns same type as type()', -> assert.same type(value), mtype(value) context 'nil', -> it 'returns "nil"', -> assert.same 'nil', mtype(nil) context 'file', -> it 'returns same type as io.type()', -> value = io.open('/dev/null') assert.same io.type(value), mtype(value) value\close() assert.same io.type(value), mtype(value) context 'table with metatype', -> context 'when __type is string', -> value = setmetatable({}, { __type: 'meta' }) it 'returns __type value', -> assert.same 'meta', mtype(value) context 'when __type is function', -> it 'calls __type and returns return value', -> value = setmetatable({}, { __type: -> 'meta' }) assert.same 'meta', mtype(value) it 'calls __type with the value as 1st argument', -> value = setmetatable({}, { __type: (t) -> t }) assert.equals value, mtype(value) context 'and returns nil', -> it 'returns "table"', -> value = setmetatable({}, { __type: -> nil }) assert.same 'table', mtype(value)
31.045455
64
0.535871
7d2dd5878298e6e645ff4d2e69961f86dbb3489f
1,624
import Flow from require "lapis.flow" describe "lapis.flow", -> local base_object base_object = { msg: "hello" get_msg: => @msg check_base_object: => assert.equal base_object, base_object } it "should create a flow", -> flow = Flow base_object, { cool: 10 proxy_to_message: => @get_msg! raw_message: => @msg get_cool: => @cool check_self: (other) => assert.same other, @ } assert.same "hello", flow\get_msg! assert.same "hello", flow\proxy_to_message! assert.same "hello", flow\raw_message! assert.same "hello", flow.msg assert.same 10, flow\get_cool! assert.same 10, flow.cool flow\check_base_object! flow\check_self flow it "should create a flow with inheritance", -> class MyFlow extends Flow some_val: 999 get_some_val: => @some_val proxy_to_message: => @get_msg! check_self: (other) => assert.same other, @ flow = MyFlow base_object assert.same "hello", flow\get_msg! assert.same "hello", flow\proxy_to_message! assert.same "hello", flow.msg assert.same 999, flow\get_some_val! assert.same 999, flow.some_val flow\check_base_object! flow\check_self flow it "should let flows inherit each other", -> class BaseFlow extends Flow the_data: 100 the_method: => @the_data class ChildFlow extends BaseFlow the_method: => super! + 11 proxy_to_message: => @get_msg! flow = ChildFlow base_object assert.same 111, flow\the_method! assert.same "hello", flow\proxy_to_message!
22.246575
48
0.639163
f2a2cc6a5b44f11b0b8b22eb5e9526073656eea9
1,497
local rshift, lshift, band, ok, _ local string_loader -- lua5.1 has separate 'loadstring' and 'load' -- functions ('load' doesn't accept strings). -- This provides a function that 'load' can use, -- and will work on all versions of lua string_loader = (str) -> sent = false return -> if sent then return nil sent = true return str -- use load to treat as a string to prevent -- parse errors under lua < 5.3 -- luajit uses 32-bit integers for bitwise ops, but lua5.3+ -- uses 32-bit or 64-bit integers, so these wrappers will -- truncate results and/or extend the sign, as appropriate -- to match luajit's behavior. ok, band = pcall(load(string_loader([[ return function(a,b) a = a & b if a > 0x7FFFFFFF then -- extend the sign bit a = ~0xFFFFFFFF | a end return a end ]]))) if ok then _, lshift = pcall(load(string_loader([[ return function(x,y) -- limit to 32-bit shifts y = y % 32 x = x << y if x > 0x7FFFFFFF then -- extend the sign bit x = ~0xFFFFFFFF | x end return x end ]]))) _, rshift = pcall(load(string_loader([[ return function(x,y) y = y % 32 -- truncate to 32-bit before applying shift x = x & 0xFFFFFFFF x = x >> y if x > 0x7FFFFFFF then x = ~0xFFFFFFFF | x end return x end ]]))) else import rshift, lshift, band from require "bit" return { rshift: rshift lshift: lshift band: band }
21.084507
59
0.604542
48217f87fb236d85a926921d89d6bdfab2ab48b1
562
-- Copyright 2013-2015 The Howl Developers -- License: MIT (see LICENSE.md) import formatting from howl completer = bundle_load 'css_completer' class CSSMode new: => @lexer = bundle_load 'css_lexer' @completers = { completer, 'in_buffer' } default_config: word_pattern: r'\\b[-_\\w]+\\b' comment_syntax: { '/*', '*/' } auto_pairs: { '(': ')' '[': ']' '{': '}' '"': '"' "'": "'" } on_completion_accepted: (completion, context) => @completer or= completer! @completer.finish_completion completion, context
20.071429
52
0.601423
a71dd0aad31eaa48f4b3cc79c806efb30164f861
1,797
--- fish lexer for howl from textadept fish.lua as reference. -- See @{README.md} for details on usage. -- @author [Alejandro Baez](https://keybase.io/baez) -- @copyright 2016 -- @license MIT (see LICENSE) -- @module fish howl.util.lpeg_lexer -> c = capture -- shorthand for lexer.word ident = (alpha + '_')^1 * (alpha + digit + '_')^0 -- Whitespace. ws = c 'whitespace', space -- Comments. comment = c 'comment', P'#' * scan_until eol -- Strings. dq_str = span '"', '"', '\\' sq_str = span "'", "'" string = c 'string', any {dq_str, sq_str} -- Numbers number = c 'number', any {float, digit} -- Keywords. keyword = c 'keyword', word { 'alias', 'and', 'begin', 'bg', 'bind', 'block', 'break', 'breakpoint', 'builtin', 'case', 'cd', 'command', 'commandline', 'complete', 'contains', 'continue', 'count', 'dirh', 'dirs', 'echo', 'else', 'emit', 'end', 'eval', 'exec', 'exit', 'fg', 'fish', 'fish_config', 'fish_indent', 'fish_pager', 'fish_prompt', 'fish_right_prompt', 'fish_update_completions', 'fishd', 'for', 'funced', 'funcsave', 'function', 'functions', 'help', 'history', 'if', 'in', 'isatty', 'jobs', 'math', 'mimedb', 'nextd', 'not', 'open', 'or', 'popd', 'prevd', 'psub', 'pushd', 'pwd', 'random', 'read', 'return', 'set', 'set_color', 'source', 'status', 'string', 'switch', 'test', 'trap', 'type', 'ulimit', 'umask', 'vared', 'while' } -- Identifiers. identifier = c 'identifier', ident -- Variables. var = P'$' * ((P'{' * ident * P'}') + ident) variable = c 'variable', var -- Operators. operator = c 'operator', S'=!<>+-/*^&|~.,:;?()[]{}' P { 'all' all: any { keyword, identifier, variable, string, comment, number, operator } }
27.646154
82
0.553144
1ba736b64678e83e12f1ee79d87a6543c3ada43f
40
export ok_require = "ok" return "hello"
13.333333
24
0.725
41d177c6ea0a5bae48026157f3a2b87bcf2b9d8a
8,500
http = require 'lapis.nginx.http' stringy = require 'stringy' sass = require 'sass' import map, table_index from require 'lib.utils' import from_json, to_json, trim from require 'lapis.util' import aql, document_get, foxx_upgrade from require 'lib.arango' -------------------------------------------------------------------------------- write_content = (filename, content)-> file = io.open(filename, 'w+') io.output(file) io.write(content) io.close(file) -------------------------------------------------------------------------------- read_file = (filename)-> file = io.open(filename, 'r') io.input(file) data = io.read('*all') io.close(file) data -------------------------------------------------------------------------------- install_service = (sub_domain, name)-> if name\match('^[%w_%-%d]+$') -- allow only [a-zA-Z0-9_-]+ path = "install_service/#{sub_domain}/#{name}" os.execute("mkdir -p #{path}/APP/routes") os.execute("mkdir #{path}/APP/scripts") os.execute("mkdir #{path}/APP/tests") os.execute("mkdir #{path}/APP/libs") request = 'FOR api IN apis FILTER api.name == @name LET routes = (FOR r IN api_routes FILTER r.api_id == api._key RETURN r) LET scripts = (FOR s IN api_scripts FILTER s.api_id == api._key RETURN s) LET tests = (FOR t IN api_tests FILTER t.api_id == api._key RETURN t) LET libs = (FOR l IN api_libs FILTER l.api_id == api._key RETURN l) RETURN { api, routes, scripts, tests, libs }' api = aql("db_#{sub_domain}", request, { 'name': name })[1] write_content("#{path}/APP/main.js", api.api.code) write_content("#{path}/APP/package.json", api.api.package) write_content("#{path}/APP/manifest.json", api.api.manifest) for k, item in pairs api.routes write_content("#{path}/APP/routes/#{item.name}.js", item.javascript) for k, item in pairs api.tests write_content("#{path}/APP/tests/#{item.name}.js", item.javascript) for k, item in pairs api.libs write_content("#{path}/APP/libs/#{item.name}.js", item.javascript) for k, item in pairs api.scripts write_content("#{path}/APP/scripts/#{item.name}.js", item.javascript) os.execute("cd install_service/#{sub_domain}/#{name}/APP && export PATH='$PATH:/usr/local/bin' && yarn") os.execute("cd install_service/#{sub_domain} && zip -rq #{name}.zip #{name}/") os.execute("rm --recursive install_service/#{sub_domain}/#{name}") foxx_upgrade( "db_#{sub_domain}", name, read_file("install_service/#{sub_domain}/#{name}.zip") ) -------------------------------------------------------------------------------- install_script = (sub_domain, name) -> if name\match('^[%w_%-%d]+$') -- allow only [a-zA-Z0-9_-]+ path = "scripts/#{sub_domain}/#{name}" os.execute("mkdir -p #{path}") request = 'FOR script IN scripts FILTER script.name == @name RETURN script' script = aql("db_#{sub_domain}", request, { 'name': name })[1] write_content("#{path}/package.json", script.package) os.execute("export PATH='$PATH:/usr/local/bin' && cd #{path} && yarn") write_content("#{path}/index.js", script.code) -------------------------------------------------------------------------------- deploy_site = (sub_domain, settings) -> config = require('lapis.config').get! db_config = require('lapis.config').get("db_#{config._name}") path = "dump/#{sub_domain[1]}/" home = from_json(settings.home) deploy_to = stringy.split(settings.deploy_secret, '#') request = 'FOR s IN settings LIMIT 1 RETURN s' sub_domain_settings = aql(deploy_to[1], request)[1] if deploy_to[2] == sub_domain_settings.secret os.execute("mkdir -p #{path}") command = "arangodump --collection layouts --collection partials --collection components --collection spas --collection redirections --collection datatypes --collection aqls --collection helpers --collection apis --collection api_libs --collection api_routes --collection api_scripts --collection api_tests --collection scripts --collection pages --collection folder_path --collection folders --collection scripts --include-system-collections true --server.database db_#{sub_domain} --server.username #{db_config.login} --server.password #{db_config.pass} --server.endpoint #{db_config.endpoint} --output-directory #{path} --overwrite true" command ..= " --collection datasets" if home['deploy_datasets'] command ..= " --collection trads" if home['deploy_trads'] os.execute(command) os.execute("arangorestore --include-system-collections true --server.database #{deploy_to[1]} --server.username #{db_config.login} --server.password #{db_config.pass} --server.endpoint #{db_config.endpoint} --input-directory #{path} --overwrite true") os.execute("rm -Rf #{path}") -- Restart scripts -- scripts = aql(deploy_to[1], 'FOR script IN scripts RETURN script') -- for k, item in pairs scripts -- install_script(deploy_to[1], item.name) -- Restart apis apis = aql(deploy_to[1], 'FOR api IN apis RETURN api') for k, item in pairs apis install_service(deploy_to[1]\gsub('db_', ''), item.name) -------------------------------------------------------------------------------- compile_riotjs = (sub_domain, name, id) -> if name\match('^[%w_%-%d]+$') -- allow only [a-zA-Z0-9_-]+ path = "compile_tag/#{sub_domain}/#{name}" os.execute("mkdir -p #{path}") tag = document_get("db_" .. sub_domain, id) write_content("#{path}/#{name}.riot", tag.html) command = "export PATH=\"$PATH;/usr/local/bin\" && riot --format umd #{path}/#{name}.riot --output #{path}/#{name}.js && terser --compress --mangle -o #{path}/#{name}.js #{path}/#{name}.js" handle = io.popen(command) result = handle\read('*a') handle\close() read_file("#{path}/#{name}.js") -------------------------------------------------------------------------------- compile_tailwindcss = (sub_domain, layout_id, field) -> subdomain = 'db_' .. sub_domain layout = document_get(subdomain, "layouts/" .. layout_id) settings = aql(subdomain, 'FOR s IN settings LIMIT 1 RETURN s')[1] home_settings = from_json(settings.home) langs = stringy.split(settings.langs, ',') path = "compile_tailwind/#{subdomain}/#{layout_id}" os.execute("mkdir -p #{path}") write_content("#{path}/#{layout_id}.css", sass.compile(layout[field], 'compressed')) -- default config file config_file = "module.exports = { mode: 'jit', purge: ['./*.html'], darkMode: false, theme: { extend: {} }, variants: {}, plugins: [] }" -- check if we have defined a config file if home_settings.tailwindcss_config config_file = aql( subdomain, 'FOR page IN partials FILTER page.slug == @slug RETURN page.html', { slug: home_settings.tailwindcss_config } )[1] write_content("#{path}/tailwind.config.js", config_file) if config_file -- Layouts layouts = aql(subdomain, 'FOR doc IN layouts RETURN { html: doc.html }') for k, item in pairs layouts write_content("#{path}/layout_#{k}.html", item.html) -- Pages pages = aql(subdomain, 'FOR doc IN pages RETURN { html: doc.html, raw_html: doc.raw_html }') for k, item in pairs pages for k2, lang in pairs langs lang = stringy.strip(lang) html = "" if type(item['raw_html']) == 'table' and item['raw_html'][lang] html = html .. item['raw_html'][lang] if type(item['html']) == "table" and item['html'][lang] and item['html'][lang].html html = html .. item['html'][lang].html write_content("#{path}/page_#{k}_#{lang}.html", html) -- Components components = aql(subdomain, 'FOR doc IN components RETURN { html: doc.html }') for k, item in pairs components write_content("#{path}/component_#{k}.html", item.html) -- Partials partials = aql(subdomain, 'FOR doc IN partials RETURN { html: doc.html }') for k, item in pairs partials write_content("#{path}/partial_#{k}.html", item.html) command = "cd #{path} && export PATH=\"$PATH;/usr/local/bin\" && NODE_ENV=production tailwindcss build -m -i #{layout_id}.css -o #{layout_id}_compiled.css" handle = io.popen(command) result = handle\read('*a') handle\close() data = read_file("#{path}/#{layout_id}_compiled.css") os.execute("rm -Rf #{path}") data -------------------------------------------------------------------------------- -- expose methods { :install_service, :install_script, :deploy_site, :compile_riotjs, :compile_tailwindcss }
45.945946
644
0.612118
7cb98d0c26a993947e2de174251b5b6e8914a134
672
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) ffi = require 'ffi' require 'ljglibs.cdefs.gdk' core = require 'ljglibs.core' gobject = require 'ljglibs.gobject' ref_ptr = gobject.ref_ptr C = ffi.C core.define 'GdkScreen', { properties: { font_options: 'gpointer' resolution: 'gdouble' -- Added properties number: => C.gdk_screen_get_number @ width: => C.gdk_screen_get_width @ height: => C.gdk_screen_get_height @ width_mm: => C.gdk_screen_get_width_mm @ height_mm: => C.gdk_screen_get_height_mm @ } get_default: -> ref_ptr C.gdk_screen_get_default! }
24
79
0.708333
1d1cbad80e5446a3d23b1c8dfbd3ced5ffb2cbb1
1,466
import java, File from sauce3 Gdx = java.require "com.badlogic.gdx.Gdx" Sauce3VM = java.require "sauce3.Sauce3VM" append = (path, v, t) -> file = new_file path, t file\append v copy = (old, new, old_t, new_t) -> old_f = new_file old, old_t new_f = new_file new, new_t old_f\copy new_f exists = (f, t) -> file = new_file f, t file\exists! dir_create = (f, t) -> file = new_file f, t file\create_dir! dir_list = (f, t) -> file = new_file f, t file\list! get_external_path = -> Gdx.files\getLocalStoragePath! get_working_path = -> file = new_file(".")\file! file\getAbsolutePath! get_last_modified = (f, t) -> file = new_file f, t file\last_modified! get_size = (f, t) -> file = new_file f, t file\size! is_dir = (f, t) -> file = new_file f, t file\is_directory! is_file = (f, t) -> file = new_file f, t file\is_file! load = (f, t) -> file = new_file f, t Sauce3VM.lua\load file\reader!, file move = (old, new, old_t, new_t) -> old_f = new_file old, old_t new_f = new_file new, new_t old_f\move new_f new_file = (f, t) -> File f, t read = (f, t) -> file = new_file f, t file\read! remove = (f, t) -> file = new_file f, t file\remove! write = (f, v, t) -> file = new_file f, t file\write v { :append :copy :exists :dir_create :dir_list :get_external_path :get_working_path :get_last_modified :get_size :load :move :new_file :read :remove :write }
15.763441
45
0.622783
28aeeb623d4220908197bae435bf99efa0d6192d
475
{ lexer: bundle_load 'lexer' comment_syntax: { '/*', '*/' } auto_pairs: '(': ')' '[': ']' '{': '}' '"': '"' "'": "'" indentation: more_after: { r'(if|elif|else|for|while|match|struct|union)\\b', r'pkg\\b.*=$' ':$' r'=\\s*{[^}]*$', } less_for: {r'}|;;$'} code_blocks: multiline: { {r'(if|elif|else|for|while|match|struct|union)\\b', '^%s*;;$', ';;'} {r'=\\s*{[^}]*$', '^%s*}', '}'} } }
16.964286
74
0.374737
0d1addc01b443fc903f93a31b7de5441fb679b94
44
result => random => stop => (stop result)
14.666667
27
0.590909
9541da899cfb21f23a295cbd8527493ce5eeeb02
522
html2unicode = require'html' PRIVMSG: '^%panagram (.+)$': (s, d, arg) => ivar2.util.simplehttp "http://www.wordsmith.org/anagram/anagram.cgi?t=50&anagram=" .. ivar2.util.urlEncode(arg), (s) -> s = s\match "(Displaying%s.-)</?[Pp][ />]" unless s return say "Did not find result" s = s\gsub "[\r\n]", "" s = s\gsub "<script>.*", "" s = s\gsub "<[Bb][Rr][ />]", ", " -- Strip tags s = s\gsub "%b<>", "" say html2unicode(s)\gsub(":%s*,", ":")\gsub(",%s*$", "")
30.705882
123
0.48659
1dc145d0f2579b15786c842e6096e0df103d9936
711
export modinfo = { type: "function" id: "GetOutput" func: (recipient) -> if recipient == LocalPlayer FindOutModel = ConfigSystem("Get", "Camera")\FindFirstChild"Shutsuryoku::PersonScript" if not FindOutModel NewModel = CreateInstance"Model" Parent: ConfigSystem "Get", "Camera" Name: "Shutsuryoku::PersonScript" return NewModel else return FindOutModel FindOutModel = ConfigSystem("Get", "Camera")\FindFirstChild(string.format("Shutsuryoku::%s",recipient.Name)) if not FindOutModel NewModel = CreateInstance"Model" Parent: ConfigSystem("Get", "Camera") Name: string.format("Shutsuryoku::%s", recipient.Name) return NewModel else return FindOutModel }
29.625
110
0.71308
08dbe393199b6a005d63e6a6c74d208d53fb34bf
14,265
socket = require "pgmoon.socket" import insert from table import rshift, lshift, band from require "pgmoon.bit" local pl_file local ssl if ngx pl_file = require "pl.file" ssl = require "ngx.ssl" unpack = table.unpack or unpack VERSION = "2.2.0" _len = (thing, t=type(thing)) -> switch t when "string" #thing when "table" l = 0 for inner in *thing inner_t = type inner if inner_t == "string" l += #inner else l += _len inner, inner_t l else error "don't know how to calculate length of #{t}" _debug_msg = (str) -> require("moon").dump [p for p in str\gmatch "[^%z]+"] flipped = (t) -> keys = [k for k in pairs t] for key in *keys t[t[key]] = key t MSG_TYPE = flipped { status: "S" auth: "R" backend_key: "K" ready_for_query: "Z" query: "Q" notice: "N" notification: "A" password: "p" row_description: "T" data_row: "D" command_complete: "C" error: "E" } ERROR_TYPES = flipped { severity: "S" code: "C" message: "M" position: "P" detail: "D" schema: "s" table: "t" constraint: "n" } PG_TYPES = { [16]: "boolean" [17]: "bytea" [20]: "number" -- int8 [21]: "number" -- int2 [23]: "number" -- int4 [700]: "number" -- float4 [701]: "number" -- float8 [1700]: "number" -- numeric [114]: "json" -- json [3802]: "json" -- jsonb -- arrays [1000]: "array_boolean" -- bool array [1005]: "array_number" -- int2 array [1007]: "array_number" -- int4 array [1016]: "array_number" -- int8 array [1021]: "array_number" -- float4 array [1022]: "array_number" -- float8 array [1231]: "array_number" -- numeric array [1009]: "array_string" -- text array [1015]: "array_string" -- varchar array [1002]: "array_string" -- char array [1014]: "array_string" -- bpchar array [2951]: "array_string" -- uuid array [199]: "array_json" -- json array [3807]: "array_json" -- jsonb array } NULL = "\0" tobool = (str) -> str == "t" class Postgres convert_null: false NULL: {"NULL"} :PG_TYPES user: "postgres" host: "127.0.0.1" port: "5432" ssl: false -- custom types supplementing PG_TYPES type_deserializers: { json: (val, name) => import decode_json from require "pgmoon.json" decode_json val bytea: (val, name) => @decode_bytea val array_boolean: (val, name) => import decode_array from require "pgmoon.arrays" decode_array val, tobool array_number: (val, name) => import decode_array from require "pgmoon.arrays" decode_array val, tonumber array_string: (val, name) => import decode_array from require "pgmoon.arrays" decode_array val array_json: (val, name) => import decode_array from require "pgmoon.arrays" import decode_json from require "pgmoon.json" decode_array val, decode_json hstore: (val, name) => import decode_hstore from require "pgmoon.hstore" decode_hstore val } set_type_oid: (oid, name) => unless rawget(@, "PG_TYPES") @PG_TYPES = {k,v for k,v in pairs @PG_TYPES} @PG_TYPES[assert tonumber oid] = name setup_hstore: => res = unpack @query "SELECT oid FROM pg_type WHERE typname = 'hstore'" assert res, "hstore oid not found" @set_type_oid tonumber(res.oid), "hstore" new: (opts) => @sock, @sock_type = socket.new opts and opts.socket_type if opts @user = opts.user @host = opts.host @database = opts.database @port = opts.port @password = opts.password @ssl = opts.ssl @ssl_verify = opts.ssl_verify @ssl_required = opts.ssl_required @pool_name = opts.pool key = opts.key cert = opts.cert if @sock_type == "nginx" and key and cert key = assert(ssl.parse_pem_priv_key(pl_file.read(key, true))) cert = assert(ssl.parse_pem_cert(pl_file.read(cert, true))) @luasec_opts = { key: key cert: cert cafile: opts.cafile ssl_version: opts.ssl_version or "tlsv1_2" } connect: => opts = if @sock_type == "nginx" { pool: @pool_name or "#{@host}:#{@port}:#{@database}:#{@user}" } ok, err = @sock\connect @host, @port, opts return nil, err unless ok if @sock\getreusedtimes! == 0 if @ssl success, err = @send_ssl_message! return nil, err unless success success, err = @send_startup_message! return nil, err unless success success, err = @auth! return nil, err unless success success, err = @wait_until_ready! return nil, err unless success true settimeout: (...) => @sock\settimeout ... disconnect: => sock = @sock @sock = nil sock\close! keepalive: (...) => sock = @sock @sock = nil sock\setkeepalive ... auth: => t, msg = @receive_message! return nil, msg unless t unless MSG_TYPE.auth == t @disconnect! if MSG_TYPE.error == t return nil, @parse_error msg error "unexpected message during auth: #{t}" auth_type = @decode_int msg, 4 switch auth_type when 0 -- trust true when 3 -- cleartext password @cleartext_auth msg when 5 -- md5 password @md5_auth msg else error "don't know how to auth: #{auth_type}" cleartext_auth: (msg) => assert @password, "missing password, required for connect" @send_message MSG_TYPE.password, { @password NULL } @check_auth! md5_auth: (msg) => import md5 from require "pgmoon.crypto" salt = msg\sub 5, 8 assert @password, "missing password, required for connect" @send_message MSG_TYPE.password, { "md5" md5 md5(@password .. @user) .. salt NULL } @check_auth! check_auth: => t, msg = @receive_message! return nil, msg unless t switch t when MSG_TYPE.error nil, @parse_error msg when MSG_TYPE.auth true else error "unknown response from auth" query: (q) => if q\find NULL return nil, "invalid null byte in query" @post q local row_desc, data_rows, command_complete, err_msg local result, notifications num_queries = 0 while true t, msg = @receive_message! return nil, msg unless t switch t when MSG_TYPE.data_row data_rows or= {} insert data_rows, msg when MSG_TYPE.row_description row_desc = msg when MSG_TYPE.error err_msg = msg when MSG_TYPE.command_complete command_complete = msg next_result = @format_query_result row_desc, data_rows, command_complete num_queries += 1 if num_queries == 1 result = next_result elseif num_queries == 2 result = { result, next_result } else insert result, next_result row_desc, data_rows, command_complete = nil when MSG_TYPE.ready_for_query break when MSG_TYPE.notification notifications = {} unless notifications insert notifications, @parse_notification(msg) -- when MSG_TYPE.notice -- TODO: do something with notices if err_msg return nil, @parse_error(err_msg), result, num_queries, notifications result, num_queries, notifications post: (q) => @send_message MSG_TYPE.query, {q, NULL} wait_for_notification: => while true t, msg = @receive_message! return nil, msg unless t switch t when MSG_TYPE.notification return @parse_notification(msg) format_query_result: (row_desc, data_rows, command_complete) => local command, affected_rows if command_complete command = command_complete\match "^%w+" affected_rows = tonumber command_complete\match "(%d+)%z$" if row_desc return {} unless data_rows fields = @parse_row_desc row_desc num_rows = #data_rows for i=1,num_rows data_rows[i] = @parse_data_row data_rows[i], fields if affected_rows and command != "SELECT" data_rows.affected_rows = affected_rows return data_rows if affected_rows { :affected_rows } else true parse_error: (err_msg) => local severity, message, detail, position error_data = {} offset = 1 while offset <= #err_msg t = err_msg\sub offset, offset str = err_msg\match "[^%z]+", offset + 1 break unless str offset += 2 + #str if field = ERROR_TYPES[t] error_data[field] = str switch t when ERROR_TYPES.severity severity = str when ERROR_TYPES.message message = str when ERROR_TYPES.position position = str when ERROR_TYPES.detail detail = str msg = "#{severity}: #{message}" if position msg = "#{msg} (#{position})" if detail msg = "#{msg}\n#{detail}" msg, error_data parse_row_desc: (row_desc) => num_fields = @decode_int row_desc\sub(1,2) offset = 3 fields = for i=1,num_fields name = row_desc\match "[^%z]+", offset offset += #name + 1 -- 4: object id of table -- 2: attribute number of column (4) -- 4: object id of data type (6) data_type = @decode_int row_desc\sub offset + 6, offset + 6 + 3 data_type = @PG_TYPES[data_type] or "string" -- 2: data type size (10) -- 4: type modifier (12) -- 2: format code (16) -- we only know how to handle text format = @decode_int row_desc\sub offset + 16, offset + 16 + 1 assert 0 == format, "don't know how to handle format" offset += 18 {name, data_type} fields parse_data_row: (data_row, fields) => -- 2: number of values num_fields = @decode_int data_row\sub(1,2) out = {} offset = 3 for i=1,num_fields field = fields[i] continue unless field {field_name, field_type} = field -- 4: length of value len = @decode_int data_row\sub offset, offset + 3 offset += 4 if len < 0 out[field_name] = @NULL if @convert_null continue value = data_row\sub offset, offset + len - 1 offset += len switch field_type when "number" value = tonumber value when "boolean" value = value == "t" when "string" nil else if fn = @type_deserializers[field_type] value = fn @, value, field_type out[field_name] = value out parse_notification: (msg) => pid = @decode_int msg\sub 1, 4 offset = 4 channel, payload = msg\match "^([^%z]+)%z([^%z]*)%z$", offset + 1 unless channel error "parse_notification: failed to parse notification" { operation: "notification" pid: pid channel: channel payload: payload } wait_until_ready: => while true t, msg = @receive_message! return nil, msg unless t if MSG_TYPE.error == t @disconnect! return nil, @parse_error(msg) break if MSG_TYPE.ready_for_query == t true receive_message: => t, err = @sock\receive 1 unless t @disconnect! return nil, "receive_message: failed to get type: #{err}" len, err = @sock\receive 4 unless len @disconnect! return nil, "receive_message: failed to get len: #{err}" len = @decode_int len len -= 4 msg = @sock\receive len t, msg send_startup_message: => assert @user, "missing user for connect" assert @database, "missing database for connect" data = { @encode_int 196608 "user", NULL @user, NULL "database", NULL @database, NULL "application_name", NULL "pgmoon", NULL NULL } @sock\send { @encode_int _len(data) + 4 data } send_ssl_message: => success, err = @sock\send { @encode_int 8, @encode_int 80877103 } return nil, err unless success t, err = @sock\receive 1 return nil, err unless t if t == MSG_TYPE.status if @sock_type == "nginx" @sock\tlshandshake { verify: @ssl_verify, client_cert: @luasec_opts.cert, client_priv_key: @luasec_opts.key, } else @sock\sslhandshake @ssl_verify, @luasec_opts elseif t == MSG_TYPE.error or @ssl_required @disconnect! nil, "the server does not support SSL connections" else true -- no SSL support, but not required by client send_message: (t, data, len) => len = _len data if len == nil len += 4 -- includes the length of the length integer @sock\send { t @encode_int len data } decode_int: (str, bytes=#str) => switch bytes when 4 d, c, b, a = str\byte 1, 4 a + lshift(b, 8) + lshift(c, 16) + lshift(d, 24) when 2 b, a = str\byte 1, 2 a + lshift(b, 8) else error "don't know how to decode #{bytes} byte(s)" -- create big endian binary string of number encode_int: (n, bytes=4) => switch bytes when 4 a = band n, 0xff b = band rshift(n, 8), 0xff c = band rshift(n, 16), 0xff d = band rshift(n, 24), 0xff string.char d, c, b, a else error "don't know how to encode #{bytes} byte(s)" decode_bytea: (str) => if str\sub(1, 2) == '\\x' str\sub(3)\gsub '..', (hex) -> string.char tonumber hex, 16 else str\gsub '\\(%d%d%d)', (oct) -> string.char tonumber oct, 8 encode_bytea: (str) => string.format "E'\\\\x%s'", str\gsub '.', (byte) -> string.format '%02x', string.byte byte escape_identifier: (ident) => '"' .. (tostring(ident)\gsub '"', '""') .. '"' escape_literal: (val) => switch type val when "number" return tostring val when "string" return "'#{(val\gsub "'", "''")}'" when "boolean" return val and "TRUE" or "FALSE" error "don't know how to escape value: #{val}" __tostring: => "<Postgres socket: #{@sock}>" { :Postgres, new: Postgres, :VERSION }
22.824
82
0.585839
df274323722b4bd197841b8a903cb0ca98879887
6,125
describe "class", -> it "should make a class with constructor", -> class Thing new: => @color = "blue" instance = Thing! assert.same instance, { color: "blue" } it "should have instance methods", -> class Thing get_color: => @color new: => @color = "blue" instance = Thing! assert.same instance\get_color!, "blue" it "should have base properies from class", -> class Thing color: "blue" get_color: => @color instance = Thing! assert.same instance\get_color!, "blue" assert.same Thing.color, "blue" it "should inherit another class", -> class Base get_property: => @[@property] new: (@property) => class Thing extends Base color: "green" instance = Thing "color" assert.same instance\get_property!, "green" it "should have class properties", -> class Base class Thing extends Base instance = Thing! assert.same Base.__name, "Base" assert.same Thing.__name, "Thing" assert.is_true Thing.__parent == Base assert.is_true instance.__class == Thing it "should have name when assigned", -> Thing = class assert.same Thing.__name, "Thing" it "should not expose class properties on instance", -> class Thing @height: 10 Thing.color = "blue" instance = Thing! assert.same instance.color, nil assert.same instance.height, nil it "should expose new things added to __base", -> class Thing instance = Thing! Thing.__base.color = "green" assert.same instance.color, "green" it "should call with correct receiver", -> local instance class Thing is_class: => assert.is_true @ == Thing is_instance: => assert.is_true @ == instance go: => @@is_class! @is_instance! instance = Thing! instance\go! it "should have class properies take precedence over base properties", -> class Thing @prop: "hello" prop: "world" assert.same "hello", Thing.prop describe "super", -> it "should call super constructor", -> class Base new: (@property) => class Thing extends Base new: (@name) => super "name" instance = Thing "the_thing" assert.same instance.property, "name" assert.same instance.name, "the_thing" it "should call super method", -> class Base _count: 111 counter: => @_count class Thing extends Base counter: => "%08d"\format super! instance = Thing! assert.same instance\counter!, "00000111" it "should call other method from super", -> class Base _count: 111 counter: => @_count class Thing extends Base other_method: => super\counter! instance = Thing! assert.same instance\other_method!, 111 it "should get super class", -> class Base class Thing extends Base get_super: => super instance = Thing! assert.is_true instance\get_super! == Base it "should get a bound method from super", -> class Base count: 1 get_count: => @count class Thing extends Base get_count: => "this is wrong" get_method: => super\get_count instance = Thing! assert.same instance\get_method!!, 1 it "class properties take precedence in super class over base", -> class Thing @prop: "hello" prop: "world" class OtherThing extends Thing assert.same "hello", OtherThing.prop it "gets value from base in super class", -> class Thing prop: "world" class OtherThing extends Thing assert.same "world", OtherThing.prop it "should let parent be replaced on class", -> class A @prop: "yeah" cool: => 1234 plain: => "a" class B @prop: "okay" cool: => 9999 plain: => "b" class Thing extends A cool: => super! + 1 get_super: => super instance = Thing! assert.same "a", instance\plain! assert.same 1235, instance\cool! assert A == instance\get_super!, "expected super to be B" Thing.__parent = B setmetatable Thing.__base, B.__base assert.same "b", instance\plain! assert.same 10000, instance\cool! assert B == instance\get_super!, "expected super to be B" it "should resolve many levels of super", -> class One a: => 1 class Two extends One a: => super! + 2 class Three extends Two a: => super! + 3 i = Three! assert.same 6, i\a! it "should resolve many levels of super with a gap", -> class One a: => 1 class Two extends One class Three extends Two a: => super! + 3 class Four extends Three a: => super! + 4 i = Four! assert.same 8, i\a! it "should call correct class/instance super methods", -> class Base doit: => "instance" @doit: => "class" class One extends Base doit: => super! @doit: => super! assert.same "instance", One!\doit! assert.same "class", One\doit! it "should resolve many levels of super on class methods", -> class One @a: => 1 class Two extends One class Three extends Two @a: => super! + 3 class Four extends Three @a: => super! + 4 assert.same 8, Four\a! it "super should still work when method wrapped", -> add_some = (opts) -> => opts.amount + opts[1] @ class Base value: => 1 class Sub extends Base value: add_some { amount: 12 => super! + 100 } class OtherSub extends Base value: if true => 5 + super! else => 2 + super! assert.same 1 + 100 + 12, Sub!\value! assert.same 6, OtherSub!\value!
20.692568
75
0.558204
891cfb80059fa219146778f290c7664a566fae37
2,579
-- adapted from: http://thiemonge.org/getting-started-with-uinput ffi = require "ffi" import bor from require "bit" ffi.cdef [[ typedef int ssize_t; static const int O_WRONLY = 1; static const int O_NONBLOCK = 2048; static const int EV_SYN = 0; static const int EV_KEY = 1; static const int KEY_LEFTSHIFT = 42; static const int UI_SET_EVBIT = 1074025828; static const int UI_SET_KEYBIT = 1074025829; static const int UI_SET_RELBIT = 1074025830; static const int UI_DEV_CREATE = 21761; static const int UI_DEV_DESTROY = 21762; static const int BUS_USB = 3; int open(const char *path, int oflag, ...); int ioctl(int fildes, int request, ...); ssize_t write(int fildes, const void *buf, size_t nbyte); unsigned int sleep(unsigned int seconds); typedef unsigned int __u32; typedef signed int __s32; typedef unsigned short __u16; typedef signed short __s16; struct input_id { __u16 bustype; __u16 vendor; __u16 product; __u16 version; }; struct uinput_user_dev { char name[80]; struct input_id id; __u32 ff_effects_max; __s32 absmax[64]; __s32 absmin[64]; __s32 absfuzz[64]; __s32 absflat[64]; }; struct timeval { long tv_sec; long tv_usec; }; struct input_event { struct timeval time; __u16 type; __u16 code; __s32 value; }; ]] import O_WRONLY, O_NONBLOCK EV_KEY, EV_SYN UI_SET_EVBIT, UI_SET_KEYBIT UI_DEV_CREATE, UI_DEV_DESTROY KEY_LEFTSHIFT BUS_USB from ffi.C fd = ffi.C.open "/dev/uinput", bor(O_WRONLY, O_NONBLOCK) print bor(O_WRONLY, O_NONBLOCK) if fd < 0 print "Failed to open uinput file #{fd}" os.exit 1 assert 0 <= ffi.C.ioctl fd, UI_SET_EVBIT, EV_KEY assert 0 <= ffi.C.ioctl fd, UI_SET_EVBIT, EV_SYN assert 0 <= ffi.C.ioctl fd, UI_SET_KEYBIT, KEY_LEFTSHIFT device = ffi.new "struct uinput_user_dev" device.name = "uinput-sample" device.id.bustype = BUS_USB device.id.version = 1 device.id.vendor = 1 device.id.product = 1 assert 0 <= ffi.C.write fd, device, ffi.sizeof(device) assert 0 <= ffi.C.ioctl fd, UI_DEV_CREATE print "Creating..." ffi.C.sleep 10 -- wait for X to find it send_event = (typ, code, value)-> input = ffi.new "struct input_event" input.type = typ if typ input.code = code if code input.value = value if value assert 0 <= ffi.C.write fd, input, ffi.sizeof(input) send_event EV_KEY, KEY_LEFTSHIFT, 1 send_event EV_SYN print "Shift on..." ffi.C.sleep 10 send_event EV_KEY, KEY_LEFTSHIFT, 0 send_event EV_SYN print "Shift off..." ffi.C.sleep 1 ffi.C.ioctl fd, UI_DEV_DESTROY
21.139344
65
0.702986
0df1aa9f0b1b5c4da24b20050422f02b7d228952
78
import ( "../pricing/schema.moon" ) struct Order { candle pricing.Candle }
9.75
25
0.679487
58cee11f86f40c7e863e060072390f01c1afbade
1,139
import floor from math export class Entity new: (x, y, sprite) => @pos = Vector x, y @changeSprite sprite, false @body = world\add @, @pos.x, @pos.y, @dim.x, @dim.y filter: (item, other) -> return "cross" changeSprite: (@sprite, update = true) => @dim = Vector @sprite.width, @sprite.height @offset = @dim / 2 if update world\update @, @pos.x, @pos.y, @dim.x, @dim.y draw: (offset = false) => love.graphics.setColor @sprite.color if debugDrawSprites love.graphics.draw @sprite.img, floor(@pos.x), floor(@pos.y) if debugDrawCollisionBoxes x, y, w, h = world\getRect @ love.graphics.rectangle "line", x, y, w, h update: => setPosition: (@pos) => world\update @, @pos.x, @pos.y move: (velocity) => goal = @pos + velocity actual = Vector! local cols, len actual.x, actual.y, cols, len = world\move @, goal.x, goal.y, @filter @pos = actual if @onCollision then @onCollision cols onCollision: (cols) => for col in *cols other = col.other switch other.__class when Player other\damage!
25.886364
73
0.590869
5862915dbfea492bfd5bf292111aa89171718ea2
1,941
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) _G = _G import table from _G import config, signal from howl append = table.insert config.define name: 'max_log_entries' description: 'Maximum number of log entries to keep in memory' default: 1000 type_of: 'number' signal.register 'log-entry-appended', description: 'Called when a new entry is appended to the log' parameters: essentials: 'The log message essentials' level: 'The log level (one of info, warning, error)' message: 'The log message' signal.register 'log-trimmed', description: 'Called when the log is trimmed to the given size' parameters: size: 'The new number of entries in the log' log = {} setfenv 1, log emitting = false safe_emit = (name, options) -> if emitting -- safe_emit called into signal.emit, which tried to log an error. Back out now -- to avoid a stack overflow. return emitting = true signal.emit name, options emitting = false export entries = {} essentials_of = (s) -> first_line = s\match '[^\n\r]*' essentials = first_line\match '^%[[^]]+%]:%d+: (.+)' unless essentials essentials = first_line\match ':%d+: (.-)[\'"]?$' essentials or first_line dispatch = (level, message) -> essentials = essentials_of message entry = :essentials, :message, :level append entries, entry safe_emit 'log-entry-appended', entry if #entries > config.max_log_entries to_remove = #entries - config.max_log_entries for i=1,to_remove table.remove entries, i safe_emit 'log-trimmed', size: #entries entry export * last_error = nil info = (message) -> dispatch 'info', message warning = (message) -> dispatch 'warning', message warn = warning error = (message) -> last_error = dispatch 'error', message clear = -> entries = {} last_error = nil signal.emit 'log-trimmed', size: 0 return log
24.56962
83
0.691396
b369b7dc3ae9afa7e9d30f721b38ec6441a4f75f
2,514
---------------------------------------------------------------- -- A specialized @{Block} which contains two @{SpaceBlock}s and -- allows children to be added to either. -- -- @classmod DoubleBlock -- @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 DoubleBlock extends Block ---------------------------------------------------------------- -- Constant for adding children to the top @{Block}. -- -- @prop TOP ---------------------------------------------------------------- @TOP: "top" ---------------------------------------------------------------- -- Constant for adding children to the bottom @{Block}. -- -- @prop BOTTOM ---------------------------------------------------------------- @BOTTOM: "bottom" new: => super! @_topBlock = SpaceBlock! @_bottomBlock = SpaceBlock! table.insert @_children, @_topBlock table.insert @_children, @_bottomBlock SetIndent: (indent) => @_indent = indent @_topBlock\SetIndent "#{indent} " @_bottomBlock\SetIndent "#{indent} " ---------------------------------------------------------------- -- Adds a child to either of the two @{Block}s. -- -- @tparam DoubleBlock self -- @tparam string block One of DoubleBlock.TOP or -- DoubleBlock.BOTTOM -- @tparam Block/Line child The child to add. ---------------------------------------------------------------- AddChild: (block, child) => if block == @@TOP @_topBlock\AddChild child elseif block == @@BOTTOM @_bottomBlock\AddChild child ---------------------------------------------------------------- -- @tparam DoubleBlock self -- @treturn string The code that will be added to the buffer -- that will be added in between the content of the two -- @{Block}s. ---------------------------------------------------------------- MiddleRender: => Render: => buffer = "" buffer ..= @\BeforeRender! buffer ..= "\n" buffer ..= @_topBlock\Render! buffer ..= "\n" buffer ..= @\MiddleRender! buffer ..= "\n" buffer ..= @_bottomBlock\Render! buffer ..= "\n" buffer .. @\AfterRender! -- {{ TBSHTEMPLATE:END }} return DoubleBlock
27.626374
69
0.50716
79cf2e171ca8cb73ca76dbd0eb7daf27fee0fbd9
2,066
module_reset = -> keep = {k, true for k in pairs package.loaded} -> count = 0 for mod in *[k for k in pairs package.loaded when not keep[k]] count += 1 package.loaded[mod] = nil true, count class Runner attach_server: (env, overrides) => overrides or= {} overrides.logging = false assert not @current_server, "there's already a server thread" import AttachedServer from require "lapis.cmd.cqueues.attached_server" server = AttachedServer! server\start env, overrides @current_server = server @current_server detach_server: => assert @current_server, "no current server" class Server new: (@server) => stop: => @server\close! start: => logger = require "lapis.logging" port = select 3, @server\localname! logger.start_server port package.loaded["lapis.running_server"] = "cqueues" assert @server\loop! package.loaded["lapis.running_server"] = nil create_server = (app_module) -> config = require("lapis.config").get! http_server = require "http.server" import dispatch from require "lapis.cqueues" load_app = -> app_cls = if type(app_module) == "string" require(app_module) else app_module if app_cls.__base -- is a class app_cls! else app_cls\build_router! app_cls onstream = if config.code_cache == false or config.code_cache == "off" reset = module_reset! (stream) => reset! app = load_app! dispatch app, @, stream else app = load_app! (stream) => dispatch app, @, stream server = http_server.listen { host: "127.0.0.1" port: assert config.port, "missing server port" :onstream onerror: (context, op, err, errno) => msg = op .. " on " .. tostring(context) .. " failed" if err msg = msg .. ": " .. tostring(err) assert io.stderr\write msg, "\n" } Server server start_server = (...) -> server = create_server ... server\start! { type: "cqueues" :create_server :start_server runner: Runner! }
22.215054
74
0.630203
43e7dc9f1631881b13b9321762e4e759c48964f6
8,492
import Widget from require "lapis.html" class Portfolio extends Widget content: => link rel: "stylesheet", href: "/static/css/portfolio/main.css" center -> h1 "Projects I've Worked On" div class: "row", -> div class: "col-xs-12 col-sm-6 col-md-6 col-lg-6", -> div class: "box", -> div class: "box-icon", -> center -> img src: "/static/img/projects/flitter.png", width: 70, height: 70, style: "position: relative; top: 50%; transform: translateY(12%);" div class: "info", -> h4 class: "text-center", "Flitter" p "Flitter is an experimental platform-as-a-service implementation from scratch in Go. It uses mostly handrolled tools and Vulcand for HTTP proxying to applications. It is currently not being maintained but it is able to deploy applications with a Dockerfile via a heroku-style git push." a href: "/projects/flitter", class: "btn", "Learn More" div class: "col-xs-12 col-sm-6 col-md-6 col-lg-6", -> div class: "box", -> div class: "box-icon", -> span class: "fa fa-4x fa-server" div class: "info", -> h4 class: "text-center", "Scalable Deployment" p -> text "This site and a few others I host are deployed inside Docker containers and are updated using " code "git push" text ". The code for this site is available to the public at the link below. This is a simple Lapis application inside nginx and deployed using my docker-lapis image." a href: "http://github.com/Xe/christine.website", class: "btn", "Learn More" div class: "col-xs-12 col-sm-6 col-md-6 col-lg-6", -> div class: "box", -> div class: "box-icon", -> center -> img src: "/static/img/projects/cod.png", width: 70, height: 70, style: "position: relative; top: 50%; transform: translateY(25%);" div class: "info", -> h4 class: "text-center", "Cod" p "Cod is an opinionated set of extended services for IRC networks. It's written from scratch in Python and currently is in active use on a network with over 250 users daily. It works with any Charybdis family IRC daemon but will work best with Elemental-IRCd." a href: "https://github.com/cod-services/cod", class: "btn", "Learn More" div class: "col-xs-12 col-sm-6 col-md-6 col-lg-6", -> div class: "box", -> div class: "box-icon", -> center -> img src: "/static/img/projects/tetra.png", width: 70, height: 70, style: "position: relative; top: 50%; transform: translateY(25%);" div class: "info", -> h4 class: "text-center", "Tetra" p "Tetra is the successor to Cod. It is rewritten from the ground up with the core in Go and all plugins in either Moonscript or Lua. It is in development but master is considered stable. Any active development that could break things is done in feature branches that will PR to master." a href: "/projects/Tetra", class: "btn", "Learn More" div class: "col-xs-12 col-sm-6 col-md-6 col-lg-6", -> div class: "box", -> div class: "box-icon", -> span class: "fa fa-4x fa-code" div class: "info", -> h4 class: "text-center", "Elemental-IRCd" p "Elemental-IRCd is a fork of the (now defunct) ShadowIRCd project. It is also a fork of Atheme's Charybdis irc daemon with more user-friendly features. Most of these things are security patches, network staff usability features, patches that make centralized management simpler and extra status levels in channels; but the resulting core changes mean it needs to be its own project." a href: "https://github.com/elemental-ircd/elemental-ircd", class: "btn", "Learn More" div class: "col-xs-12 col-sm-6 col-md-6 col-lg-6", -> div class: "box", -> div class: "box-icon", -> span class: "fa fa-4x fa-music" div class: "info", -> h4 class: "text-center", "PonyvilleFM" p "PonyvilleFM is an online radio station with both live DJ's and a continuously shuffling set of playlists. My main contribution to them has been helping maintain and deploy their cross-network utility and relay IRC bot as well as help with research and development for future projects still in research and development phases." a href: "http://ponyvillefm.com", class: "btn", "Learn More" div class: "col-xs-12 col-sm-6 col-md-6 col-lg-6", -> div class: "box", -> div class: "box-icon", -> center -> img src: "/static/img/projects/glue.png", width: 70, height: 70, style: "position: relative; top: 50%; transform: translateY(18%);" div class: "info", -> h4 class: "text-center", "Glue" p "Glue is a small shim I needed to make in order to test some aspects of Tetra outside of the main environment. Its name comes from the fact that it needed to glue things together as well as the fact that it combines Go and Lua together." a href: "https://github.com/Xe/glue", class: "btn", "Learn More" div class: "col-xs-12 col-sm-6 col-md-6 col-lg-6", -> div class: "box", -> div class: "box-icon", -> center -> img src: "https://camo.githubusercontent.com/0842ae6eb213b4d95efc9f2137085bbbd8e52258/68747470733a2f2f692e696d6775722e636f6d2f4379337a4f6f772e706e67", width: 70, height: 70, style: "position: relative; top: 50%; transform: translateY(18%);" div class: "info", -> h4 class: "text-center", "Shuo" p -> text "Originally a fork of " a href: "https://github.com/erming/shout", "Shout" text ", Shuo is a stable and proven web interface to IRC. It has a server written in Node.JS and uses socket.io to communicate with the HTML5 client. It is pending a large scale rewrite with a backend in Haskell or Go." a href: "https://github.com/ponychat/shuo", class: "btn", "Learn More" div class: "col-xs-12 col-sm-6 col-md-6 col-lg-6", -> div class: "box", -> div class: "box-icon", -> center -> img src: "/static/img/projects/ponyapi.png", width: 70, height: 70, style: "position: relative; top: 50%; transform: translateY(18%);" div class: "info", -> h4 class: "text-center", "PonyAPI" p "A simple JSON api for information on episodes of My Little Pony: Friendship is Magic. It uses data scraped by hand over 4 years and presents as JSON via a server written in Nim. It also follows best practices for not breaking existing code when adding improvements." a href: "https://github.com/Xe/PonyAPI", class: "btn", "Learn More" h3 -> text "Web Portfolio" div class: "row", -> div class: "col-md-6", -> a href: "https://yolo-swag.com", -> img src: "http://api.webthumbnail.org/?width=420&height=330&screen=1280&url=https://yolo-swag.com" div class: "col-md-6", -> a href: "http://xeserv.us", -> img src: "http://api.webthumbnail.org/?width=420&height=330&screen=1280&url=http://xeserv.us" div class: "col-md-6", -> a href: "http://diddy-kong.racing", -> img src: "http://api.webthumbnail.org/?width=420&height=330&screen=1280&url=http://diddy-kong.racing" div class: "col-md-6", -> a href: "https://ponychat.net", -> img src: "http://api.webthumbnail.org/?width=420&height=330&screen=1280&url=https://ponychat.net" div class: "col-md-6", -> a href: "https://clop.science", -> img src: "http://api.webthumbnail.org/?width=420&height=330&screen=1280&url=https://clop.science" div class: "col-md-6", -> a href: "http://cinemaquestria.com", -> img src: "http://api.webthumbnail.org/?width=420&height=330&screen=1280&url=http://cinemaquestria.com" div class: "col-md-6", -> a href: "https://bnc.ponychat.net", -> img src: "http://api.webthumbnail.org/?width=420&height=330&screen=1280&url=https://bnc.ponychat.net" div class: "col-md-6", -> a href: "https://bnc-signup.ponychat.net", -> img src: "http://api.webthumbnail.org/?width=420&height=330&screen=1280&url=https://bnc-signup.ponychat.net"
60.22695
397
0.616934
aa28801a35c392ddff73cee55fb03122dfc16e37
390
import readproc from require 'mon.util' () -> output = {} v4, v6 = 0, 0 for address in string.gmatch (readproc 'hostname -I'), '%S+' if string.match address, '%.' output["ipv4:addr#{v4}"] = value: address name: "Network - IPv4 - Address #{v4}" v4 += 1 else output["ipv6:addr#{v6}"] = value: address name: "Network - IPv6 - Address #{v6}" v6 += 1 output
21.666667
61
0.579487
854f6297c69108e205410573997dfcf97372cf0a
3,119
#!/this/is/ignored a = 1 + 2* 3 / 6 a, bunch, go, here = another, world func arg1, arg2, another, arg3 here, we = () ->, yeah the, different = () -> approach; yeah dad() dad(lord) hello(one,two)() (5 + 5)(world) fun(a)(b) fun(a) b fun(a) b, bad hello hello world what are you doing here what(the)[3243] world, yeck heck hairy[hands][are](gross) okay okay[world] (get[something] + 5)[years] i,x = 200, 300 yeah = (1 + 5) * 3 yeah = ((1+5)*3)/2 yeah = ((1+5)*3)/2 + i % 100 whoa = (1+2) * (3+4) * (4+5) -> if something return 1,2,4 print "hello" -> if hello "heloo", "world" else no, way -> 1,2,34 return 5 + () -> 4 + 2 return 5 + (() -> 4) + 2 print 5 + () -> 34 good nads something 'else', "ya" something'else' something"else" something[[hey]] * 2 something[======[hey]======] * 2 something'else', 2 something"else", 2 something[[else]], 2 something 'else', 2 something "else", 2 something [[else]], 2 here(we)"go"[12123] -- this runs something = test: 12323 what: -> print "hello world" print something.test frick = hello: "world" argon = num: 100 world: (self) -> print self.num return { something: -> print "hi from something" } somethin: (self, str) -> print "string is", str return world: (a,b) -> print "sum", a + b something.what() argon\world().something() argon\somethin"200".world(1,2) x = -434 x = -hello world one two hi = -"herfef" x = -[x for x in x] print "hello" if cool print "hello" unless cool print "hello" unless 1212 and 3434 -- hello print "hello" for i=1,10 print "nutjob" if hello then 343 print "what" if cool else whack arg = {...} x = (...) -> dump {...} x = not true y = not(5+5) y = #"hello" x = #{#{},#{1},#{1,2}} hello, world something\hello(what) a,b something\hello what something.hello\world a,b something.hello\world(1,2,3) a,b x = 1232 x += 10 + 3 j -= "hello" y *= 2 y /= 100 m %= 2 hello ..= "world" @@something += 10 @something += 10 a["hello"] += 10 a["hello#{tostring ff}"] += 10 a[four].x += 10 x = 0 (if ntype(v) == "fndef" then x += 1) for v in *values hello = something: world if: "hello" else: 3434 function: "okay" good: 230203 div class: "cool" 5 + what wack what whack + 5 5 - what wack what whack - 5 x = hello - world - something ((something = with what \cool 100) -> print something)! if something 03589 -- okay what about this else 3434 if something yeah elseif "ymmm" print "cool" else okay -- test names containing keywords x = notsomething y = ifsomething z = x and b z = x andb -- undelimited tables while 10 > something something: "world" print "yeah" x = okay: sure yeah okay: man sure: sir hello "no comma" yeah: dada another: world hello "comma", something: hello_world frick: you -- creates two tables another hello, one, two, three, four, yeah: man okay: yeah -- a += 3 - 5 a *= 3 + 5 a *= 3 a >>= 3 a <<= 3 a /= func "cool" --- x.then = "hello" x.while.true = "hello" -- x or= "hello" x and= "hello" -- z = a-b z = a -b z = a - b z = a- b -- cooool
11.424908
53
0.587047
34c15e8734fd0e9586968ed9a454a48b004d80f7
30
require "lapis.features.etlua"
30
30
0.833333
df480ff81b6edb2d9cf7cf87678e5e8858aa215f
2,461
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) {:config} = howl config.define name: 'hidden_file_extensions' description: 'File extensions that determine which files should be hidden in file selection lists' scope: 'global' type_of: 'string_list' default: {'a', 'bc', 'git', 'hg', 'o', 'pyc', 'so', 'svn', 'cvs'} config.define { name: 'complete' description: 'Controls the operation of auto-completion' default: 'auto' options: { { 'manual', 'Only complete when explicitly asked' } { 'auto', 'Complete whenever it is deemed appropriate' } { 'always', 'Alway start completion automatically' } } } config.define name: 'auto_format' description: 'Whether to automatically format code when possible' default: true type_of: 'boolean' config.define name: 'preview_files' description: 'Whether to automatically preview the selected file or buffer' default: true type_of: 'boolean' scope: 'global' config.define { name: 'inspectors_on_idle' description: 'List of on-idle inspectors to run for a buffer' type_of: 'string_list' default: {} } config.define { name: 'inspectors_on_save' description: 'List of on-save inspectors to run for a buffer' type_of: 'string_list' default: {} } config.define { name: 'auto_inspect' description: 'When to automatically inspect code for abberrations' default: 'on' options: { { 'off', 'Run all inspectors only when explicitly asked to' } { 'on', 'Run on-idle inspectors on idle and on-save inspectors on save' } { 'save_only', 'Run all inspectors, but only on save' } } } config.define { name: 'display_inspections_delay' description: 'The delay before inspections are displayed at the current pos (ms, minimum 500ms)' type_of: 'number' default: 500 scope: 'global' validate: (v) -> return false unless type(v) == 'number' v >= 500 } config.define { name: 'activities_popup_delay' description: 'The delay before a popup is displayed for a running activity (ms)' type_of: 'number' default: 700 scope: 'global' } config.define { name: 'popup_menu_accept_key' description: 'What key should be used for accepting the current option of a popup menu?' default: 'enter' scope: 'global' options: { { 'enter', 'Pressing <ENTER> accepts the current option' } { 'tab', 'Pressing <TAB> accepts the current option' } } }
26.75
100
0.696059
31f5c469fe303e3a568603e62940581a0d3ac6f6
1,084
import sin, floor from math help = {} help.text = "Help" help.height = 16 help.y = help.height move = -> flux.to(help, 0.48, {y: help.height + 16 })\ease("cubicin")\oncomplete(-> flux.to(help, 0.48, {y: help.height})\ease("cubicout")\oncomplete(move) ) move! textCentered = (s, font, y) -> x = gameWidth / 2 - font\getWidth(s) / 2 love.graphics.setFont font love.graphics.print(s, x, y) text = (s, font, y) -> love.graphics.setFont font love.graphics.print(s, 0, y) help.update = (dt) => flux.update dt help.draw = () => -- draw the level push\start! textCentered @text, fontFantasy, floor(@y) text "WASD - MOVEMENT\n\nARROW KEYS - ATTACK\n\n YOUR GOAL IS TO FIND THE SECRETS\n OF THE UNKNOWN DEPTHS. THE\n DEEPER YOU GO THE MORE YOU WILL\n DISCOVER. WATCH OUT FOR THE\n DEADLY CREATURES OF THE DEPTHS,\n THEY WILL TRY TO STOP YOU.", fontRetro, 96 push\finish! help.keypressed = (key) => if key == "return" or key == "escape" or key == "h" manager\pop! if key == "f" push\switchFullscreen(windowedWidth, windowedHeight) return help
23.565217
75
0.658672
601ed87e76f0b53d4d1fad9919f61f452ad9424c
360
{:capture} = require "command" -> acpi = capture("acpi -b")\split('\n') batt = ([line for line in *acpi when line\match '^Battery'])[1] return unless batt status = batt\match ':%s(%a+),' status = status\lower! percent = tonumber batt\match(',%s(%d+)%%') time_remaining = batt\match ',%s(%d+:%d+):%d+%s%a+' {:status, :percent, :time_remaining}
30
65
0.602778
fed2d1e125921457ef997679788bbe4c67144e07
201
export ^ class State update: (dt) => draw: => mousereleased: (x, y, button) => mousepressed: (x, y, button) => keypressed: (k) => keyreleased: (k) => wheelmoved: (x, y) =>
18.272727
36
0.517413
57ed5583b0d18847cd970f7136a46868dffa0c5d
140
return { RouteNotFoundError: require "tbsp.errors.route_not_found" StaticFileNotFoundError: require "tbsp.errors.static_file_not_found" }
28
69
0.835714
d07bedb6d561292619dcbf389d48867a16716e7a
646
class Utils contains: (input, el) -> return false if not input return false if not el for _, value in pairs(input) return true if value == el return false concat: (a, b) -> return a if not b return b if not a result = {unpack(a)} table.move(b, 1, #b, #result + 1, result) return result explode: (div, str) -> return false if div == '' pos,arr = 0, {} for st, sp in () -> string.find(str,div,pos,true) table.insert(arr, string.sub(str, pos, st - 1)) pos = sp + 1 return arr return Utils
21.533333
59
0.503096
430d44643dda9bf2c5a65cfcbe8f45fc674b044c
738
export redis = require 'redis' export config = require 'config' export library = require 'library' export inspect = require 'inspect' export socket = require 'socket' export plugins = {} -- load plugins for i, plugin in ipairs config.plugins name, param = nil, nil if type(plugin) == 'string' name = plugin else name, param = plugin[1], plugin[2] require_string = "return require('" .. name .. "')" library.log("Loading plugin: " .. name) plugins[i] = { name: name, param: param, plugin: loadstring(require_string) } -- seed math.random math.randomseed(socket.gettime! * 1000) library.log('Redis host: ' .. config.redis_host .. ':' .. config.redis_port) return nil
24.6
76
0.638211
e5a3eceea46aa1e672faff6373847f6d61289e95
10,972
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) Gtk = require 'ljglibs.gtk' require 'howl.ui.icons.font_awesome' import bindings, dispatch from howl import PropertyObject from howl.util.moon import NotificationWidget, BufferPopup, TextWidget, IndicatorBar, ContentBox, HelpContext, style from howl.ui append = table.insert style.define_default 'prompt', 'keyword' class CommandLine extends PropertyObject new: (@window) => super! @def = {} @bin = Gtk.Box Gtk.ORIENTATION_HORIZONTAL @box = nil @command_widget = nil @header = nil @indic_title = nil @indic_info = nil @is_open = false @is_hidden = false @_help_context = nil @_title = nil @_prompt = '' @_widgets = {} -- maps string name to widget object to_gobject: => @bin _initialize_box: => @box = Gtk.Box Gtk.ORIENTATION_VERTICAL @command_widget = TextWidget line_wrap: 'char' on_keypress: (event) -> result = true if not @handle_keypress(event) result = false @post_keypress! return result on_changed: -> @handle_text_change! on_focus_lost: -> -- don't let focus leave command line, even if user clicks the editor, we'll grab focus back while open if @is_open and not @is_hidden and howl.activities.nr_visible == 0 @command_widget\focus! @command_widget.visible_rows = 1 @box\pack_end @command_widget\to_gobject!, false, 0, 0 @notification = NotificationWidget! @box\pack_end @notification\to_gobject!, false, 0, 0 @header = IndicatorBar 'header' @indic_title = @header\add 'left', 'title' @indic_info = @header\add 'right', 'info' @box.margin_left = 2 @box.margin_top = 2 c_box = ContentBox 'command_line', @box, { header: @header\to_gobject! } @bin\add c_box\to_gobject! _destroy_box: => @box\destroy! @box = nil @property title: get: => @_title set: (text) => @_title = text if text == nil or text.is_empty @header\to_gobject!\hide! else @header\to_gobject!\show! @indic_title.label = tostring text @property prompt: get: => @_prompt or '' set: (prompt='') => @command_widget\delete 1, @_prompt_end @command_widget\insert prompt, 1, 'prompt' @_prompt = prompt @_cursor_to_end! @property _prompt_end: get: => if @_prompt then @_prompt.ulen else 0 @property text: get: => @command_widget.text\usub 1 + @_prompt_end set: (text) => @clear! @write text clear: => @command_widget\delete 1 + @_prompt_end, @command_widget.text.ulen @\_cursor_to_end! write: (text) => @command_widget\append text @\_cursor_to_end! @\handle_text_change! _cursor_to_end: => @command_widget.cursor\eof! post_keypress: => @_enforce_left_pos! _enforce_left_pos: => -- don't allow cursor to go left into prompt left_pos = @_prompt_end + 1 if @command_widget.cursor.pos < left_pos @command_widget.cursor.pos = left_pos handle_text_change: => @command_widget\adjust_height! -- expand or contract on wrapping return unless @def.on_text_changed -- avoid deep recursive calls to short circuit cyclic bugs in the code @_update_recursive_count or= 0 @_update_recursive_count += 1 if @_update_recursive_count > 1000 error 'command line hit on_text_changed recursion limit' ok, err = pcall -> @def\on_text_changed @text @_update_recursive_count -= 1 error err unless ok handle_keypress: (event) => -- keymaps checked in order: -- @preemptive_keymap - command line keystrokes that cannot be remapped -- @opts.cancel_for_keymap - if dispatch is successful, this command_line is cancelled -- @def.keymap - keymap provided by definition table passed into run() -- @default_keymap - standard keys such ask arrows and backspace return true if bindings.dispatch event, 'command_line', { @preemptive_keymap }, self @window.status\clear! @close_help! if @opts.cancel_for_keymap and bindings.can_dispatch event, 'command_line', { @opts.cancel_for_keymap } text = @text @finish! bindings.dispatch event, 'command_line', { @opts.cancel_for_keymap }, :text return true if @def and @def.keymap return true if bindings.dispatch event, 'command_line', { @def.keymap }, @def return true if bindings.dispatch event, 'command_line', { @default_keymap }, self return false preemptive_keymap: ctrl_shift_backspace: => @finish! if @parking escape: => if @help_popup @close_help! return true return false default_keymap: f1: => @show_help! binding_for: ["cursor-home"]: => @command_widget.cursor.pos = @_prompt_end ["cursor-line-end"]: => @_cursor_to_end! ["cursor-left"]: => @command_widget.cursor\left! ["cursor-right"]: => @command_widget.cursor\right! ["editor-delete-back"]: => if @command_widget.cursor.pos <= @_prompt_end + 1 -- backspace attempted into prompt if @def.handle_back @def\handle_back! return true else return true range_start = @command_widget.selection\range! return if range_start and range_start < @_prompt_end @command_widget\delete_back! ["editor-paste"]: => import clipboard from howl if clipboard.current @write clipboard.current.text add_widget: (name, widget, pos='bottom') => error('No widget provided', 2) if not widget @remove_widget name local pack if pos == 'bottom' pack = @box\pack_end elseif pos == 'top' pack = @box\pack_start else error "Invalid pos #{pos}" pack widget\to_gobject!, false, 0, 0 @_widgets[name] = widget widget\show! remove_widget: (name) => widget = @_widgets[name] return unless widget widget\to_gobject!\destroy! @_widgets[name] = nil get_widget: (name) => @_widgets[name] clear_widgets: => names = [name for name, _ in pairs @_widgets] for name in *names @remove_widget name load_help: => -- merge help provided by @def and @opts @_help_context = HelpContext! if @opts.help @_help_context\merge @opts.help def_help = @def.get_help and @def\get_help! if def_help @_help_context\merge def_help -- when help is available, show help info/keyboard icons in header info_icon = howl.ui.icon.get('font-awesome-info') keyboard_icon = howl.ui.icon.get('font-awesome-keyboard-o') text = '' if #@_help_context.sections > 0 text = info_icon.text if #@_help_context.keys > 0 text ..= " #{keyboard_icon.text}" unless text.is_empty text ..= ': f1' @indic_info.label = text show_help: => help_buffer = @_help_context\get_buffer! return unless help_buffer and not help_buffer.text.is_blank -- display help buffer in a centered popup popup = BufferPopup help_buffer @close_help! popup\show howl.app.window\to_gobject!, x:1, y:1 popup\center! @help_popup = popup close_help: => if @help_popup @help_popup\destroy! @help_popup = nil open: => return if @is_open @bin\show_all! @notification\hide! @title = @title @is_open = true @is_hidden = false @command_widget\focus! hide: => @bin\hide! @is_hidden = true unhide: => @bin\show! @is_hidden = false @command_widget\focus! close: => return if not @box if @def.on_close @def\on_close! @reset! if @is_open @bin\hide! @_destroy_box! @is_open = false reset: => @def = {} @parking = nil @title = '' @prompt = '' @text = '' run: (def, opts={}) => error 'def not provided' unless def error 'def.init not provided' unless def.init @_initialize_box! unless @box @def = def @opts = moon.copy opts @load_help! @parking = dispatch.park 'command_line' status, err = pcall -> def\init self, max_height: @window.allocated_height * 0.5, max_width: @window.allocated_width - 20 unless status log.error 'def.init returned error: ', :err @open! -- calls @def.on_text_changed dispatch.launch -> @text = opts.text or '' result = dispatch.wait @parking @close! return result finish: (result) => error 'no handler to finish' unless @parking dispatch.resume @parking, result class CommandPanel extends PropertyObject new: (@window) => super! @command_lines = {} @bin = Gtk.Box Gtk.ORIENTATION_VERTICAL to_gobject: => @bin @property is_active: get: => #@command_lines > 0 @property active_command_line: get: => @command_lines[#@command_lines] _push: (command_line) => @bin\pack_end command_line\to_gobject!, false, 0, 0 append @command_lines, command_line _remove: (command_line) => before_count = #@command_lines @command_lines = [cl for cl in *@command_lines when cl != command_line] after_count = #@command_lines if after_count < before_count @bin\remove command_line\to_gobject! return command_line run: (def, opts={}) => current_command_line = @command_lines[#@command_lines] -- currently active command line unless current_command_line -- first command line, save focus of current editor @last_focused = @window.focus if not @last_focused @window\remember_focus! if current_command_line -- hide currently active command line -- this should also hide all related widgets because they're in the same bin -- *important*: this should always happen before we run the new command -- line otherwise both command_lines will fight for the focus (see -- on_focus_lost) current_command_line\hide! else @window.status\hide! @bin\show! -- create the new command line and run it command_line = CommandLine @window @_push command_line result = table.pack command_line\run def, opts @_remove command_line -- after the run, revert to previous state if current_command_line -- re display the previous command line current_command_line\unhide! else -- no more command lines, close up the entire panel @bin\hide! @last_focused\grab_focus! if @last_focused @last_focused = nil @window.status\show! return table.unpack result notify: (message, level) => return unless @is_active with @active_command_line.notification \notify level, message \show! cancel: => command_lines = [command_line for _, command_line in ipairs @command_lines] dispatch.launch -> for idx = #command_lines, 1, -1 command_lines[idx]\finish! return CommandPanel
27.361596
125
0.65175
02f45cdc843184b844a71f413944fcbf218ed716
1,443
Timer = require 'vendor.hump.timer' deep = require 'vendor.deep' V = require 'vector' import copy from require 'moon' Node = require 'node' class Block extends Node @BASE_SIZE: 38 @SPACING_FACTOR: 0.07 @DEFAULT_SPACING: @BASE_SIZE * @SPACING_FACTOR @RADIUS_DIVISOR: 5 @STATES: { SELECT: factor: 0.62, padding: 0.00 GRABBED: factor: 1.00, padding: 0.10 PLACED: factor: 1.00, padding: 0.00 } new: (game, parent, pos, color, state) => super game, parent, pos @state = copy state or @@STATES.PLACED size = @@BASE_SIZE * @state.factor @size = w: size, h: size @color = color or 'def' -- string corresponding to theme color name @onTop = false -- set by Polies getSpacing: => @size.w * @@SPACING_FACTOR setState: (state) => @game.timer\tween(.2, @state, state, 'out-back') update: => size = @@BASE_SIZE * @state.factor @size = w: size, h: size draw: => padding = @state.padding * @size.w size = @size.w - padding radius = size / @@RADIUS_DIVISOR deep.queue @onTop and 2 or 1, -> love.graphics.setColor @game.theme[@color] love.graphics.rectangle('fill', @pos.x + padding, @pos.y + padding, size, size, radius) return Block
28.294118
76
0.540541
5b9bd9a83185cd2fc5f0d8a2ad7bd4d8e86e1a3c
3,848
{graphics: g} = love class TileGenerator extends Box w: 16 h: 16 x: 0 y: 0 new: (@seed) => @render! draw: => @outline! g.draw @canvas, @x, @y if @canvas render: => unless @canvas @canvas = g.newCanvas @w, @h @canvas\setFilter "nearest", "nearest" g.setCanvas @canvas @render_tile! g.setCanvas! render_tile: => update: (dt) => true class GrassGenerator extends TileGenerator render_tile: => @rng = love.math.newRandomGenerator @seed + 777 @rng\random! for i=1,3 Box.draw @, C.grass for color in *{C.grass_dark, C.grass_light} for i=1,20 x = @rng\random 0, 15 y = @rng\random 0, 15 w = @rng\random 1, 2 h = @rng\random 2, 4 Box(x,y,w,h)\draw color class DirtGenerator extends TileGenerator colors: => C.dirt, C.dirt_dark render_tile: => @rng = love.math.newRandomGenerator @seed @rng\random! for i=1,3 light, dark = @colors! Box.draw @, light COLOR\push dark g.setPointSize 1 for i=1,3 x = @rng\random 0, 15 y = @rng\random 0, 15 g.point x,y g.setPointSize 2 for i=1,3 x = @rng\random 0, 15 y = @rng\random 0, 15 g.point x,y g.setPointSize 3 for i=1,3 x = @rng\random 0, 15 y = @rng\random 0, 15 g.point x,y COLOR\pop! class WetDirtGenerator extends DirtGenerator colors: => C.dirt_dark, C.dirt_darker class TilledDirtGenerator extends TileGenerator colors: => C.dirt, C.dirt_dark render_tile: => @rng = love.math.newRandomGenerator @seed + 327 light, dark = @colors! Box.draw @, light @rng\random! for i=1,3 g.push! g.translate @w/2, @h/2 g.rotate @rng\random! g.translate -@w/2, -@h/2 oy = @rng\random 1,4 for y=0,2 Box(0,oy + y * 4,16,2)\draw dark g.pop! class WetTilledDirtGenerator extends TilledDirtGenerator colors: => C.dirt_dark, C.dirt_darker class WoodGenerator extends TileGenerator render_tile: => @rng = love.math.newRandomGenerator @seed @rng\random! for i=1,3 Box.draw @, C.wood for color in *{C.wood_dark, C.wood_light} for i=1,3 y = @rng\random 0, 15 Box(0,y,16,2)\draw color class FloorGenerator extends TileGenerator render_tile: => @rng = love.math.newRandomGenerator @seed @rng\random! for i=1,3 Box.draw @, C.floor g.setPointSize 2 COLOR\push C.floor_light ox = @rng\random 1,4 oy = @rng\random 1,4 dt = @rng\random 3,5 g.push! g.translate ox, oy g.translate @w/2, @h/2 g.rotate @rng\random! g.translate -@w/2, -@h/2 for y=0,4 for x=0,4 g.point x*dt, y*dt g.pop! COLOR\pop! class TopGenerator extends TileGenerator render_tile: => @rng = love.math.newRandomGenerator @seed + 263 Box.draw @, C.top COLOR\push C.top_light g.rectangle "line", 0,0, @w, @h COLOR\pop! class TileSheet w: 7 new: => {:w, :h} = TileGenerator rows = { [GrassGenerator i for i=2,1+@w] [DirtGenerator i for i=2,1+@w] [WoodGenerator i for i=2,1+@w] [FloorGenerator i for i=2,1+@w] [TopGenerator i for i=2,1+@w] [WetDirtGenerator i for i=2,1+@w] [TilledDirtGenerator i for i=2,1+@w] [WetTilledDirtGenerator i for i=2,1+@w] } @h = #rows @canvas = g.newCanvas w * @w, h * @h @canvas\setFilter "nearest", "nearest" g.setCanvas @canvas for y, row in ipairs rows for x, gen in ipairs row g.draw gen.canvas, (x - 1) * w, (y - 1) * h g.setCanvas! row_tid: (row) => row * @w spriter: => Spriter Image\from_tex(@canvas), TileGenerator.w, TileGenerator.h { :TileGenerator, :GrassGenerator, :DirtGenerator, :WoodGenerator, :TileSheet }
19.049505
56
0.588098
b0fa1babca636c5814bfc339bf15973569681ba0
3,304
lfs = require "lfs" import with_dev from require "spec.helpers" pattern = ... unpack = table.unpack or unpack options = { in_dir: "spec/inputs", out_dir: "spec/outputs", input_pattern: "(.*)%.moon$", output_ext: ".lua" show_timings: os.getenv "TIME" diff: { tool: "git diff --no-index --color" --color-words" filter: (str) -> -- strip the first four lines table.concat [l for l in *([line for line in str\gmatch("[^\n]+")])[5,]], "\n" } } timings = {} gettime = nil pcall -> require "socket" gettime = socket.gettime gettime or= os.clock benchmark = (fn) -> if gettime start = gettime! res = {fn!} gettime! - start, unpack res else nil, fn! read_all = (fname) -> if f = io.open(fname, "r") with f\read "*a" f\close! diff_file = (a_fname, b_fname) -> out = io.popen(options.diff.tool .. " ".. a_fname .. " " .. b_fname, "r")\read "*a" if options.diff.filter out = options.diff.filter out out diff_str = (expected, got) -> a_tmp = os.tmpname! .. ".expected" b_tmp = os.tmpname! .. ".got" with io.open(a_tmp, "w") \write expected \close! with io.open(b_tmp, "w") \write got \close! with diff_file a_tmp, b_tmp os.remove a_tmp os.remove b_tmp string_assert = (expected, got) -> if expected != got diff = diff_str expected, got error "string equality assert failed" if os.getenv "HIDE_DIFF" error "string equality assert failed:\n" .. diff input_fname = (base) -> options.in_dir .. "/" .. base .. ".moon" output_fname = (base) -> options.out_dir .. "/" .. base .. options.output_ext inputs = for file in lfs.dir options.in_dir with match = file\match options.input_pattern continue unless match table.sort inputs describe "input tests", -> local parse, compile with_dev -> parse = require "moonscript.parse" compile = require "moonscript.compile" for name in *inputs input = input_fname name it input .. " #input", -> file_str = read_all input_fname name parse_time, tree, err = benchmark -> parse.string file_str error err if err compile_time, code, err, pos = benchmark -> compile.tree tree error compile.format_error err, pos, file_str unless code table.insert timings, {name, parse_time, compile_time} if os.getenv "BUILD" with io.open output_fname(name), "w" \write code \close! else expected_str = read_all output_fname name error "Test not built: " .. input_fname(name) unless expected_str string_assert expected_str, code nil if options.show_timings teardown -> format_time = (sec) -> ("%.3fms")\format(sec*1000) col_width = math.max unpack [#t[1] for t in *timings] print "\nTimings:" total_parse, total_compile = 0, 0 for tuple in *timings name, parse_time, compile_time = unpack tuple name = name .. (" ")\rep col_width - #name total_parse += parse_time total_compile += compile_time print " * " .. name, "p: " .. format_time(parse_time), "c: " .. format_time(compile_time) print "\nTotal:" print " parse:", format_time total_parse print " compile:", format_time total_compile
23.6
85
0.616828
5ba1d2bfe606e7f993c15379ba81ed4a0cc957bd
131
package.path = "../?.lua;" .. package.path export test = (klass) -> v! for k, v in pairs(klass.__base) when string.find(k, "test$")
65.5
88
0.633588
1add34eae61dbab5ed92c5d6335da4525239825a
1,234
html_builer = { "text" "raw" "widget" "element" "html_5" "capture" 'area' "applet" 'base' 'br' 'col' 'embed' 'frame' 'hr' 'img' 'input' 'link' 'meta' 'param' 'a' 'abbr' 'acronym' 'address' 'article' 'aside' 'audio' 'b' 'bdo' 'big' 'blockquote' 'body' 'button' 'canvas' 'caption' 'center' 'cite' 'code' 'colgroup' 'command' 'datalist' 'dd' 'del' 'details' 'dfn' 'dialog' 'div' 'dl' 'dt' 'em' 'fieldset' 'figure' 'footer' 'form' 'frameset' 'h1' 'h2' 'h3' 'h4' 'h5' 'h6' 'head' 'header' 'hgroup' 'html' 'i' 'iframe' 'ins' 'keygen' 'kbd' 'label' 'legend' 'li' 'map' 'mark' 'meter' 'nav' 'noframes' 'noscript' 'object' 'ol' 'optgroup' 'option' 'p' 'pre' 'progress' 'q' 'ruby' 'rt' 'rp' 's' 'samp' 'script' 'section' 'select' 'small' 'source' 'span' 'strike' 'strong' 'style' 'sub' 'sup' 'table' 'tbody' 'td' 'textarea' 'tfoot' 'th' 'thead' 'time' 'title' 'tr' 'tt' 'u' 'ul' 'var' 'video' } { whitelist_globals: { ["."]: {"ngx"} ["lapis/console/views"]: html_builer } }
8.226667
40
0.465964
5dc2d8ea30415deabf8920d87729ccc809d63810
1,066
import readproc from require 'mon.util' -> data = readproc 'free -hw' result = {} add = (name, tab) -> for k, v in pairs tab result["#{name}:#{k}"] = value: tonumber string.match v, '[0-9.]+' unit: string.gsub (string.match v, '[a-zA-Z]+'), 'i', '' min: 0 total, used, free, shared, buffers, cache, available = string.match data, 'Mem:%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)' add 'ram', :total, :used, :free, :shared, :buffers, :cache, :available total, used, free = string.match data, 'Swap:%s+(%S+)%s+(%S+)%s+(%S+)' add 'swap', :total, :used, :free result['ram:total'].name = "RAM - Total" result['ram:free'].name = "RAM - Free" result['ram:available'].name = "RAM - Available" result['ram:used'].name = "RAM - Used (user)" result['ram:buffers'].name = "RAM - Used (buffers)" result['ram:cache'].name = "RAM - Used (cache)" result['ram:shared'].name = "RAM - Used (shared)" result['swap:total'].name = "Swap - Total" result['swap:free'].name = "Swap - Free" result['swap:used'].name = "Swap - Used" result
33.3125
137
0.585366
99d157472d836a9e8aea7b77627dc122e794e7a2
325
hi = "hello" hello = "what the heckyes" print hi umm = 'umm' here, another = "yeah", 'world' aye = "YU'M" you '"hmmm" I said' print aye, you another = [[ hello world ]] hi_there = [[ hi there ]] well = [==[ "helo" ]==] hola = [===[ eat noots]===] mm = [[well trhere]] x = "\\" x = "a\\b" x = "\\\n" x = "\""
9.558824
31
0.489231
b84388ac1f5deab8fa98f0af31c34e7ce2a8629f
725
class PathItem extends Item getIntersections: (path) => -- First check the bounds of the two paths. If they don't intersect, -- we don't need to iterate through their curves. return [] if !@getBounds()\touches(path\getBounds()) locations = [] curves1 = @getCurves() curves2 = path\getCurves() length2 = curves2.length values2 = [] i = 0 while i < length2 values2[i] = curves2[i]\getValues() i++ i = 0 l = curves1.length while i < l curve1 = curves1[i] values1 = curve1\getValues() j = 0 while j < length2 Curve\getIntersections values1, values2[j], curve1, curves2[j], locations j++ i++ locations
24.166667
81
0.587586
fd4e8ceaf89524b9ecf39e65e3fc0e282a4ce5d3
39
export PILE_OF_CODE_BASE = (...) .. '.'
39
39
0.589744
f4e0169c5762f89c19aa7e662ae0d989c33f9a2a
1,006
describe "helpers.apply_template", -> apply_template = require("shipwright.transform.helpers").apply_template it "accepts strings and numbers", -> x = { str: "my_string" int: 10, float: 99.99, bool: false, missing: nil -- wont convert } template = "$missing, $str, $int, $float, $bool" value = apply_template(template, x) assert.matches("$missing, my_string, 10, 99.99, false", value) it "calls tostring internally", -> x = {a: 1} setmetatable(x, { __tostring: (v) -> "to_string" }) template = "$rep" value = apply_template(template, { rep: x }) assert.matches("to_string", value) it "warns on tables with no tostring", -> x = {a: 1} template = "$rep" assert.has_error(-> apply_template(template, { rep: x })) it "warns on raw functions", -> x = -> template = "$rep" assert.has_error(-> value = apply_template(template, { rep: x }))
22.863636
73
0.565606
6eefbfc3a713e3290bf24bd4b9a61227d02f9612
6,502
-- -- 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. DLib.RegisterAddonName('PPM/2') mat_dxlevel = GetConVar('mat_dxlevel') timer.Create 'PPM2.Unsupported', 600, 4, -> if mat_dxlevel\GetInt() >= 90 timer.Remove 'PPM2.Unsupported' return Derma_Message('gui.ppm2.dxlevel.not_supported', 'gui.ppm2.dxlevel.toolow') timer.Create 'PPM2.ModelChecks', 1, 0, -> for _, task in ipairs PPM2.NetworkedPonyData.RenderTasks ent = task.ent if IsValid(ent) ent.__cachedIsPony = ent\IsPony() for _, ply in ipairs player.GetAll() if not ply\IsDormant() ply.__cachedIsPony = ply\IsPony() ponydata = ply\GetPonyData() if ply.__cachedIsPony if (not ponydata or ponydata\GetHideWeapons()) and not hook.Run('SuppressPonyWeaponsHide', ply) and not ply.RenderOverride for _, wep in ipairs ply\GetWeapons() if wep if not hook.Run('ShouldDrawPonyWeapon', ply, wep) and (not wep.ShouldPonyDraw or not wep\ShouldPonyDraw(ply)) wep\SetNoDraw(true) wep.__ppm2_weapon_hit = true elseif wep.__ppm2_weapon_hit wep\SetNoDraw(false) ply.__ppm2_weapon_hit = false else for _, wep in ipairs ply\GetWeapons() if wep and wep.__ppm2_weapon_hit wep\SetNoDraw(false) ply.__ppm2_weapon_hit = false PlayerRespawn = -> ent = net.ReadEntity() return if not IsValid(ent) return if not ent\GetPonyData() ent\GetPonyData()\PlayerRespawn() PlayerDeath = -> ent = net.ReadEntity() return if not IsValid(ent) return if not ent\GetPonyData() ent\GetPonyData()\PlayerDeath() lastDataSend = 0 lastDataReceived = 0 net.Receive 'PPM2.PlayerRespawn', PlayerRespawn net.Receive 'PPM2.PlayerDeath', PlayerDeath concommand.Add 'ppm2_require', -> net.Start('PPM2.Require') net.SendToServer() PPM2.Message 'Requesting pony data...' concommand.Add 'ppm2_reload', -> return if lastDataSend > RealTimeL() lastDataSend = RealTimeL() + 10 instance = PPM2.GetMainData() newData = instance\CreateNetworkObject() newData\Create() instance\SetNetworkData(newData) PPM2.Message 'Sending pony data to server...' if not IsValid(LocalPlayer()) times = 0 hook.Add 'Think', 'PPM2.RequireData', -> ply = LocalPlayer() return if not IsValid(ply) times += 1 if ply\GetVelocity()\Length() > 5 return if times < 200 hook.Remove 'Think', 'PPM2.RequireData' hook.Add 'KeyPress', 'PPM2.RequireData', -> hook.Remove 'KeyPress', 'PPM2.RequireData' RunConsoleCommand('ppm2_reload') timer.Simple 3, -> RunConsoleCommand('ppm2_require') else timer.Simple 0, -> RunConsoleCommand('ppm2_reload') timer.Simple 3, -> RunConsoleCommand('ppm2_require') PPM_HINT_COLOR_FIRST = Color(255, 255, 255) PPM_HINT_COLOR_SECOND = Color(0, 0, 0) net.receive 'PPM2.EditorCamPos', -> ply = net.ReadPlayer() return if not ply\IsValid() pVector, pAngle = net.ReadVector(), net.ReadAngle() if not IsValid(ply.__ppm2_cam) ply.__ppm2_cam = ClientsideModel('models/tools/camera/camera.mdl', RENDERGROUP_BOTH) ply.__ppm2_cam\SetModelScale(0.4) ply.__ppm2_cam.RenderOverride = => return if not ply.__ppm2_campos_lerp render.DrawLine(ply.__ppm2_campos_lerp, ply\EyePos(), color_white, true) @DrawModel() hook.Add 'Think', ply.__ppm2_cam, => return @Remove() if not IsValid(ply) or not ply\GetNWBool('PPM2.InEditor') findPos, findAng = LocalToWorld(pVector, pAngle, ply\GetPos(), ply\EyeAngles()) ply.__ppm2_campos_lerp = Lerp(RealFrameTime() * 22, ply.__ppm2_campos_lerp or findPos, findPos) @SetPos(ply.__ppm2_campos_lerp) @SetAngles(findAng) hook.Add 'HUDPaint', 'PPM2.EditorStatus', -> lply = LocalPlayer() lpos = lply\EyePos() editortext = DLib.i18n.localize('tip.ppm2.in_editor') for ply in *player.GetAll() if ply ~= lply and ply\GetNWBool('PPM2.InEditor') pos = ply\EyePos() dist = pos\Distance(lpos) if dist < 250 pos.z += 10 alpha = (1 - dist\progression(0, 250))\max(0.1) * 255 {:x, :y} = pos\ToScreen() draw.DrawText(editortext, 'HudHintTextLarge', x, y, Color(0, 0, 0, alpha), TEXT_ALIGN_CENTER) draw.DrawText(editortext, 'HudHintTextLarge', x + 1, y + 1, Color(255, 255, 255, alpha), TEXT_ALIGN_CENTER) if ply.__ppm2_campos pos = Vector(ply.__ppm2_campos) dist = pos\Distance(lpos) if dist < 250 pos.z += 9 alpha = (1 - dist\progression(0, 250))\max(0.1) * 255 {:x, :y} = pos\ToScreen() text = DLib.i18n.localize('tip.ppm2.camera', ply\Nick()) draw.DrawText(text, 'HudHintTextLarge', x, y, Color(0, 0, 0, alpha), TEXT_ALIGN_CENTER) draw.DrawText(text, 'HudHintTextLarge', x + 1, y + 1, Color(255, 255, 255, alpha), TEXT_ALIGN_CENTER) concommand.Add 'ppm2_cleanup', -> for _, ent in ipairs ents.GetAll() if ent.isPonyPropModel and not IsValid(ent.manePlayer) ent\Remove() PPM2.Message('All unused models were removed') timer.Create 'PPM2.ModelCleanup', 60, 0, -> for _, ent in ipairs ents.GetAll() if ent.isPonyPropModel and not IsValid(ent.manePlayer) ent\Remove() cvars.AddChangeCallback('mat_picmip', (-> timer.Simple 0, (-> RunConsoleCommand('ppm2_require') RunConsoleCommand('ppm2_reload') ) ), 'ppm2') cvars.AddChangeCallback('ppm2_cl_hires_generic', (-> timer.Simple 0, (-> RunConsoleCommand('ppm2_require') RunConsoleCommand('ppm2_reload') ) ), 'ppm2') cvars.AddChangeCallback('ppm2_cl_hires_body', (-> timer.Simple 0, (-> RunConsoleCommand('ppm2_require') RunConsoleCommand('ppm2_reload') ) ), 'ppm2') return
33.005076
126
0.716549
aae9d54eac3b187908ccb2345274703159284730
839
-- hmac auth util = require "mooncrafts.util" crypto = require "mooncrafts.crypto" import string_slit from util import base64_encode, base64_decode from crypto import unpack from table local * sign = (key, data, algo=crypto.sha256) -> base64_encode(crypto.hmac(key, data, algo).digest()) verify = (key, data, algo=crypto.sha256) -> data == sign(key, data, algo) sign_custom = (key, data="", ttl=600, ts=os.time(), algo=crypto.sha256) -> "#{ts}:#{ttl}:#{data}:" .. sign("#{ts}:#{ttl}:#{data}") -- reverse the logic above to hmac verify verify_custom = (key, payload, algo=crypto.sha256) -> ts, ttl, data = unpack string_split(payload, ":") -- validate expiration return { valid: false, timeout: true } if (ts < (os.time() - tonumber(str[2]))) -- validate { valid: (sign(key, data, ttl, ts) == payload) } { :sign, :verify }
32.269231
130
0.665077
77795418844f2467ef3624f6705d80fee89e9e92
1,106
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) ffi = require 'ffi' jit = require 'jit' require 'ljglibs.cdefs.gtk' core = require 'ljglibs.core' gobject = require 'ljglibs.gobject' require 'ljglibs.gtk.misc' ffi_string = ffi.string gc_ptr = gobject.gc_ptr C = ffi.C jit.off true, true core.define 'GtkLabel < GtkMisc', { properties: { angle: 'gdouble' cursor_position: 'gint' ellipsize: 'PangoEllipsizeMode' justify: 'GtkJustification' label: 'gchar*' lines: 'gint' max_width_chars: 'gint' mnemonic_keyval: 'guint' mnemonic_widget: 'GtkWidget*' pattern: 'gchar*' selectable: 'gboolean' selection_bound: 'gint' single_line_mode: 'gboolean' track_visited_links: 'gboolean' use_markup: 'gboolean' use_underline: 'gboolean' width_chars: 'gint' wrap: 'gboolean' text: get: => ffi_string C.gtk_label_get_text @ set: (text) => C.gtk_label_set_text @, text } new: (str) -> gc_ptr C.gtk_label_new str }, (spec, ...) -> spec.new ...
23.041667
79
0.669982
c61b052b8accb2d2b94067b335b2e0ebb11edd3f
698
export isnumber = (o using nil) -> type(o) == "number" export isstring = (o using nil) -> type(o) == "string" export istable = (o using nil) -> type(o) == "table" table.GetKeys = (items using nil) -> [key for key, value in pairs items] export Msg = io.write export PrintTable = (t, indent=0, done={} using nil) -> keys = table.GetKeys t table.sort(keys, (a, b) -> if isnumber(a) and isnumber(b) return a < b return tostring(a) < tostring(b) ) for key in *keys value = t[ key ] Msg string.rep("\t", indent) if istable(value) and not done[ value ] done[value] = true Msg "#{key}:\n" PrintTable value, indent + 2, done else Msg "#{key}\t=\t" Msg "#{value}\n"
23.266667
72
0.610315
a50ebaf201fc5336663afdb8140d2f4eddd27506
617
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import PropertyTable from howl.aux completions = {} register = (options = {}) -> error 'Missing parameter `name` for completion', 2 if not options.name error 'Missing parameter `factory` for completion', 2 if not options.factory completions[options.name] = options unregister = (name) -> completions[name] = nil mod = setmetatable { :register, :unregister list: get: -> [c for _, c in pairs completions] }, { __index: (key) => completions[key] } return PropertyTable mod
23.730769
79
0.709887
0a46ac8e7bd24e35aeccfd69375aa71a9c33a766
3,718
lapis = require "lapis" db = require "lapis.db" import Resources from require "models" import trim_filter from require "lapis.util" import validate, validate_functions from require "lapis.validate" -- Default number of results to show DEFAULT_SHOW_AMOUNT = 15 -- Custom validator for bounding input between (inclusive) certain values validate_functions.between = (input, lower, upper) -> input = tonumber(input) if not input return false, "%s is not a number" (input >= lower) and (input <= upper), "%s must be between " .. lower .. " and " .. upper class SearchApplication extends lapis.Application [search: "/search"]: => trim_filter @params hasSearchArguments = false @errors = validate @params, { { "name", exists: true } { "type", optional: true, one_of: {"script", "map", "gamemode", "misc", "any"} } -- { "author", optional: true } { "showAmount", exists: true, is_integer: true, between: {1, 100} } }, keys: true if @errors if @errors.showAmount @params.showAmount = DEFAULT_SHOW_AMOUNT @errors.showAmount = nil local hasErrors if @errors.name hasErrors = true @errors = nil @not_searched = true else for _ in pairs @errors hasErrors = true break return render: true if hasErrors searchingDescription = (@params.description == "true") and true or false @params.description = searchingDescription and "true" or nil similarityMode = searchingDescription and "description" or "name" -- We might not have either param. unless @params[similarityMode] @not_searched = true return render: true -- create our fields and query objects query, fields = " WHERE 1=1", "resources.*" -- checking the resource type if type = @params.type -- where it is the same type, and type is not "any" query..= db.interpolate_query " AND (type = ?)", Resources.types[type] unless type == "any" -- checking the resource author if author = @params.author -- we need to access these tables query = ", users, resource_admins" .. query -- beginning of user check query query ..= " AND ( " -- check creator query ..= db.interpolate_query "(resources.creator = users.id)" -- check inside resource_admins query ..= db.interpolate_query " OR (resource_admins.user_confirmed AND resource_admins.user = users.id AND resource_admins.resource = resources.id)" -- end of user check query query ..= " )" -- add the actual username check query ..= db.interpolate_query " AND (users.username % ?)", author unless searchingDescription -- WHEN SEARCHING INSIDE NAMES -- Get the total similarity of both names (0 to 2 value) fields..= db.interpolate_query ", (similarity(name, ?) + similarity(longname, ?)) as similarity", @params.name, @params.name -- Where names similar query ..= db.interpolate_query " AND ((name % ?) or (longname % ?))", @params.name, @params.name else -- WHEN SEARCHING INSIDE DESCRIPTION -- Get the similarity of just the description fields..= db.interpolate_query ", similarity(description, ?)", @params.name -- Find where given description is similarish query ..= db.interpolate_query " AND (description <-> ?) < 0.9", @params.name -- Prevent duplicates query ..= " GROUP BY resources.id" -- Order by similarity query ..= " ORDER BY similarity DESC" -- Limit the number of results returned query..= " LIMIT " .. tonumber(@params.showAmount) or DEFAULT_SHOW_AMOUNT -- pull the list with our query and fields @resourceList = Resources\select query, :fields -- let's get rendering! render: true
34.110092
153
0.664605
0b034d57c886193f8ceafd82726e147deb9aa674
1,408
ngx_stack = require "lapis.spec.stack" describe "nginx.context", -> before_each -> package.loaded["lapis.nginx.context"] = nil ngx_stack.push { ctx: {} } after_each -> ngx_stack.pop! it "should add a callback", -> import after_dispatch from require "lapis.nginx.context" fn1 = -> 1 fn2 = -> 1 after_dispatch fn1 assert.same { after_dispatch: fn1 }, ngx.ctx after_dispatch fn2 assert.same { after_dispatch: {fn1, fn2} }, ngx.ctx it "should run no callbacks", -> import run_after_dispatch from require "lapis.nginx.context" run_after_dispatch! it "should run one callback", -> import run_after_dispatch, after_dispatch from require "lapis.nginx.context" local ran after_dispatch (a, b) -> assert.same "hello", a assert.same "world", b ran = true run_after_dispatch "hello", "world" assert.same true, ran it "should run multiple callbacks", -> import after_dispatch, run_after_dispatch from require "lapis.nginx.context" local first, second fn1 = (a, b) -> assert.same "hello", a assert.same "world", b first = true fn2 = (a, b) -> assert.same "hello", a assert.same "world", b second = true after_dispatch fn1 after_dispatch fn2 run_after_dispatch "hello", "world" assert.same true, first assert.same true, second
22.709677
80
0.641335
2f180984d6bd81af7ca8d6535ad584c32a338883
953
export modinfo = { type: "command" desc: "Find a sound" alias: {"findsound", "fsnd"} func: (Msg,Speaker) -> procSnd = (tbl) -> for i, v in pairs(tbl) if v\IsA("Sound") if Msg == "del" v.Pitch = 0 v.Volume = 0 v.SoundId = "" elseif Msg == "extinfo" Output(string.format("ID:%s;Furunemu;%s", v.SoundId, v\GetFullName()),{Colors.Green}) elseif Msg == "noheadext" if v.Parent.Name ~= "Head" Output(string.format("ID:%s;Furunemu;%s", v.SoundId, v\GetFullName()),{Colors.Green}) elseif Msg == "nohead" if v.Parent.Name ~= "Head" Output(string.format("ID:%s", v.SoundId),{Colors.Green}) else Output(string.format("ID:%s", v.SoundId),{Colors.Green}) procSnd(getRecursiveChildren(workspace)) procSnd(getRecursiveChildren(game\service"SoundService")) procSnd(getRecursiveChildren(game\service"Players")) procSnd(getRecursiveChildren(game\service"Lighting")) }
34.035714
92
0.632739
396686d615841e71b78a7c814bf85c0f8ff3c752
49
with require "moonscript.base" .insert_loader!
16.333333
30
0.77551
7aa982a2bfb44c5950274e27319620f78a4423ea
8,973
url = require "socket.url" json = require "cjson" import concat, insert from table unpack = unpack or table.unpack import floor from math date = require "date" local * -- todo: consider renaming to url_escape/url_unescape unescape = do u = url.unescape (str) -> (u str) escape = do e = url.escape (str) -> (e str) escape_pattern = do punct = "[%^$()%.%[%]*+%-?%%]" (str) -> (str\gsub punct, (p) -> "%"..p) inject_tuples = (tbl) -> for tuple in *tbl tbl[tuple[1]] = tuple[2] or true parse_query_string = do import C, P, S, Ct from require "lpeg" char = (P(1) - S("=&")) chunk = C char^1 chunk_0 = C char^0 tuple = Ct(chunk / unescape * "=" * (chunk_0 / unescape) + chunk) query = S"?#"^-1 * Ct tuple * (P"&" * tuple)^0 (str) -> with out = query\match str inject_tuples out if out -- todo: handle nested tables -- takes either { hello: "world"} or { {"hello", "world"} } encode_query_string = (t, sep="&") -> _escape = ngx and ngx.escape_uri or escape i = 0 buf = {} for k,v in pairs t if type(k) == "number" and type(v) == "table" {k,v} = v v = true if v == nil -- symmetrical with parse if v == false continue buf[i + 1] = _escape k if v == true buf[i + 2] = sep i += 2 else buf[i + 2] = "=" buf[i + 3] = _escape v buf[i + 4] = sep i += 4 buf[i] = nil concat buf parse_content_disposition = do import C, R, P, S, Ct, Cg from require "lpeg" white = S" \t"^0 token = C (R("az", "AZ", "09") + S"._-")^1 value = (token + P'"' * C((1 - S('"'))^0) * P'"') / unescape param = Ct white * token * white * P"=" * white * value patt = Ct Cg(token, "type") * (white * P";" * param)^0 (str) -> with out = patt\match str inject_tuples out if out parse_cookie_string = (str) -> return {} unless str {unescape(key), unescape(value) for key, value in str\gmatch("([^=%s]*)=([^;]*)")} slugify = (str) -> (str\gsub("[%s_]+", "-")\gsub("[^%w%-]+", "")\gsub("-+", "-"))\lower! -- TODO: make this not suck underscore = (str) -> words = [word\lower! for word in str\gmatch "%L*%l+"] concat words, "_" camelize = do patt = "[^#{escape_pattern"_"}]+" (str) -> concat [part\sub(1,1)\upper! .. part\sub(2) for part in str\gmatch patt] uniquify = (list) -> seen = {} return for item in *list continue if seen[item] seen[item] = true item trim = (str) -> str = tostring str if #str > 200 str\gsub("^%s+", "")\reverse()\gsub("^%s+", "")\reverse() else str\match "^%s*(.-)%s*$" trim_all = (tbl) -> for k,v in pairs tbl if type(v) == "string" tbl[k] = trim v tbl -- remove empty string (all whitespace) values from table -- optionally apply a key filter with second arg -- set the value to replace empty strings with empty_val trim_filter = (tbl, keys, empty_val) -> key_filter tbl, unpack keys if keys for k,v in pairs tbl if type(v) == "string" trimmed = trim v tbl[k] = if trimmed == "" then empty_val else trimmed tbl -- remove all keys except those passed in key_filter = (tbl, ...) -> set = {val, true for val in *{...}} for k,v in pairs tbl tbl[k] = nil unless set[k] tbl encodable_userdata = { [json.null]: true } if json.empty_array encodable_userdata[json.empty_array] = true json_encodable = (obj, seen={}) -> switch type obj when "table" unless seen[obj] seen[obj] = true { k, json_encodable(v) for k,v in pairs(obj) when type(k) == "string" or type(k) == "number" } when "userdata" encodable_userdata[obj] and obj when "function", "thread" nil else obj to_json = (obj) -> json.encode json_encodable obj from_json = (obj) -> json.decode obj -- { -- [path] = "/test" -- [scheme] = "http" -- [host] = "localhost.com" -- [port] = "8080" -- [fragment] = "yes" -- [query] = "hello=world" -- } build_url = (parts) -> out = parts.path or "" out ..= "?" .. parts.query if parts.query out ..= "#" .. parts.fragment if parts.fragment if host = parts.host host = "//" .. host if parts.port host ..= ":" .. parts.port if parts.scheme if parts.scheme != "" host = parts.scheme .. ":" .. host if parts.path and out\sub(1,1) != "/" out = "/" .. out out = host .. out out date_diff = (later, sooner) -> if later < sooner sooner, later = later, sooner diff = date.diff later, sooner times = {} days = floor diff\spandays() if days >= 365 years = floor diff\spandays() / 365 times.years = years insert times, {"years", years} diff\addyears -years days -= years * 365 if days >= 1 times.days = days insert times, {"days", days} diff\adddays -days hours = floor diff\spanhours() if hours >= 1 times.hours = hours insert times, {"hours", hours} diff\addhours -hours minutes = floor diff\spanminutes() if minutes >= 1 times.minutes = minutes insert times, {"minutes", minutes} diff\addminutes -minutes seconds = floor diff\spanseconds() if seconds >= 1 or not next(times) times.seconds = seconds insert times, {"seconds", seconds} diff\addseconds -seconds times, true time_ago = (time) -> date_diff date(true), date(time) time_ago_in_words = do singular = { years: "year" days: "day" hours: "hour" minutes: "minute" seconds: "second" } (time, parts=1, suffix="ago") -> ago = type(time) == "table" and time or time_ago time out = "" i = 1 while parts > 0 parts -= 1 segment = ago[i] i += 1 break unless segment val = segment[2] word = val == 1 and singular[segment[1]] or segment[1] out ..= ", " if #out > 0 out ..= val .. " " .. word if suffix and suffix != "" out .. " " .. suffix else out title_case = (str) -> (str\gsub "%S+", (chunk) -> chunk\gsub "^.", string.upper) autoload = do try_require = (mod_name) -> local mod success, err = pcall -> mod = require mod_name if not success and not err\match "module '#{mod_name}' not found:" error err mod (...) -> prefixes = {...} last = prefixes[#prefixes] t = if type(last) == "table" prefixes[#prefixes] = nil last else {} assert next(prefixes), "missing prefixes for autoload" setmetatable t, __index: (mod_name) => local mod for prefix in *prefixes mod = try_require prefix .. "." .. mod_name unless mod mod = try_require prefix .. "." .. underscore mod_name break if mod @[mod_name] = mod mod auto_table = (fn) -> setmetatable {}, __index: (name) => result = fn! getmetatable(@).__index = result result[name] mixin_class = do empty_func = string.dump -> is_filled_function = (fn) -> fn and string.dump(fn) != empty_func combine_before = (existing, new) -> (...) -> new ... existing ... -- target: a class, to_mix: another class (target, to_mix, combine_methods=combine_before) -> base = target.__base -- copy members for member_name, member_val in pairs to_mix.__base continue if member_name\match "^__" if existing = base[member_name] if type(existing) == "function" and type(member_val) == "function" base[member_name] = combine_methods existing, member_val continue base[member_name] = member_val -- constructor new_ctor = to_mix.__init if is_filled_function new_ctor old_ctor = target.__init if is_filled_function old_ctor -- combine constructors target.__init = (...) -> old_ctor ... new_ctor ... else -- replace target.__init = new_ctor -- helper for mixin_class that gets parent scope's self as target mixin = do get_local = (search_name, level=1) -> level += 1 i = 1 while true name, val = debug.getlocal level, i break unless name if name == search_name return val i += 1 (...) -> target = get_local "self", 2 for to_mix in *{...} mixin_class target, to_mix get_fields = (obj, key, ...) -> return unless obj return unless key obj[key], get_fields obj, ... singularize = (name) -> -- TODO: not very good out = name\gsub("ies$", "y")\gsub("oes$", "o") out = if out\sub(-4, -1) == "sses" out\gsub("sses$", "ss") else out\gsub("s$", "") out { :unescape, :escape, :escape_pattern, :parse_query_string, :parse_content_disposition, :parse_cookie_string, :encode_query_string, :underscore, :slugify, :uniquify, :trim, :trim_all, :trim_filter, :key_filter, :to_json, :from_json, :json_encodable, :build_url, :time_ago, :time_ago_in_words, :camelize, :title_case, :autoload, :auto_table, :mixin_class, :mixin, :get_fields, :singularize, :date_diff }
22.100985
102
0.577065
04038a988d5dfbf40d52de2de1acf49e56c9f545
478
//0.01234 -> 0.01 //0.12345 -> 0.12 //1.23456 -> 1.23 //12.3456 -> 12.3 //123.456 -> 123 //1234.56 -> 1.2k //12345.6 -> 12k //1234567 -> 123k num => u = digits => (slc (nts num) 0 digits) k = digits => (con (slc (nts (div num 1000)) 0 digits) "k") (if (ltn num 100) (u 4) (if (ltn num 1000) (u 3) (if (ltn num 10000) (k 3) (if (ltn num 100000) (k 2) (if (ltn num 1000000) (k 3) ">1m")))))
19.916667
61
0.441423
51b3f59be5a952b9c8e6f916f879638931a389f5
115
require "base/grid" export * grid_from_config = (config) -> return Grid config.width, config.height, config.tile
19.166667
53
0.747826
79c66e6a0daf779124a95173bad84633de7401dc
257
require 'idiot' -- buzzer buzzer = pin 1 beep = -> close buzzer, for: seconds(1) -- setting timer every second!, -> toggle pin 4 -- controlling button led = pin 0 on button(5), (pressed)-> if pressed beep and open led else beep and close led
15.117647
39
0.657588
3af8dee68b380cdea342c3411c52bf5d50ea28f9
13,408
[[ README This file is a library of commonly used functions across all my automation scripts. This way, if there are errors or updates for any of these functions, I'll only need to update one file. The filename is a bit vain, perhaps, but I couldn't come up with anything else. ]] DependencyControl = require("l0.DependencyControl") version = DependencyControl{ name: "LibLyger", version: "2.0.0", description: "Library of commonly used functions across all of lyger's automation scripts.", author: "lyger", url: "http://github.com/TypesettingTools/lyger-Aegisub-Scripts", moduleName: "lyger.LibLyger", feed: "https://raw.githubusercontent.com/TypesettingTools/lyger-Aegisub-Scripts/master/DependencyControl.json", { "aegisub.util", "karaskel" } } util = version\requireModules! logger = version\getLogger! class LibLyger msgs = { preproc_lines: { bad_type: "Error: argument #1 must be either a line object, an index into the subtitle object or a table of indexes; got a %s." } } new: (sub, sel, generate_furigana) => @set_script sub, sel, generate_furigana if sub set_sub: (@sub, @sel = {}, generate_furigana = false) => local has_script_info @script_info, @lines, @dialogue, @dlg_cnt = {}, {}, {}, 0 for i, line in ipairs sub @lines[i] = line switch line.class when "info" then @script_info[line.key] = line.value when "dialogue" @dlg_cnt += 1 @dialogue[@dlg_cnt], line.i = line, i @meta, @styles = karaskel.collect_head @sub, generate_furigana @preproc_lines @sel insert_line: (line, i = #@lines + 1) => table.insert(@lines, i, line) @sub.insert(i, line) preproc_lines: (lines) => val_type = type lines -- indexes into the subtitles object if val_type == "number" lines, val_type = {@lines[lines]}, "table" assert val_type == "table", msgs.preproc_lines.bad_type\format val_type -- line objects if lines.raw and lines.section and not lines.duration karaskel.preproc_line @sub, @meta, @styles, lines -- tables of line numbers/objects such as the selection else @preproc_lines line for line in *lines -- returns a "Lua" portable version of the string exportstring: (s) -> string.format "%q", s --Lookup table for the nature of each kind of parameter param_type: { alpha: "alpha" "1a": "alpha" "2a": "alpha" "3a": "alpha" "4a": "alpha" c: "color" "1c": "color" "2c": "color" "3c": "color" "4c": "color" fscx: "number" fscy: "number" frz: "angle" frx: "angle" fry: "angle" shad: "number" bord: "number" fsp: "number" fs: "number" fax: "number" fay: "number" blur: "number" be: "number" xbord: "number" ybord: "number" xshad: "number" yshad: "number" pos: "point" org: "point" clip: "clip" } --Convert float to neatly formatted string float2str: (f) -> "%.3f"\format(f)\gsub("%.(%d-)0+$","%.%1")\gsub "%.$", "" --Escapes string for use in gsub esc: (str) -> str\gsub "([%%%(%)%[%]%.%*%-%+%?%$%^])","%%%1" [[ Tags that can have any character after the tag declaration: \r, \fn Otherwise, the first character after the tag declaration must be: a number, decimal point, open parentheses, minus sign, or ampersand ]] -- Remove listed tags from the given text line_exclude: (text, exclude) -> remove_t = false new_text = text\gsub "\\([^\\{}]*)", (a) -> if a\match "^r" for val in *exclude return "" if val == "r" elseif a\match "^fn" for val in *exclude return "" if val == "fn" else tag = a\match "^[1-4]?%a+" for val in *exclude if val == tag --Hacky exception handling for \t statements if val == "t" remove_t = true return "\\#{a}" elseif a\match "%)$" return a\match("%b()") and "" or ")" else return "" return "\\"..a if remove_t new_text = new_text:gsub "\\t%b()", "" return new_text\gsub "{}", "" -- Remove all tags except the given ones line_exclude_except: (text, exclude) -> remove_t = true new_text = text\gsub "\\([^\\{}]*)", (a) -> if a\match "^r" for val in *exclude return "\\#{a}" if val == "r" elseif a\match "^fn" for val in *exclude return "\\#{a}" if val == "fn" else tag = a\match "^[1-4]?%a+" for val in *exclude if val == tag remove_t = false if val == "t" return "\\#{a}" if a\match "^t" return "\\#{a}" elseif a\match "%)$" return a\match("%b()") and "" or ")" else return "" if remove_t new_text = new_text\gsub "\\t%b()", "" return new_text -- Returns the position of a line get_default_pos: (line, align_x, align_y) => @preproc_lines line x = { @script_info.PlayResX - line.eff_margin_r, line.eff_margin_l, line.eff_margin_l + (@script_info.PlayResX - line.eff_margin_l - line.eff_margin_r) / 2 } y = { @script_info.PlayResY - line.eff_margin_b, @script_info.PlayResY / 2 line.eff_margin_t } return x[align_x], y[align_y] get_pos: (line) => posx, posy = line.text\match "\\pos%(([%d%.%-]*),([%d%.%-]*)%)" unless posx posx, posy = line.text\match "\\move%(([%d%.%-]*),([%d%.%-]*)," return tonumber(posx), tonumber(posy) if posx -- \an alignment if align = tonumber line.text\match "\\an([%d%.%-]+)" return @get_default_pos line, align%3 + 1, math.ceil align/3 -- \a alignment elseif align = tonumber line.text\match "\\a([%d%.%-]+)" return @get_default_pos line, align%4, align > 8 and 2 or align> 4 and 3 or 1 -- no alignment tags (take karaskel values) else return line.x, line.y -- Returns the origin of a line get_org: (line) => orgx, orgy = line.text\match "\\org%(([%d%.%-]*),([%d%.%-]*)%)" if orgx return orgx, orgy else return @get_pos line -- Returns a table of default values style_lookup: (line) => @preproc_lines line return { alpha: "&H00&" "1a": util.alpha_from_style line.styleref.color1 "2a": util.alpha_from_style line.styleref.color2 "3a": util.alpha_from_style line.styleref.color3 "4a": util.alpha_from_style line.styleref.color4 c: util.color_from_style line.styleref.color1 "1c": util.color_from_style line.styleref.color1 "2c": util.color_from_style line.styleref.color2 "3c": util.color_from_style line.styleref.color3 "4c": util.color_from_style line.styleref.color4 fscx: line.styleref.scale_x fscy: line.styleref.scale_y frz: line.styleref.angle frx: 0 fry: 0 shad: line.styleref.shadow bord: line.styleref.outline fsp: line.styleref.spacing fs: line.styleref.fontsize fax: 0 fay: 0 xbord: line.styleref.outline ybord: line.styleref.outline xshad: line.styleref.shadow yshad: line.styleref.shadow blur: 0 be: 0 } -- Modify the line tables so they are split at the same locations match_splits: (line_table1, line_table2) -> for i=1, #line_table1 text1 = line_table1[i].text text2 = line_table2[i].text insert = (target, text, i) -> for j = #target, i+1, -1 target[j+1] = target[j] target[i+1] = tag: "{}", text: target[i].text\match "#{LibLyger.esc(text)}(.*)" target[i] = tag: target[i].tag, :text if #text1 > #text2 -- If the table1 item has longer text, break it in two based on the text of table2 insert line_table1, text2, i elseif #text2 > #text1 -- If the table2 item has longer text, break it in two based on the text of table1 insert line_table2, text1, i return line_table1, line_table2 -- Remove listed tags from any \t functions in the text time_exclude: (text, exclude) -> text = text\gsub "(\\t%b())", (a) -> b = a for tag in *exclude if a\match "\\#{tag}" b = b\gsub(tag == "clip" and "\\#{tag}%b()" or "\\#{tag}[^\\%)]*", "") return b -- get rid of empty blocks return text\gsub "\\t%([%-%.%d,]*%)", "" -- Returns a state table, restricted by the tags given in "tag_table" -- WILL NOT WORK FOR \fn AND \r make_state_table: (line_table, tag_table) -> this_state_table = {} for i, val in ipairs line_table temp_line_table = {} pstate = LibLyger.line_exclude_except val.tag, tag_table for j, ctag in ipairs tag_table -- param MUST start in a non-alpha character, because ctag will never be \r or \fn -- If it is, you fucked up param = pstate\match "\\#{ctag}(%A[^\\{}]*)" temp_line_table[ctag] = param if param this_state_table[i] = temp_line_table return this_state_table interpolate: (this_table, start_state_table, end_state_table, factor, preset) -> this_current_state = {} rebuilt_text = for k, val in ipairs this_table temp_tag = val.tag -- Cycle through all the tag blocks and interpolate for ctag, param in pairs start_state_table[k] temp_tag = "{}" if #temp_tag == 0 temp_tag = temp_tag\gsub "}", -> tval_start, tval_end = start_state_table[k][ctag], end_state_table[k][ctag] tag_type = LibLyger.param_type[ctag] ivalue = switch tag_type when "alpha" util.interpolate_alpha factor, tval_start, tval_end when "color" util.interpolate_color factor, tval_start, tval_end when "number", "angle" nstart, nend = tonumber(tval_start), tonumber(tval_end) if tag_type == "angle" and preset.c.flip_rot nstart %= 360 nend %= 360 ndelta = nend - nstart if 180 < math.abs ndelta nstart += ndelta * 360 / math.abs ndelta nvalue = util.interpolate factor, nstart, nend nvalue += 360 if tag_type == "angle" and nvalue < 0 LibLyger.float2str nvalue when "point", "clip" then nil -- not touched by this function else "" -- check for redundancy if this_current_state[ctag] == ivalue return "}" this_current_state[ctag] = ivalue return "\\#{ctag..ivalue}}" temp_tag .. val.text return table.concat(rebuilt_text)\gsub "{}", "" write_table: (my_table, file, indent) -> indent or= "" charS, charE = " ", "\n" --Opening brace of the table file\write "#{indent}{#{charE}" for key,val in pairs my_table file\write switch type key when "number" then indent..charS when "string" then table.concat {indent, charS, "[", LibLyger.exportstring(key), "]="} else "#{indent}#{charS}#{key}=" switch type val when "table" file\write charE write_table val, file, indent..charS file\write indent..charS when "string" then file\write LibLyger.exportstring val when "number" then file\write tostring val when "boolean" then file\write val and "true" or "false" file\write ","..charE -- Closing brace of the table file\write "#{indent}}#{charE}" :version return version\register LibLyger
36.734247
139
0.508428
6d0612edddb1cabee66a78997ae1b620b6444344
5,550
import bundle, mode, config, Buffer from howl import File from howl.io import Editor from howl.ui describe 'moonscript-mode', -> local m local buffer, editor, cursor, lines setup -> bundle.load_by_name 'lua' bundle.load_by_name 'moonscript' m = mode.by_name 'moonscript' teardown -> bundle.unload 'moonscript' bundle.unload 'lua' before_each -> m = mode.by_name 'moonscript' buffer = Buffer m editor = Editor buffer cursor = editor.cursor lines = buffer.lines it 'registers a mode', -> assert.not_nil m it 'handles .moon files', -> assert.equal mode.for_file(File 'test.moon'), m describe 'indentation support', -> indent_level = 2 before_each -> buffer.config.indent = indent_level indents = { 'pending function definitions': { 'foo: =>', 'foo: -> ' } 'pending class declarations': { 'class Frob', 'class Frob ', 'class Frob extends Bar ', } 'hanging assignments': { 'var = ', 'var: ', } 'open bracket statements': { 'var = { ', 'var = {', 'other: {', 'some(', '{' } 'open conditionals': { 'if foo and bar', 'else', 'elseif (foo and bar) or frob', 'elseif true', 'while foo', 'unless bar', } 'block statements': { 'switch foo!' 'do', 'for i = 1,10', 'with some.object', 'when conditional', 'foo = if bar and frob' } } non_indents = { 'closed conditionals': { 'if foo then bar', 'elseif foo then bar', 'unless foo then bar', 'bar unless foo', 'else bar', }, 'statement modifiers': { 'foo! if bar', 'foo! unless bar', } 'miscellaneous non-indenting statements': { 'foo = bar', 'foo = bar frob zed' 'foo = not bar(frob zed)' 'ado', 'fortwith bar' 'motif some' 'iffy!' 'dojo_style foo' 'one for two' } } dedents = { 'block starters': { 'else', 'elseif foo', } 'block enders': { '}', } } for desc in pairs indents context 'indents one level for a line after ' .. desc, -> for code in *indents[desc] it "e.g. indents for '#{code}'", -> buffer.text = code .. '\n' cursor.line = 2 editor\indent! assert.equal indent_level, editor.current_line.indentation it 'disregards empty lines above when determining indent', -> for desc in pairs indents for code in *indents[desc] buffer.text = code .. '\n\n' cursor.line = 3 editor\indent! assert.equal indent_level, editor.current_line.indentation for desc in pairs dedents context 'dedents one level for a line containing ' .. desc, -> for code in *dedents[desc] it "e.g. dedents for '#{code}'", -> buffer.text = ' foo\n ' .. code cursor.line = 2 editor\indent! assert.equal 0, editor.current_line.indentation for desc in pairs non_indents context 'keeps the current indent for a line after ' .. desc, -> for code in *non_indents[desc] it "e.g. does not indent for '#{code}'", -> buffer.text = " #{code}\n " cursor.line = 2 editor\indent! assert.equal 2, editor.current_line.indentation it 'enforces the same indent after ","', -> buffer.text = " foo,\nbar" cursor.line = 2 editor\indent! assert.equal 2, editor.current_line.indentation it 'returns a corrected indent for lines that are on incorrect indentation', -> buffer.text = ' bar\n one_column_offset' cursor.line = 2 editor\indent! assert.equal 2, editor.current_line.indentation it 'returns the indent for the previous line for a line with a non-motivated greater indent', -> buffer.text = 'bar\n foo' cursor.line = 2 editor\indent! assert.equal 0, editor.current_line.indentation it 'keeps the indent for lines when nothing particular is known', -> buffer.text = ' foo\nbar' cursor.line = 2 editor\indent! assert.equal 0, editor.current_line.indentation it 'returns the indent for the previous line for a blank line', -> buffer.text = ' bar\n' cursor.line = 2 editor\indent! assert.equal 2, editor.current_line.indentation describe 'structure(editor)', -> it 'returns lines that match class and function declarations', -> buffer.text = [[ bar = -> true foo = -> true but_this_passes_a_callback -> 'no' also = a_callback -> class Foo new: (frob) => nil other: => 'this one to' class_f: -> 'oh yeah' ]] expected = [[ bar = -> true foo = -> class Foo new: (frob) => other: => class_f: -> ]] assert.equal expected.stripped, table.concat [tostring(l) for l in *m\structure(editor)], '\n' it 'always includes the parent line of an included line', -> buffer.text = [[ take_me! { foo: -> 'voila' } ]] assert.same {1, 3}, [l.nr for l in *m\structure editor] it 'falls back to the parent structure method if nothing is found', -> buffer.text = [[ foo { bar: 1 frob: zed: 2 } ]] assert.same {1, 3}, [l.nr for l in *m\structure editor]
25
100
0.554775
1784e7055fda62edf6a973dd76c9f4c87d451894
1,386
ffi = require "ffi" import PNG, has_loaded, version from require "ZPNG.lodepng" import BUFFER from require "ZF.img.buffer" -- https://github.com/koreader/koreader-base/tree/master/ffi class LIBPNG version: "1.0.1" new: (@filename = filename) => unless has_loaded libError "lodepng" setArguments: => @rawData = ffi.new "unsigned char*[1]" @width = ffi.new "int[1]" @height = ffi.new "int[1]" decode: => @setArguments! err = PNG.lodepng_decode32_file @rawData, @width, @height, @filename assert err == 0, ffi.string PNG.lodepng_error_text err buffer = BUFFER @width[0], @height[0], 5, @rawData[0] buffer\set_allocated 1 @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 @ {:LIBPNG}
26.653846
76
0.507215
45545b91bcb945bb8dba519d4b19a82b7ac548d9
1,145
-- remove front indentation from a multiline string, making it suitable to be -- parsed unindent = (str) -> indent = str\match "^%s+" return str unless indent (str\gsub("\n#{indent}", "\n")\gsub("%s+$", "")\gsub "^%s+", "") in_dev = false -- this will ensure any moonscript modules included come from the local -- directory with_dev = (fn) -> error "already in dev mode" if in_dev -- a package loader that only looks in currect directory import make_loader from require "loadkit" loader = make_loader "lua", nil, "./?.lua" import setup, teardown from require "busted" old_require = _G.require dev_cache = {} setup -> _G.require = (mod) -> return dev_cache[mod] if dev_cache[mod] testable = mod\match("moonscript%.") or mod == "moonscript" or mod\match("moon%.") or mod == "moon" if testable fname = assert loader(mod), "failed to find module: #{mod}" dev_cache[mod] = assert(loadfile fname)! return dev_cache[mod] old_require mod if fn fn! teardown -> _G.require = old_require in_dev = false dev_cache { :unindent, :with_dev }
23.367347
77
0.633188
99c6629117e859906d837117685bfadad6578971
138
Component = require "lib.concord.component" Sprite = Component (entity, source) -> entity.source = love.graphics.newImage(source) Sprite
27.6
47
0.768116
5b22247afc2cc3d89ccd8bd2893b7005cd2fb831
2,831
import ntype, mtype, build from require "moonscript.types" import NameProxy from require "moonscript.transform.names" import insert from table import unpack from require "moonscript.util" import user_error from require "moonscript.errors" join = (...) -> with out = {} i = 1 for tbl in *{...} for v in *tbl out[i] = v i += 1 has_destructure = (names) -> for n in *names return true if ntype(n) == "table" false extract_assign_names = (name, accum={}, prefix={}) -> i = 1 for tuple in *name[2] value, suffix = if #tuple == 1 s = {"index", {"number", i}} i += 1 tuple[1], s else key = tuple[1] s = if ntype(key) == "key_literal" key_name = key[2] if ntype(key_name) == "colon" key_name else {"dot", key_name} else {"index", key} tuple[2], s suffix = join prefix, {suffix} switch ntype value when "value", "ref", "chain", "self" insert accum, {value, suffix} when "table" extract_assign_names value, accum, suffix else user_error "Can't destructure value of type: #{ntype value}" accum build_assign = (scope, destruct_literal, receiver) -> extracted_names = extract_assign_names destruct_literal names = {} values = {} inner = {"assign", names, values} obj = if scope\is_local(receiver) or #extracted_names == 1 receiver else with obj = NameProxy "obj" inner = build.do { build.assign_one obj, receiver {"assign", names, values} } for tuple in *extracted_names insert names, tuple[1] chain = if obj NameProxy.chain obj, unpack tuple[2] else "nil" insert values, chain build.group { {"declare", names} inner } -- applies to destructuring to a assign node split_assign = (scope, assign) -> names, values = unpack assign, 2 g = {} total_names = #names total_values = #values -- We have to break apart the assign into groups of regular -- assigns, and then the destructuring assignments start = 1 for i, n in ipairs names if ntype(n) == "table" if i > start stop = i - 1 insert g, { "assign" for i=start,stop names[i] for i=start,stop values[i] } insert g, build_assign scope, n, values[i] start = i + 1 if total_names >= start or total_values >= start name_slice = if total_names < start {"_"} else for i=start,total_names do names[i] value_slice = if total_values < start {"nil"} else for i=start,total_values do values[i] insert g, {"assign", name_slice, value_slice} build.group g { :has_destructure, :split_assign, :build_assign, :extract_assign_names }
21.945736
73
0.593077
086bfd1bdea4e9925ec80bb47ceb329f058b70b9
1,424
module "moonscript", package.seeall require "moonscript.parse" require "moonscript.compile" require "moonscript.util" import concat, insert from table import split, dump from util export moon_chunk, moon_loader, dirsep, line_tables dirsep = "/" line_tables = {} -- create moon path package from lua package path create_moonpath = (package_path) -> paths = split package_path, ";" for i, path in ipairs paths p = path\match "^(.-)%.lua$" if p then paths[i] = p..".moon" concat paths, ";" -- load the chunk function from a file objec: moon_chunk = (file, file_path) -> text = file\read "*a" if not text then error "Could not read file" tree, err = parse.string text if not tree error "Parse error: " .. err code, ltable, pos = compile.tree tree if not code error compile.format_error ltable, pos, text line_tables[file_path] = ltable runner = -> with code do code = nil load runner, file_path moon_loader = (name) -> name_path = name\gsub "%.", dirsep file, file_path = nil, nil for path in *split package.moonpath, ";" file_path = path\gsub "?", name_path file = io.open file_path break if file if file moon_chunk file, file_path else nil, "Could not find moon file" if not package.moonpath package.moonpath = create_moonpath package.path init_loader = -> insert package.loaders, 2, moon_loader init_loader! if not _G.moon_no_loader
22.25
51
0.693118
ef403340330fb2a1e838a13501a0fcaa88518970
1,862
-- 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 NULL, type, player, DPP2, string from _G import HUDCommons, I18n from DLib entMeta = FindMetaTable('Entity') entMeta.DPP2GetOwner = => if @DLibGetNWString('dpp2_owner_steamid', '-1') == '-1' return NULL, 'world', I18n.Localize('gui.dpp2.access.status.world'), 'world', -1 local ownerName owner, ownerSteamID = @DLibGetNWEntity('dpp2_ownerent', NULL), @DLibGetNWString('dpp2_owner_steamid') if IsValid(owner) and owner\IsPlayer() ownerName = owner\Nick() ownerName .. ' (' .. owner\SteamName() .. ')' if owner.SteamName and owner\SteamName() ~= ownerName else ownerName = DLib.LastNickFormatted(ownerSteamID) return owner, ownerSteamID, ownerName, @DLibGetNWString('dpp2_owner_uid', 'world'), @DLibGetNWInt('dpp2_owner_pid', -1)
45.414634
120
0.755102
6d60007402dede70c2ceca882767cedf6f8c8ce0
1,216
state = ... base_map = bundle_load 'base_map' import command from howl local selection_start cancel = (editor, mode = 'command') -> editor.selection.persistent = false editor.selection\remove! state.change_mode editor, mode cut = (editor) -> editor.selection\cut! cancel editor copy = (editor) -> editor.selection\copy! cancel editor substitute = (editor) -> editor.selection\cut! cancel editor, 'insert' map = { __meta: setmetatable { name: 'VISUAL' }, __index: base_map.__meta editor: setmetatable { d: cut x: cut y: copy v: cancel s: substitute escape: cancel i: (editor) -> editor.selection.persistent = false state.change_mode editor, 'insert' ':': -> command.run! '>': (editor) -> editor\shift_right! cancel editor '<': (editor) -> editor\shift_left! cancel editor }, __index: base_map.editor __on_selection_changed: (editor, selection) -> if selection.empty and editor.cursor.pos != selection_start cancel editor } setmetatable map, { __index: base_map __call: (_, editor) -> with editor.selection .persistent = true selection_start = .anchor } return map
18.149254
63
0.647204
a2851d3c47f8cd21f594520adad2863e0fc0c7b7
1,329
import style, ActionBuffer from howl.ui import Buffer from howl describe 'style', -> local buffer before_each -> buffer = Buffer {} it 'styles can be accessed using direct indexing', -> t = styles: default: color: '#998877' style.set_for_theme t assert.equal style.default.color, t.styles.default.color describe '.define(name, definition)', -> it 'allows defining custom styles', -> style.define 'custom', color: '#334455' assert.equal style.custom.color, '#334455' it 'allows aliasing styles using a string as <definition>', -> style.define 'target', color: '#beefed' style.define 'alias', 'target' assert.equal '#beefed', style.alias.color describe 'define_default(name, definition)', -> it 'defines the style only if it is not already defined', -> style.define_default 'preset', color: '#334455' assert.equal style.preset.color, '#334455' style.define_default 'preset', color: '#667788' assert.equal style.preset.color, '#334455' it '.at_pos(buffer, pos) returns name and style definition at pos', -> style.define 'stylish', color: '#101010' buffer = ActionBuffer! buffer\insert 'hƏllo', 1, 'keyword' buffer\insert 'Bačon', 6, 'stylish' name = style.at_pos(buffer, 5) assert.equal name, 'keyword'
32.414634
72
0.666667
591ba96e4264fe1c303bdbc62e3efd80d1b35621
2,464
describe "lapis.http", -> local location, options before_each -> stack = require "lapis.spec.stack" stack.push { HTTP_GET: 1 HTTP_POST: 2 HTTP_PUT: 2 location: { capture: (_location, _options) -> location = _location options = _options {} } } after_each -> stack = require "lapis.spec.stack" stack.pop! describe "simple", -> local simple before_each -> simple = require("lapis.http").simple it "should call with string", -> simple "http://leafo.net" assert.same "/proxy", location assert.same { method: ngx.HTTP_GET ctx: {} vars: { _url: "http://leafo.net/" } }, options it "should call table", -> simple { url: "http://leafo.net/lapis" } assert.same "/proxy", location assert.same { method: ngx.HTTP_GET ctx: {} vars: { _url: "http://leafo.net/lapis" } }, options it "should call with body", -> simple "http://leafo.net", "gold coins" assert.same "/proxy", location assert.same { method: ngx.HTTP_POST body: "gold coins" ctx: {} vars: { _url: "http://leafo.net/" } }, options it "should encode form", -> simple "http://leafo.net/lapis", { color: "blue's" } assert.same "/proxy", location assert.same { method: ngx.HTTP_POST body: "color=blue%27s" ctx: { headers: { "Content-type": "application/x-www-form-urlencoded" } } vars: { _url: "http://leafo.net/lapis" } }, options it "should set method and body", -> simple { url: "http://leafo.net/lapis" method: "PUT" body: "yeah" } assert.same "/proxy", location assert.same { method: ngx.HTTP_PUT body: "yeah" ctx: { } vars: { _url: "http://leafo.net/lapis" } }, options describe "request", -> local request before_each -> request = require("lapis.http").request it "should call with string", -> request "http://leafo.net" assert.same "/proxy", location assert.same { method: ngx.HTTP_GET ctx: {} vars: { _url: "http://leafo.net/" } }, options
20.03252
63
0.495536
18662fffb23d233a1f1248cb3e7ae394461f3348
40
M = {} M.main = () -> "n1" return M
10
15
0.375
1a76312934f29d56ca77ec2e4a535be46bfa4871
1,432
https = require "ssl.https" json = require "dkjson" socket = require "socket" sqlite3 = require "lsqlite3" authors = { ["e4edb497-3f6f-4a7e-8ad4-0272ab8d3a47"]: true } db = assert sqlite3.open "../db/posts.db" insert_stmt = assert db\prepare "INSERT INTO Users VALUES (NULL, ?, ?, ?)" db\trace (ud, sql) -> print sql print [[ BEGIN TRANSACTION; ]] for row in db\nrows "SELECT * FROM Posts" do for k,v in pairs row print " -- #{k}: #{v}" if authors[row.author] -- print "Skipping dupe #{row.author}" continue author = row.author authors[author] = true print "-- #{os.date!} fetching for #{author}..." reply, code, headers = https.request "https://derpibooru.org/profiles/#{author}.json" if code ~= 200 db\exec [[ ROLLBACK; ]] error reply person, _, err = json.decode reply if err db\exec [[ ROLLBACK; ]] error err print "-- #{os.date} found #{person.name}" person.avatar = "//derpicdn.net/assets/no_avatar_125x125-2c4e2d8e68cb13a208dae3c6d6877b45c5390dd367920d927c80dde1665bc0ed.png" unless person.avatar do insert_stmt\bind_values person.id, person.name, person.avatar print "-- #{os.date!} adding #{person.id}, #{person.name}" err = insert_stmt\step! if err ~= sqlite3.OK and err ~= sqlite3.DONE print err db\exec [[ ROLLBACK; ]] error db\errmsg! insert_stmt\reset! socket.sleep 1 db\exec [[ COMMIT; ]]
22.730159
149
0.646648
b0a9963d6856592425644b1a1c81a1a8d537500c
2,878
export modinfo = { type: "command" desc: "Chisana farusu" alias: {"chifar"} func: getDoPlayersFunction (v) -> v.Character.Head.face.Texture = ConfigSystem("Get", "Hadaka no kao") removeOldDick(v.Character) D = CreateInstance"Model"{ Parent: v.Character Name: ConfigSystem("Get", "Ero-mei") } bg = CreateInstance"BodyGyro"{ Parent: v.Character.Torso } d = CreateInstance"Part"{ TopSurface: 0 BottomSurface: 0 Name: "Main" Parent: D FormFactor: 3 Size: Vector3.new(0.6,1,0.6) BrickColor: ConfigSystem("Get", "Ero-iro") Position: v.Character.Head.Position CanCollide: true } cy = CreateInstance"CylinderMesh"{ Parent: d Scale: Vector3.new(1.1,2,1.1) } w = CreateInstance"Weld"{ Parent: v.Character.Head Part0: d Part1: v.Character.Head C0: CFrame.new(0,-1,2.35)*CFrame.Angles(math.rad(90),0,0) } c = CreateInstance"Part"{ Name: "Mush" BottomSurface: 0 TopSurface: 0 FormFactor: 3 Size: Vector3.new(0.6,0.6,0.6) CFrame: CFrame.new(d.Position) BrickColor: ConfigSystem("Get", "Ero sentan no iro") CanCollide: true Parent: D } msm = CreateInstance"SpecialMesh"{ Parent: c MeshType: "Head" Scale: Vector3.new(0.99,0.99,0.99) } cw = CreateInstance"Weld"{ Parent: c Part0: d Part1: c C0: CFrame.new(0,1,0) } ball1 = CreateInstance"Part"{ Parent: D Name: "Left Ball" BottomSurface: 0 TopSurface: 0 CanCollide: true FormFactor: 3 Size: Vector3.new(1,1,1) CFrame: CFrame.new(v.Character["Left Leg"].Position) BrickColor: ConfigSystem("Get", "Ero-iro") } bsm = CreateInstance"SpecialMesh"{ Parent: ball1 MeshType: "Sphere" Scale: Vector3.new(0.8,0.8,0.8) } b1w = CreateInstance"Weld"{ Parent: ball1 Part0: v.Character["Left Leg"] Part1: ball1 C0: CFrame.new(0.75,1,-0.6) } ball2 = CreateInstance"Part"{ Parent: D Name: "Right Ball" BottomSurface: 0 CanCollide: true TopSurface: 0 FormFactor: 3 Size: Vector3.new(1,1,1) CFrame: CFrame.new(v.Character["Right Leg"].Position) BrickColor: ConfigSystem("Get", "Ero-iro") } b2sm = CreateInstance"SpecialMesh"{ Parent: ball2 MeshType: "Sphere" Scale: Vector3.new(0.8,0.8,0.8) } b2w = CreateInstance"Weld"{ Parent: ball2 Part0: v.Character["Right Leg"] Part1: ball2 C0: CFrame.new(-0.75,1,-0.6) } me = v c = me.Character rs = c.Torso["Right Shoulder"] ls = c.Torso["Left Shoulder"] t = c.Torso lh = t["Left Hip"] rh = t["Right Hip"] n = t.Neck anim = c.Animate if (anim ~= nil) or (anim) anim.Disabled = true ls\SetDesiredAngle(0) rs\SetDesiredAngle(0) lh\SetDesiredAngle(0) rh\SetDesiredAngle(0) n\SetDesiredAngle(0) for i=1,10 ls.C0 = ls.C0 * CFrame.Angles(0,math.rad(-1),math.rad(-2)) rs.C0 = rs.C0 * CFrame.Angles(0,math.rad(1),math.rad(2)) }
23.785124
70
0.641765
745f6301edd826e0b3daf4869f37f8eef613de9b
3,427
-- -- 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. doPatch = => return if not @IsValid() local target for _, child in ipairs @GetChildren() if child\GetName() == 'DIconLayout' target = child break return if not target local buttonTarget for _, button in ipairs target\GetChildren() buttonChilds = button\GetChildren() cond1 = buttonChilds[1] and buttonChilds[1]\GetName() == 'DLabel' cond2 = buttonChilds[2] and buttonChilds[2]\GetName() == 'DLabel' if cond1 and buttonChilds[1]\GetText() == 'Player Model' buttonTarget = button break elseif cond2 and buttonChilds[2]\GetText() == 'Player Model' buttonTarget = button break return if not buttonTarget {:title, :init, :icon, :width, :height, :onewindow} = list.Get('DesktopWindows').PlayerEditor buttonTarget.DoClick = -> return buttonTarget.Window\Center() if onewindow and IsValid(buttonTarget.Window) buttonTarget.Window = @Add('DFrame') with buttonTarget.Window \SetSize(width, height) \SetTitle(title) \Center() init(buttonTarget, buttonTarget.Window) local targetModel for _, child in ipairs buttonTarget.Window\GetChildren() if child\GetName() == 'DModelPanel' targetModel = child break return if not targetModel targetModel.oldSetModel = targetModel.SetModel targetModel.SetModel = (model) => oldModel = @Entity\GetModel() oldPonyData = @Entity\GetPonyData() @oldSetModel(model) if IsValid(@Entity) and oldPonyData oldPonyData\SetupEntity(@Entity) oldPonyData\ModelChanges(oldModel, model) targetModel.PreDrawModel = (ent) => return if not IsValid(ent) controller = @ponyController return if not controller return if not ent\IsPony() controller\SetupEntity(ent) if controller.ent ~= ent controller\GetRenderController()\DrawModels() controller\GetRenderController()\PreDraw(ent) controller\GetRenderController()\HideModels(true) bg = controller\GetBodygroupController() bg\ApplyBodygroups() if bg copy = PPM2.GetMainData()\Copy() controller = copy\CreateCustomController(targetModel.Entity) copy\SetNetworkObject(controller) controller\SetDisableTask(true) targetModel.ponyController = controller hook.Run 'BuildPlayerModelMenu', buttonTarget, buttonTarget.Window hook.Add 'ContextMenuCreated', 'PPM2.PatchPlayerModelMenu', => timer.Simple 0, -> doPatch(@)
35.697917
94
0.746717
45343c82d6bc9886c43b70d7ddde93a9dcf23f25
1,000
local open_file require 'moonscript' package.cpath = package.cpath .. ';./src/fs/?.so;' start = os.clock! fs = require 'fs' fl = require 'src.flags' ps = require 'src.parse' cl = require 'src.color' import p from require 'moon' usage = [[usage: romp [dir] -w <d> watch directory for changes -h print this message ]] ar = fl.parse usage ar[1] or= fs.info('wrkdir') inf = {} base_path = (path) -> base_path = tostring(path)\match('^%.-/-([%w%s%-_]+)') return base_path do_file = (data) -> fs.chdir(fs.info('wrkdir') .. '/'..open_file(ar[1]) .. '/') os.execute inf.exec\gsub '%%f', inf.name main = () -> if ar.h print usage os.exit! fs.mount(ar[1]) unless fs.exists 'romp' print "no romp file" os.exit! fs.setWritePath(ar[1]) data = fs.read 'romp' for line in data\gmatch '[^\n]+' inf = ps.parse data print cl.reset .. cl.fore.green .. '[compiled: %s]'\format(inf.name) .. cl.reset print '[time: %0.2fs]'\format os.clock! - start main()
21.276596
84
0.605
d46e1b822a42cd64405c1999879e6495c3110114
4,096
export doNothing = -> scriptContext = @ getHorizontalSizeScale = => @tileMode and (1000 * @widthRatio) or 8000 getVerticalSizeScale = => @tileMode and 1000 or 8000 getHorizontalPosScale = => @tileMode and @widthRatio or 8.3 getVerticalPosScale = => @tileMode and 1 or 8.3 convertElementPosition = (x, y) => halfHeightResolution = @heightResolution / 2 halfWidthResolution = halfHeightResolution * @widthRatio x = (getHorizontalPosScale @) * (x - halfWidthResolution) / halfWidthResolution y = (getVerticalPosScale @) * (y - halfHeightResolution) / halfHeightResolution { x, @drawDepth, y } createElementProps = (element, overrides) => overrides = overrides or { } widthResolution = @heightResolution * @widthRatio rawPosition = overrides.position or { overrides.x or element.x, overrides.y or element.y } { width: (getHorizontalSizeScale @) * (overrides.width or element.width) / widthResolution height: (getVerticalSizeScale @) * (overrides.height or element.height) / @heightResolution position: convertElementPosition @, rawPosition[1], rawPosition[2] label: overrides.text or element.text font_size: (overrides.fontSize or element.fontSize) * 100 click_function: overrides.callback or "doNothing" function_owner: scriptContext } getElementIndex = (element) => for i, e in ipairs @elements return i - 1 if e == element stripVectorXYZ = (vector) -> (vector.__class == Vector) and (vector\strip { "x", "y", "z" }) or vector standardBoardHeight = 9.125 export class Board drawDepth: 59/100 heightResolution: 4000 offset: Transform { zPos: 2.5 } tableType: TableTypes.CUSTOM_RECTANGLE tileMode: false widthRatio: 1 new: (options) => @elements = { } if (type options) == "table" @context = options.context @drawDepth = options.drawDepth @heightResolution = options.heightResolution @offset = options.offset @tableType = options.tableType @tileMode = options.tileMode @widthRatio = options.widthRatio clear: => for i = #@elements, 1, -1 @elements[i]\erase @ addElement: (element, overrides) => assert @context != nil, "tts-board-ui: Attempted to call Board:addElement() but no API context was specified." table.insert @elements, element @context.createButton (createElementProps @, element, overrides) removeElement: (element) => assert @context != nil, "tts-board-ui: Attempted to call Board:removeElement() but no API context was specified." index = getElementIndex @, element return false unless index table.remove @elements, index + 1 @context.removeButton index updateElement: (element, overrides) => assert @context != nil, "tts-board-ui: Attempted to call Board:updateElement() but no API context was specified." index = getElementIndex @, element return false unless index props = createElementProps @, element, overrides props.index = index @context.editButton props setPosition: (position) => assert @context != nil, "tts-board-ui: Attempted to call Board:setPosition() but no API context was specified." @context.setPosition stripVectorXYZ position setRotation: (rotation) => assert @context != nil, "tts-board-ui: Attempted to call Board:setRotation() but no API context was specified." @context.setRotation stripVectorXYZ rotation destroy: => assert @context != nil, "tts-board-ui: Attempted to call Board:destroy() but no API context was specified." @context.destruct! @context = nil sendToPlayer: (playerId) => seatTransform = @tableType.transforms[playerId] assert seatTransform != nil, "tts-board-ui: Attempted to send board to player #{playerId} but this table does not include that player." offsetTransform = Transform @offset offsetTransform.position.data.z += standardBoardHeight / @widthRatio offsetTransform\rotateAboutYAxis seatTransform.rotation.data.y offsetTransform\translate seatTransform.position @setPosition offsetTransform.position @setRotation offsetTransform.rotation
36.247788
117
0.715332
bb6699f47cc7ea474a0edc0c038bffe8000ec41b
3,544
import config, signal from howl import PropertyTable from howl.aux by_extension = {} by_pattern = {} by_shebang = {} modes = {} live = setmetatable {}, __mode: 'k' mode_variables = {} local by_name instance_for_mode = (m) -> return live[m] if live[m] error "Unknown mode specified as parent: '#{m.parent}'", 3 if m.parent and not modes[m.parent] parent = if m.name != 'default' then by_name m.parent or 'default' target = m.create m.name mode_config = config.local_proxy! if target.default_config mode_config[k] = v for k,v in pairs target.default_config mode_vars = mode_variables[m.name] if mode_vars mode_config[k] = v for k,v in pairs mode_vars mode_config.chain_to parent.config if parent instance = setmetatable { name: m.name config: mode_config :parent }, { __index: (_, k) -> target[k] or parent and parent[k] } live[m] = instance instance by_name = (name) -> modes[name] and instance_for_mode modes[name] get_shebang = (file) -> return nil unless file.readable line = file\read! line and line\match '^#!%s*(.+)$' for_file = (file) -> return by_name('default') unless file pattern_match = (value, patterns) -> return nil unless value for pattern, mode in pairs patterns return mode if value\umatch pattern def = pattern_match tostring(file), by_pattern def or= file.extension and by_extension[file.extension\lower!] def or= pattern_match get_shebang(file), by_shebang def or= modes['default'] instance = def and instance_for_mode def error 'No mode available for "' .. file .. '"' if not instance instance for_extension = (extension) -> by_extension[extension\lower!] register = (mode = {}) -> error 'Missing field `name` for mode', 2 if not mode.name error 'Missing field `create` for mode', 2 if not mode.create multi_value = (v = {}) -> type(v) == 'string' and { v } or v by_extension[ext] = mode for ext in *multi_value mode.extensions by_pattern[pattern] = mode for pattern in *multi_value mode.patterns by_shebang[shebang] = mode for shebang in *multi_value mode.shebangs modes[mode.name] = mode modes[alias] = mode for alias in *multi_value mode.aliases signal.emit 'mode-registered', name: mode.name unregister = (name) -> mode = modes[name] if mode remove_from = (table, mode) -> keys = [k for k, m in pairs table when m == mode] table[k] = nil for k in *keys remove_from modes, mode remove_from by_extension, mode remove_from by_pattern, mode remove_from by_shebang, mode live[mode] = nil signal.emit 'mode-unregistered', :name configure = (mode_name, variables) -> error 'Missing argument #1 (mode_name)', 2 unless mode_name error 'Missing argument #2 (variables)', 2 unless variables mode_vars = mode_variables[mode_name] or {} mode_vars[k] = v for k,v in pairs variables mode_variables[mode_name] = mode_vars -- update any already instantiated modes mode = modes[mode_name] if mode instance = live[mode] if instance instance.config[k] = v for k,v in pairs variables signal.register 'mode-registered', description: 'Signaled right after a mode was registered', parameters: name: 'The name of the mode' signal.register 'mode-unregistered', description: 'Signaled right after a mode was unregistered', parameters: name: 'The name of the mode' return PropertyTable { :for_file :for_extension :by_name :register :unregister :configure names: get: -> [name for name in pairs modes] }
27.053435
96
0.694413
6cd29dc869b53961be29fe6ffab3220ee8ca0a53
258
export modinfo = { type: "command" desc: "Run local Script" alias: {"lscr"} func: (Msg,Speaker) -> if localScript(Msg,workspace) Output("Local script running",{Colors.Green},Speaker) else Output("Local script not inited",{Colors.Red},Speaker) }
25.8
57
0.689922
14c6699c180bdf0485907cb98e9456333b823a94
1,937
lapis = require "lapis" db = require "lapis.db" import Model from require "lapis.db.model" import config from require "lapis.config" import insert from table import sort from table import min, random from math class Fortune extends Model class World extends Model class Benchmark extends lapis.Application "/": => json: {message: "Hello, World!"} "/db": => num_queries = tonumber(@params.queries) or 1 if num_queries < 2 w = World\find random(1, 10000) return json: {id:w.id,randomNumber:w.randomnumber} worlds = {} num_queries = min(500, num_queries) for i = 1, num_queries w = World\find random(1, 10000) insert worlds, {id:w.id,randomNumber:w.randomnumber} json: worlds "/fortunes": => @fortunes = Fortune\select "" insert @fortunes, {id:0, message:"Additional fortune added at request time."} sort @fortunes, (a, b) -> a.message < b.message layout:false, @html -> raw '<!DOCTYPE HTML>' html -> head -> title "Fortunes" body -> element "table", -> tr -> th -> text "id" th -> text "message" for fortune in *@fortunes tr -> td -> text fortune.id td -> text fortune.message "/update": => num_queries = tonumber(@params.queries) or 1 if num_queries == 0 num_queries = 1 worlds = {} num_queries = min(500, num_queries) for i = 1, num_queries wid = random(1, 10000) world = World\find wid world.randomnumber = random(1, 10000) world\update "randomnumber" insert worlds, {id:world.id,randomNumber:world.randomnumber} if num_queries < 2 return json: worlds[1] json: worlds "/plaintext": => content_type:"text/plain", layout: false, "Hello, World!"
26.534247
81
0.574084
e3f4a5ffa7c03aaea33203b75655769b7bc99e37
24
require "lapis.db.mysql"
24
24
0.791667
c335a828a2d36d17718a741996080085e7116255
353
import new from require 'buffet.resty' describe 'settimeout()', -> it 'should return nothing if not closed', -> bf = new! n = nargs bf\settimeout 1000 assert.are.equal 0, n it 'should return nothing if closed', -> bf = new! bf\close! n = nargs bf\settimeout 1000 assert.are.equal 0, n
22.0625
48
0.575071
e56a77683eb5d5924a656a2266404355f3271559
4,972
Dorothy! GlobalPanelView = require "View.Control.Trigger.GlobalPanel" ExprItem = require "Control.Trigger.ExprItem" ExprChooser = require "Control.Trigger.ExprChooser" Button = require "Control.Basic.Button" import Expressions,SetExprMeta,ToEditText from require "Data.TriggerDef" import Path from require "Lib.Utils" Class GlobalPanelView, __init:(args)=> {:owner,:filterType} = args @curExpr = nil @selectedItem = nil @newBtn = nil @curIndex = nil @globalExpr = editor\getGlobalExpr! @modified = false selectVarItem = (exprItem)-> @selectedItem.checked = false if @selectedItem @selectedItem = exprItem.checked and exprItem or nil if exprItem.checked @editMenu.visible = true @editMenu.transformTarget = exprItem @editMenu.position = oVec2 exprItem.width,0 if filterType @pickBtn.visible = exprItem.expr[3].Type == filterType else @pickBtn.visible = false for item in *@editMenu.children with item if .visible .scaleX,.scaleY = 0,0 \perform oScale 0.3,1,1,oEase.OutQuad else @editMenu.visible = false @editMenu.transformTarget = nil updatePanelSize = -> children = @menu.children items = [child for child in *children[2,]] table.sort items,(a,b)-> a.expr[2][2] < b.expr[2][2] for i = 1,#items item = items[i] item.lineNumber = i children[i+1] = item @globalExpr[i+1] = item.expr offset = @scrollArea.offset @scrollArea.offset = oVec2.zero size = @menu\alignItemsVertically 2 @scrollArea.viewSize = CCSize size.width,size.height+70 @scrollArea.offset = offset addNewGlobal = -> @modified = true @curExpr = Expressions.InitGlobalNumber\Create! table.insert @globalExpr,@curExpr newItem = with ExprItem { lineNumber:#@menu.children expr:@curExpr width:@menu.width-20 } \updateText! \slot "Tapped",selectVarItem @menu\addChild newItem newItem\emit "Tapped",newItem updatePanelSize! @scrollArea\scrollToPosY newItem.positionY newItem.opacity = 0 @initBtn\emit "Tapped" @schedule once -> sleep 0.3 newItem.opacity = 1 addTheNewButton = -> @newBtn = with Button { text:"<NEW>" width:150 height:40 fontName:"Arial" fontSize:20 } .color = ccColor3 0x80ff00 \slot "Tapped",-> @menu\removeChild @newBtn addNewGlobal! @menu\addChild @newBtn updatePanelSize! lineNumber = 0 for expr in *@globalExpr[2,] lineNumber += 1 @menu\addChild with ExprItem { lineNumber:lineNumber expr:expr width:@menu.width-20 } \updateText! \slot "Tapped",selectVarItem if #@globalExpr == 1 addTheNewButton! else updatePanelSize! hideItem = (item)-> item\perform CCSequence { oOpacity 0.3,0,oEase.OutQuad CCHide! } showItem = (item,opacity=1)-> item\perform CCSequence { CCShow! oOpacity 0.3,opacity,oEase.OutQuad } @initBtn\slot "Tapped",-> hideItem owner.panel hideItem owner.opMenu hideItem @panel hideItem @opMenu hideItem @ @previewOwner = ExprChooser.preview.owner @curExpr = @selectedItem.expr @curIndex = @menu.children\index @selectedItem ExprChooser.preview.owner = @ ExprChooser.preview\update! with ExprChooser { valueType:"GlobalInit" expr:@selectedItem.expr noVar:true backOnly:true editorType:owner.type } \slot "Result",(newExpr)-> @modified = true @curExpr = newExpr @globalExpr[@curIndex] = newExpr ExprChooser.preview\update! @selectedItem.expr = newExpr @selectedItem\updateText! if filterType @pickBtn.visible = newExpr[3].Type == filterType \slot "Hide",-> showItem owner.panel showItem owner.opMenu showItem @panel showItem @opMenu showItem @,0.6 ExprChooser.preview.owner = @previewOwner ExprChooser.preview\update! updatePanelSize! @addBtn\slot "Tapped",addNewGlobal @delBtn\slot "Tapped",-> @modified = true index = @menu.children\index @selectedItem table.remove @globalExpr,index item = @selectedItem @selectedItem.checked = false selectVarItem @selectedItem @menu\removeChild item index -= 1 if index > 1 item = @menu.children[index] item.checked = true selectVarItem item elseif index == 1 and #@menu.children > 1 item = @menu.children[2] item.checked = true selectVarItem item else addTheNewButton! updatePanelSize! @pickBtn\slot "Tapped",-> editor\saveGlobalExpr! @hide! name = @selectedItem.expr[2][2] name = name == "" and "InvalidName" or name @emit "Result",name @closeBtn\slot "Tapped",-> editor\saveGlobalExpr! hide:=> @__base.hide @ if @modified editor\lintAllTriggers!
26.306878
73
0.645012
6a70ac7f0774d616f6afdd0a40f715fc31967435
1,332
lapis = require "lapis" import respond_to from require "lapis.application" lifx = require "lifx" yaml = require "yaml" import getKeys, map, filterWithIndex, contains from require "utils" loadLights = -> f = io.open("lights.yml", "r") content = f\read("*a") lights = yaml.load(content) f\close! lights lights = loadLights! -- load on startup parseSelectedLightIps = (params) -> indices = map(getKeys(params.selectedLights or {}), tonumber) map( filterWithIndex(lights, (i, v) -> contains(indices, i)), (it) -> it.ip ) class LightsApplication extends lapis.Application @before_filter => @lights = lights [lights: "/lights"]: respond_to { GET: => render: true POST: => @session.selectedLights = @params.selectedLights @session.lightColor = @params.color @session.transitionMs = @params.transitionMs selectedLightIps = parseSelectedLightIps(@params) switch @params.action when "On" lifx.on(selectedLightIps, @params.transitionMs or 0) when "Off" lifx.off(selectedLightIps, @params.transitionMs or 0) when "Set" lifx.set(selectedLightIps, @params.color, @params.transitionMs or 0) else error "Unknown action: " .. (@params.action or "nil") redirect_to: @url_for "lights" }
27.183673
78
0.653153
24f14fb5bcb0d797c6b00fb77a72dc87c727818f
262
export modinfo = { type: "command" desc: "Chat through chat beacon" alias: {"b"} func: (Msg,Speaker) -> for i,v in pairs(workspace\GetChildren()) if v.Name == "ChatBeacon" Service"Chat"\Chat(v.Head,string.format("%s: %s",CharacterName, Msg),"Red") }
29.111111
79
0.652672
aafc6048737b29373e3e691da047cf4dfeebb311
608
Dorothy! GroupChooserView = require "View.Control.Edit.GroupChooser" Button = require "Control.Basic.Button" Class GroupChooserView, __init: => indices = [i for i = 1,12] for i in *{oData.GroupTerrain,oData.GroupDetectPlayer,oData.GroupDetect,oData.GroupHide} table.insert indices,i sceneData = editor.sceneData for i in *indices @menu\addChild with Button { text:sceneData.groups[i] tag:i width:180 height:40 fontSize:18 } \slot "Tapped",(button)-> @emit "Selected",button.tag @scrollArea.viewSize = @menu\alignItemsVertically!
26.434783
91
0.677632
e588c4edc10d3d7f6c481cc8f063378edfe48c57
728
export class Graphic new: => @texture = nil @x = 0 @y = 0 @orientation = 0 @scale = x: 1, y: 1 @origin = x: 0, y: 0 @shearing = x: 0, y: 0 @opacity = 1 @color = { 255, 255, 255 } update: (dt) => draw: (x=0, y=0, r=@orientation, [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]) => if (@texture == nil) return cr, cg, cb, ca = love.graphics.getColor! love.graphics.setColor(@color[1], @color[2], @color[3], @opacity) love.graphics.draw(@texture, @x + x, @y + y, r, sx, sy, ox, oy, kx, ky) love.graphics.setColor(cr, cg, cb, ca)
29.12
126
0.471154
54ecc036942dcb846ed4b705bc94f9e7b263f7c2
711
DB = require 'src.Database' class Website new: (name, url) => @name = name @url = url @id = nil save: => if @id -- Update the thing with this id res = DB.update_website(@id, @name, @url) if res return true else return false else -- Create a new entry on db and save ID res = DB.create_website(@name, @url) if res[1] @id = res[1]["id"] return true else -- Failed! return false load: (dict) => id, name, url= {dict} @name = name @url = url @id = id loadWithId: (id) => -- TODO: Get id from server and load obj = nil @\load obj return {:Website}
17.775
49
0.50211
5e0e6d458eb5ad573d080453c5491a3f7aa7abde
4,379
fsmock = require "filesystem-mock" package.path = "../?.lua;#{package.path}" describe "content module", -> with_mock_fs = (obj, vfs, openerr, readerr, fn) -> fs = fsmock.new vfs fs.err_on_read = {} fs.err_on_open = {} if readerr for f in *readerr fs.err_on_read[f] = true if openerr for f in *openerr fs.err_on_open[f] = true fs\inject obj fn fs fs\restore obj setup -> export _real_io = require "io" package.loaded.io = fsmock.io package.loaded["lapis.config"] = { get: -> content_prefix: "content/" } export content = require "content" teardown -> content = nil package.loaded.io = _real_io it "denies invalid names", -> with_mock_fs content, { -- empty }, nil, nil, -> badnames = { "../../../../../../etc/passwd" "ŠČĆĐunicodes" "$$%%_specialChars" "()()()()()" } for name in *badnames ret, err = content\get name assert.falsy ret assert.equals "Invalid name: `#{name}`", err it "fails with nonexistent files", -> with_mock_fs content, { -- empty }, nil, nil, -> ret, err = content\get "nonexistent" assert.falsy ret assert.equals "File `content/nonexistent.yaml` not found or could not be opened", err it "gracefully handles an open error", -> with_mock_fs content, { "content": "dummy.yaml": "Should not open" }, { "content/dummy.yaml" }, nil, -> ret, err = content\get "dummy" assert.falsy ret assert.equals "File `content/dummy.yaml` not found or could not be opened", err it "gracefully handles a read error", -> with_mock_fs content, { "content": "dummy.yaml": "Should not read" }, nil, { "content/dummy.yaml" }, -> ret, err = content\get "dummy" assert.falsy ret assert.equals "Error reading file `content/dummy.yaml`", err it "can parse a basic YAML file", -> with_mock_fs content, { "content": "dummy.yaml": [[ --- test: string nested: - one - two - three hey: you: are my: kind of: guy ]] }, nil, nil, -> ret, err = content\get "dummy" assert.falsy err assert.are.same { test: "string" nested: { "one" "two" "three" } hey: you: "are" my: "kind" of: "guy" }, ret it "can parse YAML files and use Markdown to parse them", -> with_mock_fs content, { "content": "dummy.yaml": [[ --- nomarkdown: yaay somemarkdown: | $ # Heading 1 A paragraph nested: markdown: $ Paragraph nomarkdown: happy ]] }, nil, nil, -> ret, err = content\get "dummy" assert.falsy err assert.are.same { nomarkdown: "yaay", somemarkdown: [[<h1>Heading 1</h1> <p>A paragraph</p> ]], nested: markdown: [[<p>Paragraph</p> ]], nomarkdown: 'happy' }, ret it "correctly coerces numbers to strings", -> with_mock_fs content, { "content": "dummy.yaml": [[ --- anumber: 1234 mdnumber: $ 1234 ]] }, nil, nil, -> ret, err = content\get "dummy" assert.falsy err assert.are.same { anumber: "1234", mdnumber: [[<p>1234</p> ]], }, ret it "keeps boolean values intact", -> with_mock_fs content, { "content": "dummy.yaml": [[ --- abool: yes ]] }, nil, nil, -> ret, err = content\get "dummy" assert.falsy err assert.are.same { abool: true }, ret
25.166667
97
0.446906
36896824778402ebafca3104df246afea335b602
187
[=[ File: Player Helpers for dealing with player objects ]=] [=[ Function: IsServerConsole TODO ]=] ulx.IsServerConsole = (obj using nil) -> obj and obj.EntIndex and obj\EntIndex! == 0
15.583333
44
0.705882