entities
listlengths
1
8.61k
max_stars_repo_path
stringlengths
7
172
max_stars_repo_name
stringlengths
5
89
max_stars_count
int64
0
82k
content
stringlengths
14
1.05M
id
stringlengths
2
6
new_content
stringlengths
15
1.05M
modified
bool
1 class
references
stringlengths
29
1.05M
[ { "context": "module.exports = {\n\n name: \"Vala\"\n namespace: \"vala\"\n\n ###\n Supported Grammars\n", "end": 33, "score": 0.6875685453414917, "start": 29, "tag": "NAME", "value": "Vala" } ]
src/languages/vala.coffee
jmullercuber/atom-beautify
1,783
module.exports = { name: "Vala" namespace: "vala" ### Supported Grammars ### grammars: [ "Vala" ] ### Supported extensions ### extensions: [ "vala" "vapi" ] options: configPath: type: 'string' default: "" description: "Path to uncrustify config file. i.e. uncrustify.cfg" }
113408
module.exports = { name: "<NAME>" namespace: "vala" ### Supported Grammars ### grammars: [ "Vala" ] ### Supported extensions ### extensions: [ "vala" "vapi" ] options: configPath: type: 'string' default: "" description: "Path to uncrustify config file. i.e. uncrustify.cfg" }
true
module.exports = { name: "PI:NAME:<NAME>END_PI" namespace: "vala" ### Supported Grammars ### grammars: [ "Vala" ] ### Supported extensions ### extensions: [ "vala" "vapi" ] options: configPath: type: 'string' default: "" description: "Path to uncrustify config file. i.e. uncrustify.cfg" }
[ { "context": "(top left corner) in the viewport.\n #\n # Author: Peter-Paul Koch, http://www.quirksmode.org/js/findpos.html\n find", "end": 111, "score": 0.9997816681861877, "start": 96, "tag": "NAME", "value": "Peter-Paul Koch" } ]
src/utils.coffee
digineo/signat0r
1
Utils = # Finds the position of an element (top left corner) in the viewport. # # Author: Peter-Paul Koch, http://www.quirksmode.org/js/findpos.html findPosition: (elem)-> leftPos = topPos = 0 if elem.offsetParent while true leftPos += elem.offsetLeft topPos += elem.offsetTop break unless elem = elem.offsetParent return [leftPos, topPos] # Ensures that the given val is in the range [min..max]. rangeCap: (val, min, max)-> return min if val < min return max if val > max val
217242
Utils = # Finds the position of an element (top left corner) in the viewport. # # Author: <NAME>, http://www.quirksmode.org/js/findpos.html findPosition: (elem)-> leftPos = topPos = 0 if elem.offsetParent while true leftPos += elem.offsetLeft topPos += elem.offsetTop break unless elem = elem.offsetParent return [leftPos, topPos] # Ensures that the given val is in the range [min..max]. rangeCap: (val, min, max)-> return min if val < min return max if val > max val
true
Utils = # Finds the position of an element (top left corner) in the viewport. # # Author: PI:NAME:<NAME>END_PI, http://www.quirksmode.org/js/findpos.html findPosition: (elem)-> leftPos = topPos = 0 if elem.offsetParent while true leftPos += elem.offsetLeft topPos += elem.offsetTop break unless elem = elem.offsetParent return [leftPos, topPos] # Ensures that the given val is in the range [min..max]. rangeCap: (val, min, max)-> return min if val < min return max if val > max val
[ { "context": " grunt-hipchat-v2-notifier\n# * https://github.com/logankoester/grunt-hipchat-v2-notifier\n# *\n# * Copyright (c) 2", "end": 67, "score": 0.9993730187416077, "start": 55, "tag": "USERNAME", "value": "logankoester" }, { "context": "ipchat-v2-notifier\n# *\n# * Copyright ...
src/tasks/hipchat_notifier.coffee
jasonmit/grunt-hipchat-v2-notifier
1
# # * grunt-hipchat-v2-notifier # * https://github.com/logankoester/grunt-hipchat-v2-notifier # * # * Copyright (c) 2013-2014 Logan Koester # * Licensed under the MIT license. # module.exports = (grunt) -> Hipchatter = require 'hipchatter' grunt.registerMultiTask 'hipchat_notifier', 'Send a message to a Hipchat room', -> grunt.config.requires 'hipchat_notifier.options.roomId' options = @options( color: 'yellow' notify: false message: 'Hello world' message_format: 'html' ) grunt.verbose.writeflags options, 'Options' grunt.verbose.writeln "Token: #{options.authToken}" done = @async() hipchat = new Hipchatter(options.authToken) grunt.verbose.writeln "Room: #{options.roomId}" grunt.log.writeln 'Sending Hipchat notification...' params = color: options.color?() ? options.color message: options.message?() ? options.message message_format: options.message_format notify: options.notify token: options.token hipchat.notify options.roomId, params, (success) -> grunt.log.writeln 'Notification sent!' done()
135729
# # * grunt-hipchat-v2-notifier # * https://github.com/logankoester/grunt-hipchat-v2-notifier # * # * Copyright (c) 2013-2014 <NAME> # * Licensed under the MIT license. # module.exports = (grunt) -> Hipchatter = require 'hipchatter' grunt.registerMultiTask 'hipchat_notifier', 'Send a message to a Hipchat room', -> grunt.config.requires 'hipchat_notifier.options.roomId' options = @options( color: 'yellow' notify: false message: 'Hello world' message_format: 'html' ) grunt.verbose.writeflags options, 'Options' grunt.verbose.writeln "Token: #{options.authToken}" done = @async() hipchat = new Hipchatter(options.authToken) grunt.verbose.writeln "Room: #{options.roomId}" grunt.log.writeln 'Sending Hipchat notification...' params = color: options.color?() ? options.color message: options.message?() ? options.message message_format: options.message_format notify: options.notify token: options.token hipchat.notify options.roomId, params, (success) -> grunt.log.writeln 'Notification sent!' done()
true
# # * grunt-hipchat-v2-notifier # * https://github.com/logankoester/grunt-hipchat-v2-notifier # * # * Copyright (c) 2013-2014 PI:NAME:<NAME>END_PI # * Licensed under the MIT license. # module.exports = (grunt) -> Hipchatter = require 'hipchatter' grunt.registerMultiTask 'hipchat_notifier', 'Send a message to a Hipchat room', -> grunt.config.requires 'hipchat_notifier.options.roomId' options = @options( color: 'yellow' notify: false message: 'Hello world' message_format: 'html' ) grunt.verbose.writeflags options, 'Options' grunt.verbose.writeln "Token: #{options.authToken}" done = @async() hipchat = new Hipchatter(options.authToken) grunt.verbose.writeln "Room: #{options.roomId}" grunt.log.writeln 'Sending Hipchat notification...' params = color: options.color?() ? options.color message: options.message?() ? options.message message_format: options.message_format notify: options.notify token: options.token hipchat.notify options.roomId, params, (success) -> grunt.log.writeln 'Notification sent!' done()
[ { "context": "oject_id, version, pathname} = req.params\n\t\t\tkey = \"#{project_id}:#{version}:#{pathname}\"\n\t\t\tif @oldFiles[key]?\n\t\t\t\tres.send @oldFiles[key]", "end": 1361, "score": 0.9993714094161987, "start": 1323, "tag": "KEY", "value": "\"#{project_id}:#{version}:#{pathname}\"...
test/acceptance/coffee/helpers/MockProjectHistoryApi.coffee
shyoshyo/web-sharelatex
1
_ = require 'lodash' express = require 'express' bodyParser = require "body-parser" app = express() {ObjectId} = require 'mongojs' module.exports = MockProjectHistoryApi = docs: {} oldFiles: {} projectVersions: {} labels: {} projectSnapshots: {} addOldFile: (project_id, version, pathname, content) -> @oldFiles["#{project_id}:#{version}:#{pathname}"] = content addProjectSnapshot: (project_id, version, snapshot) -> @projectSnapshots["#{project_id}:#{version}"] = snapshot setProjectVersion: (project_id, version) -> @projectVersions[project_id] = {version: version} setProjectVersionInfo: (project_id, versionInfo) -> @projectVersions[project_id] = versionInfo addLabel: (project_id, label) -> if !label.id? label.id = new ObjectId().toString() @labels[project_id] ?= {} @labels[project_id][label.id] = label deleteLabel: (project_id, label_id) -> delete @labels[project_id][label_id] getLabels: (project_id) -> return null unless @labels[project_id]? _.values @labels[project_id] reset: () -> @oldFiles = {} @projectVersions = {} @labels = {} run: () -> app.post "/project", (req, res, next) => res.json project: id: 1 app.get "/project/:project_id/version/:version/:pathname", (req, res, next) => {project_id, version, pathname} = req.params key = "#{project_id}:#{version}:#{pathname}" if @oldFiles[key]? res.send @oldFiles[key] else res.send 404 app.get "/project/:project_id/version/:version", (req, res, next) => {project_id, version} = req.params key = "#{project_id}:#{version}" if @projectSnapshots[key]? res.json @projectSnapshots[key] else res.sendStatus 404 app.get "/project/:project_id/version", (req, res, next) => {project_id} = req.params if @projectVersions[project_id]? res.json @projectVersions[project_id] else res.send 404 app.get "/project/:project_id/labels", (req, res, next) => {project_id} = req.params labels = @getLabels project_id if labels? res.json labels else res.send 404 app.post "/project/:project_id/user/:user_id/labels", bodyParser.json(), (req, res, next) => {project_id} = req.params {comment, version} = req.body label_id = new ObjectId().toString() @addLabel project_id, {id: label_id, comment, version} res.json {label_id, comment, version} app.delete "/project/:project_id/user/:user_id/labels/:label_id", (req, res, next) => {project_id, label_id} = req.params label = @labels[project_id]?[label_id] if label? @deleteLabel project_id, label_id res.send 204 else res.send 404 app.post "/project/:project_id/flush", (req, res, next) => res.sendStatus 200 app.listen 3054, (error) -> throw error if error? .on "error", (error) -> console.error "error starting MockProjectHistoryApi:", error.message process.exit(1) MockProjectHistoryApi.run()
71473
_ = require 'lodash' express = require 'express' bodyParser = require "body-parser" app = express() {ObjectId} = require 'mongojs' module.exports = MockProjectHistoryApi = docs: {} oldFiles: {} projectVersions: {} labels: {} projectSnapshots: {} addOldFile: (project_id, version, pathname, content) -> @oldFiles["#{project_id}:#{version}:#{pathname}"] = content addProjectSnapshot: (project_id, version, snapshot) -> @projectSnapshots["#{project_id}:#{version}"] = snapshot setProjectVersion: (project_id, version) -> @projectVersions[project_id] = {version: version} setProjectVersionInfo: (project_id, versionInfo) -> @projectVersions[project_id] = versionInfo addLabel: (project_id, label) -> if !label.id? label.id = new ObjectId().toString() @labels[project_id] ?= {} @labels[project_id][label.id] = label deleteLabel: (project_id, label_id) -> delete @labels[project_id][label_id] getLabels: (project_id) -> return null unless @labels[project_id]? _.values @labels[project_id] reset: () -> @oldFiles = {} @projectVersions = {} @labels = {} run: () -> app.post "/project", (req, res, next) => res.json project: id: 1 app.get "/project/:project_id/version/:version/:pathname", (req, res, next) => {project_id, version, pathname} = req.params key = <KEY> if @oldFiles[key]? res.send @oldFiles[key] else res.send 404 app.get "/project/:project_id/version/:version", (req, res, next) => {project_id, version} = req.params key = <KEY> if @projectSnapshots[key]? res.json @projectSnapshots[key] else res.sendStatus 404 app.get "/project/:project_id/version", (req, res, next) => {project_id} = req.params if @projectVersions[project_id]? res.json @projectVersions[project_id] else res.send 404 app.get "/project/:project_id/labels", (req, res, next) => {project_id} = req.params labels = @getLabels project_id if labels? res.json labels else res.send 404 app.post "/project/:project_id/user/:user_id/labels", bodyParser.json(), (req, res, next) => {project_id} = req.params {comment, version} = req.body label_id = new ObjectId().toString() @addLabel project_id, {id: label_id, comment, version} res.json {label_id, comment, version} app.delete "/project/:project_id/user/:user_id/labels/:label_id", (req, res, next) => {project_id, label_id} = req.params label = @labels[project_id]?[label_id] if label? @deleteLabel project_id, label_id res.send 204 else res.send 404 app.post "/project/:project_id/flush", (req, res, next) => res.sendStatus 200 app.listen 3054, (error) -> throw error if error? .on "error", (error) -> console.error "error starting MockProjectHistoryApi:", error.message process.exit(1) MockProjectHistoryApi.run()
true
_ = require 'lodash' express = require 'express' bodyParser = require "body-parser" app = express() {ObjectId} = require 'mongojs' module.exports = MockProjectHistoryApi = docs: {} oldFiles: {} projectVersions: {} labels: {} projectSnapshots: {} addOldFile: (project_id, version, pathname, content) -> @oldFiles["#{project_id}:#{version}:#{pathname}"] = content addProjectSnapshot: (project_id, version, snapshot) -> @projectSnapshots["#{project_id}:#{version}"] = snapshot setProjectVersion: (project_id, version) -> @projectVersions[project_id] = {version: version} setProjectVersionInfo: (project_id, versionInfo) -> @projectVersions[project_id] = versionInfo addLabel: (project_id, label) -> if !label.id? label.id = new ObjectId().toString() @labels[project_id] ?= {} @labels[project_id][label.id] = label deleteLabel: (project_id, label_id) -> delete @labels[project_id][label_id] getLabels: (project_id) -> return null unless @labels[project_id]? _.values @labels[project_id] reset: () -> @oldFiles = {} @projectVersions = {} @labels = {} run: () -> app.post "/project", (req, res, next) => res.json project: id: 1 app.get "/project/:project_id/version/:version/:pathname", (req, res, next) => {project_id, version, pathname} = req.params key = PI:KEY:<KEY>END_PI if @oldFiles[key]? res.send @oldFiles[key] else res.send 404 app.get "/project/:project_id/version/:version", (req, res, next) => {project_id, version} = req.params key = PI:KEY:<KEY>END_PI if @projectSnapshots[key]? res.json @projectSnapshots[key] else res.sendStatus 404 app.get "/project/:project_id/version", (req, res, next) => {project_id} = req.params if @projectVersions[project_id]? res.json @projectVersions[project_id] else res.send 404 app.get "/project/:project_id/labels", (req, res, next) => {project_id} = req.params labels = @getLabels project_id if labels? res.json labels else res.send 404 app.post "/project/:project_id/user/:user_id/labels", bodyParser.json(), (req, res, next) => {project_id} = req.params {comment, version} = req.body label_id = new ObjectId().toString() @addLabel project_id, {id: label_id, comment, version} res.json {label_id, comment, version} app.delete "/project/:project_id/user/:user_id/labels/:label_id", (req, res, next) => {project_id, label_id} = req.params label = @labels[project_id]?[label_id] if label? @deleteLabel project_id, label_id res.send 204 else res.send 404 app.post "/project/:project_id/flush", (req, res, next) => res.sendStatus 200 app.listen 3054, (error) -> throw error if error? .on "error", (error) -> console.error "error starting MockProjectHistoryApi:", error.message process.exit(1) MockProjectHistoryApi.run()
[ { "context": "# @author Gianluigi Mango\n# User API\nUserHandler = require './handler/userH", "end": 25, "score": 0.9998672604560852, "start": 10, "tag": "NAME", "value": "Gianluigi Mango" } ]
dev/server/api/userApi.coffee
knickatheart/mean-api
0
# @author Gianluigi Mango # User API UserHandler = require './handler/userHandler' module.exports = class UserApi constructor: (@action, @path, @req, @res) -> @userHandler = new UserHandler @req console.info '[Query]', action switch @action when 'getInfo' then @userHandler.getInfo @path, @res when 'addUser' then @userHandler.addUser @path, @res when 'deleteUser' then @userHandler.deleteUser @path, @res when 'login' then @userHandler.loginUser @path, @res when 'logout' then @userHandler.logout @path, @res when 'checkUser' then @userHandler.checkSession @req, @res else res.send Error: 'No method found'
22138
# @author <NAME> # User API UserHandler = require './handler/userHandler' module.exports = class UserApi constructor: (@action, @path, @req, @res) -> @userHandler = new UserHandler @req console.info '[Query]', action switch @action when 'getInfo' then @userHandler.getInfo @path, @res when 'addUser' then @userHandler.addUser @path, @res when 'deleteUser' then @userHandler.deleteUser @path, @res when 'login' then @userHandler.loginUser @path, @res when 'logout' then @userHandler.logout @path, @res when 'checkUser' then @userHandler.checkSession @req, @res else res.send Error: 'No method found'
true
# @author PI:NAME:<NAME>END_PI # User API UserHandler = require './handler/userHandler' module.exports = class UserApi constructor: (@action, @path, @req, @res) -> @userHandler = new UserHandler @req console.info '[Query]', action switch @action when 'getInfo' then @userHandler.getInfo @path, @res when 'addUser' then @userHandler.addUser @path, @res when 'deleteUser' then @userHandler.deleteUser @path, @res when 'login' then @userHandler.loginUser @path, @res when 'logout' then @userHandler.logout @path, @res when 'checkUser' then @userHandler.checkSession @req, @res else res.send Error: 'No method found'
[ { "context": "e key\n key = if base_key then (k) -> \"#{base_key}_#{k}\" else (k) -> k\n\n # First add primitive values\n", "end": 594, "score": 0.6759657263755798, "start": 592, "tag": "KEY", "value": "#{" } ]
coffee/json_connector/json_flattener.coffee
enterstudio/tableau-web-table-connector
59
_ = require 'underscore' class Table constructor: (@rows=[])-> add_row: (row_data)-> @rows.push row_data merge_table_pair = (t1, t2)-> a = t1.rows b = t2.rows o = new Table for a_row in a for b_row in b o.add_row _.extend({}, a_row, b_row) o merge_tables = (t1, tables...)-> return t1 if _.isEmpty(tables) return merge_table_pair(t1, tables[0]) if tables.length == 1 merge_table_pair(t1, merge_tables(tables...)) remap = (obj, base_key=null)-> base_row = {} # The function to retrieve the key key = if base_key then (k) -> "#{base_key}_#{k}" else (k) -> k # First add primitive values for k,v of obj if _.isString(v) or _.isNumber(v) base_row[key(k)] = v base_table = new Table([base_row]) children = [] choices = {} # For each attribute for k,v of obj switch # Add arrays as choices for the key # recursively when _.isArray(v) table_out = new Table for element in v for row in remap(element, key(k)).rows table_out.add_row(row) choices[k] = table_out # Add objects as extensions for their key # recursively when _.isObject(v) children.push remap(v, key(k)) # Merge the extensions to the base attributes after # all their children and choice tables are already extended base_out = merge_tables( base_table, children... ) # Then finally merge all the choices to the extended base table # ( so the attributes coming from the extensions are mapped across # all choices here) for k,v of choices base_out = merge_tables( base_out, v) base_out _.extend module.exports, remap: remap
33123
_ = require 'underscore' class Table constructor: (@rows=[])-> add_row: (row_data)-> @rows.push row_data merge_table_pair = (t1, t2)-> a = t1.rows b = t2.rows o = new Table for a_row in a for b_row in b o.add_row _.extend({}, a_row, b_row) o merge_tables = (t1, tables...)-> return t1 if _.isEmpty(tables) return merge_table_pair(t1, tables[0]) if tables.length == 1 merge_table_pair(t1, merge_tables(tables...)) remap = (obj, base_key=null)-> base_row = {} # The function to retrieve the key key = if base_key then (k) -> "#{base_key}_<KEY>k}" else (k) -> k # First add primitive values for k,v of obj if _.isString(v) or _.isNumber(v) base_row[key(k)] = v base_table = new Table([base_row]) children = [] choices = {} # For each attribute for k,v of obj switch # Add arrays as choices for the key # recursively when _.isArray(v) table_out = new Table for element in v for row in remap(element, key(k)).rows table_out.add_row(row) choices[k] = table_out # Add objects as extensions for their key # recursively when _.isObject(v) children.push remap(v, key(k)) # Merge the extensions to the base attributes after # all their children and choice tables are already extended base_out = merge_tables( base_table, children... ) # Then finally merge all the choices to the extended base table # ( so the attributes coming from the extensions are mapped across # all choices here) for k,v of choices base_out = merge_tables( base_out, v) base_out _.extend module.exports, remap: remap
true
_ = require 'underscore' class Table constructor: (@rows=[])-> add_row: (row_data)-> @rows.push row_data merge_table_pair = (t1, t2)-> a = t1.rows b = t2.rows o = new Table for a_row in a for b_row in b o.add_row _.extend({}, a_row, b_row) o merge_tables = (t1, tables...)-> return t1 if _.isEmpty(tables) return merge_table_pair(t1, tables[0]) if tables.length == 1 merge_table_pair(t1, merge_tables(tables...)) remap = (obj, base_key=null)-> base_row = {} # The function to retrieve the key key = if base_key then (k) -> "#{base_key}_PI:KEY:<KEY>END_PIk}" else (k) -> k # First add primitive values for k,v of obj if _.isString(v) or _.isNumber(v) base_row[key(k)] = v base_table = new Table([base_row]) children = [] choices = {} # For each attribute for k,v of obj switch # Add arrays as choices for the key # recursively when _.isArray(v) table_out = new Table for element in v for row in remap(element, key(k)).rows table_out.add_row(row) choices[k] = table_out # Add objects as extensions for their key # recursively when _.isObject(v) children.push remap(v, key(k)) # Merge the extensions to the base attributes after # all their children and choice tables are already extended base_out = merge_tables( base_table, children... ) # Then finally merge all the choices to the extended base table # ( so the attributes coming from the extensions are mapped across # all choices here) for k,v of choices base_out = merge_tables( base_out, v) base_out _.extend module.exports, remap: remap
[ { "context": "\n\n compJID = \"comp.exmaple.tld\"\n clientJID = \"client@exmaple.tld\"\n\n xmppComp =\n channels: {}\n send: (data) ", "end": 290, "score": 0.9997097253799438, "start": 272, "tag": "EMAIL", "value": "client@exmaple.tld" }, { "context": "x.Element \"iq\",\n ...
spec/Router.spec.coffee
flosse/node-xmpp-joap
0
Router = require "../src/Router" ltx = require "ltx" chai = require 'chai' expect = chai.expect { JID } = require "node-xmpp-core" JOAP_NS = "jabber:iq:joap" RPC_NS = "jabber:iq:rpc" describe "Router", -> compJID = "comp.exmaple.tld" clientJID = "client@exmaple.tld" xmppComp = channels: {} send: (data) -> process.nextTick -> xmppClient.onData data onData: (data) -> on: (channel, cb) -> @channels[channel] = cb connection: jid: new JID compJID xmppClient = send: (data) -> process.nextTick -> xmppComp.channels.stanza data onData: (data, cb) -> beforeEach -> @router = new Router xmppComp it "ignores stanzas that has an invalid 'from' attribute", (done) -> @request = new ltx.Element "iq", id:"invalid_req" to: "class@comp.example.tld" type:'set' @request.c "add", xmlns:JOAP_NS xmppComp.on "stanza", (data) -> done() xmppClient.send @request it "returns an err stanzas if 'to' attribute is invalid", (done) -> @request = new ltx.Element "iq", id:"invalid_req" from: "client@example.tld" type:'set' @request.c "add", xmlns:JOAP_NS xmppClient.onData = (data) -> errMsg = data.getChildText("error") (expect errMsg).to.eql "invalid 'to' attribute in IQ stanza" done() xmppClient.send @request it "supports custom joap actions", (done) -> @request = new ltx.Element "iq", id:"invalid_req" from: "client@example.tld" to: "class@comp.example.tld" type:'set' @request.c "foo", xmlns:JOAP_NS @router.on "foo", (action) => @router.sendResponse action, (new ltx.Element "customdata", myAttrs: "custom response") xmppClient.onData = (data) -> data = data.getChild("foo").getChild("customdata") (expect data.attrs.myAttrs).to.equal "custom response" done() xmppClient.send @request
169269
Router = require "../src/Router" ltx = require "ltx" chai = require 'chai' expect = chai.expect { JID } = require "node-xmpp-core" JOAP_NS = "jabber:iq:joap" RPC_NS = "jabber:iq:rpc" describe "Router", -> compJID = "comp.exmaple.tld" clientJID = "<EMAIL>" xmppComp = channels: {} send: (data) -> process.nextTick -> xmppClient.onData data onData: (data) -> on: (channel, cb) -> @channels[channel] = cb connection: jid: new JID compJID xmppClient = send: (data) -> process.nextTick -> xmppComp.channels.stanza data onData: (data, cb) -> beforeEach -> @router = new Router xmppComp it "ignores stanzas that has an invalid 'from' attribute", (done) -> @request = new ltx.Element "iq", id:"invalid_req" to: "<EMAIL>" type:'set' @request.c "add", xmlns:JOAP_NS xmppComp.on "stanza", (data) -> done() xmppClient.send @request it "returns an err stanzas if 'to' attribute is invalid", (done) -> @request = new ltx.Element "iq", id:"invalid_req" from: "<EMAIL>" type:'set' @request.c "add", xmlns:JOAP_NS xmppClient.onData = (data) -> errMsg = data.getChildText("error") (expect errMsg).to.eql "invalid 'to' attribute in IQ stanza" done() xmppClient.send @request it "supports custom joap actions", (done) -> @request = new ltx.Element "iq", id:"invalid_req" from: "<EMAIL>" to: "<EMAIL>" type:'set' @request.c "foo", xmlns:JOAP_NS @router.on "foo", (action) => @router.sendResponse action, (new ltx.Element "customdata", myAttrs: "custom response") xmppClient.onData = (data) -> data = data.getChild("foo").getChild("customdata") (expect data.attrs.myAttrs).to.equal "custom response" done() xmppClient.send @request
true
Router = require "../src/Router" ltx = require "ltx" chai = require 'chai' expect = chai.expect { JID } = require "node-xmpp-core" JOAP_NS = "jabber:iq:joap" RPC_NS = "jabber:iq:rpc" describe "Router", -> compJID = "comp.exmaple.tld" clientJID = "PI:EMAIL:<EMAIL>END_PI" xmppComp = channels: {} send: (data) -> process.nextTick -> xmppClient.onData data onData: (data) -> on: (channel, cb) -> @channels[channel] = cb connection: jid: new JID compJID xmppClient = send: (data) -> process.nextTick -> xmppComp.channels.stanza data onData: (data, cb) -> beforeEach -> @router = new Router xmppComp it "ignores stanzas that has an invalid 'from' attribute", (done) -> @request = new ltx.Element "iq", id:"invalid_req" to: "PI:EMAIL:<EMAIL>END_PI" type:'set' @request.c "add", xmlns:JOAP_NS xmppComp.on "stanza", (data) -> done() xmppClient.send @request it "returns an err stanzas if 'to' attribute is invalid", (done) -> @request = new ltx.Element "iq", id:"invalid_req" from: "PI:EMAIL:<EMAIL>END_PI" type:'set' @request.c "add", xmlns:JOAP_NS xmppClient.onData = (data) -> errMsg = data.getChildText("error") (expect errMsg).to.eql "invalid 'to' attribute in IQ stanza" done() xmppClient.send @request it "supports custom joap actions", (done) -> @request = new ltx.Element "iq", id:"invalid_req" from: "PI:EMAIL:<EMAIL>END_PI" to: "PI:EMAIL:<EMAIL>END_PI" type:'set' @request.c "foo", xmlns:JOAP_NS @router.on "foo", (action) => @router.sendResponse action, (new ltx.Element "customdata", myAttrs: "custom response") xmppClient.onData = (data) -> data = data.getChild("foo").getChild("customdata") (expect data.attrs.myAttrs).to.equal "custom response" done() xmppClient.send @request
[ { "context": "onParam.mold), [\n# {\n# name: 'name2'\n# $index: 0\n# $isNew: true\n# ", "end": 3650, "score": 0.6798576712608337, "start": 3649, "tag": "NAME", "value": "2" }, { "context": " this.collectionParam.child(1).setMold('name', 'new name'...
test/skipped/integration.spec.coffee
ipkozyrin/mold
0
mold = require('../../src/index').default describe.skip 'Integration.', -> describe 'documentsCollection => nested document.', -> beforeEach () -> testSchema = () -> documentsCollection: type: 'documentsCollection' item: type: 'document' schema: id: {type: 'number', primary: true} # TODO: use pouch this.testSchema = testSchema() this.mold = mold( {silent: true}, this.testSchema ) _.set(this.mold.driverManager.$defaultMemoryDb, 'documentsCollection', [ {id: 0} ]) this.document = this.mold.child('documentsCollection[0]') it 'document empty instance', -> assert.equal(this.document.root, 'documentsCollection[0]') assert.equal(this.document._schemaPath, 'documentsCollection.item') assert.equal(this.document._storagePath, 'documentsCollection.documents[0]') assert.deepEqual(this.document.mold, {}) it 'load - check responce', (done) -> promise = this.document.load() expect(Promise.all([ expect(promise).to.eventually.property('body').deep.equal({id: 0}), expect(promise).to.eventually.property('request').deep.equal({ method: 'get', moldPath: 'documentsCollection[0]', url: 'documentsCollection/0', }), ])).to.eventually.notify(done) it 'load - check mold of document', (done) -> expect(this.document.load()).to.eventually.notify => expect(Promise.resolve(this.document.mold)).to.eventually .deep.equal({ $loading: false id: 0 }) .notify(done) it 'load - check storage', (done) -> expect(this.document.load()).to.eventually.notify => expect(Promise.resolve(this.document._main.$getWholeStorageState())).to.eventually .deep.equal({ documentsCollection: { action: load: [], state: {loading: []}, documents: { '0': { $loading: false id: 0 } } } }) .notify(done) describe 'set schema to specific mount point', -> beforeEach () -> testSchemaRoot = () -> container: type: 'container' schema: paramOfRootContainer: {type: 'string'} testSchemaChild = () -> type: 'container' schema: paramOfChildContainer: {type: 'string'} @testSchemaRoot = testSchemaRoot() @testSchemaChild = testSchemaChild() @mold = mold( {silent: true}, @testSchemaRoot ) it 'set schema', -> @mold.setNode('container.childContainer', @testSchemaChild) expect(@mold.schemaManager.getFullSchema()).to.be.deep.equal { container: { type: 'container' schema: { paramOfRootContainer: {type: 'string'} childContainer: { type: 'container' schema: { paramOfChildContainer: {type: 'string'} } } } } } ######################################## # describe 'complex collection', -> # beforeEach () -> # this.mold = mold( {}, testSchema() ) # this.collectionParam = this.mold.instance('inMemory.collectionParam') # # it 'Many manupulations with collection', (done) -> # this.collectionParam.unshift({name: 'name0'}) # this.collectionParam.unshift({name: 'name1'}) # this.collectionParam.unshift({name: 'name2'}) # # assert.deepEqual _.compact(this.collectionParam.mold), [ # { # name: 'name2' # $index: 0 # $isNew: true # } # { # name: 'name1' # $index: 1 # $isNew: true # } # { # name: 'name0' # $index: 2 # $isNew: true # } # ] # # this.collectionParam.removeMold(this.collectionParam.mold[1]) # this.collectionParam.child(1).setMold('name', 'new name') # assert.deepEqual _.compact(this.collectionParam.mold), [ # { # name: 'name2' # $index: 0 # $isNew: true # } # { # name: 'new name' # $index: 1 # $isNew: true # } # ] # # expect(this.collectionParam.save()).to.eventually.notify => # expect(Promise.resolve(this.collectionParam.mold)).to.eventually # .deep.equal([ # { # id: 0 # name: 'name2' # $index: 0 # } # { # id: 1 # name: 'new name' # $index: 1 # } # ]) # .notify(done) # # # TODO: проверить - удаленный элемент не должен сохраняться, так как он новосозданный
128314
mold = require('../../src/index').default describe.skip 'Integration.', -> describe 'documentsCollection => nested document.', -> beforeEach () -> testSchema = () -> documentsCollection: type: 'documentsCollection' item: type: 'document' schema: id: {type: 'number', primary: true} # TODO: use pouch this.testSchema = testSchema() this.mold = mold( {silent: true}, this.testSchema ) _.set(this.mold.driverManager.$defaultMemoryDb, 'documentsCollection', [ {id: 0} ]) this.document = this.mold.child('documentsCollection[0]') it 'document empty instance', -> assert.equal(this.document.root, 'documentsCollection[0]') assert.equal(this.document._schemaPath, 'documentsCollection.item') assert.equal(this.document._storagePath, 'documentsCollection.documents[0]') assert.deepEqual(this.document.mold, {}) it 'load - check responce', (done) -> promise = this.document.load() expect(Promise.all([ expect(promise).to.eventually.property('body').deep.equal({id: 0}), expect(promise).to.eventually.property('request').deep.equal({ method: 'get', moldPath: 'documentsCollection[0]', url: 'documentsCollection/0', }), ])).to.eventually.notify(done) it 'load - check mold of document', (done) -> expect(this.document.load()).to.eventually.notify => expect(Promise.resolve(this.document.mold)).to.eventually .deep.equal({ $loading: false id: 0 }) .notify(done) it 'load - check storage', (done) -> expect(this.document.load()).to.eventually.notify => expect(Promise.resolve(this.document._main.$getWholeStorageState())).to.eventually .deep.equal({ documentsCollection: { action: load: [], state: {loading: []}, documents: { '0': { $loading: false id: 0 } } } }) .notify(done) describe 'set schema to specific mount point', -> beforeEach () -> testSchemaRoot = () -> container: type: 'container' schema: paramOfRootContainer: {type: 'string'} testSchemaChild = () -> type: 'container' schema: paramOfChildContainer: {type: 'string'} @testSchemaRoot = testSchemaRoot() @testSchemaChild = testSchemaChild() @mold = mold( {silent: true}, @testSchemaRoot ) it 'set schema', -> @mold.setNode('container.childContainer', @testSchemaChild) expect(@mold.schemaManager.getFullSchema()).to.be.deep.equal { container: { type: 'container' schema: { paramOfRootContainer: {type: 'string'} childContainer: { type: 'container' schema: { paramOfChildContainer: {type: 'string'} } } } } } ######################################## # describe 'complex collection', -> # beforeEach () -> # this.mold = mold( {}, testSchema() ) # this.collectionParam = this.mold.instance('inMemory.collectionParam') # # it 'Many manupulations with collection', (done) -> # this.collectionParam.unshift({name: 'name0'}) # this.collectionParam.unshift({name: 'name1'}) # this.collectionParam.unshift({name: 'name2'}) # # assert.deepEqual _.compact(this.collectionParam.mold), [ # { # name: 'name<NAME>' # $index: 0 # $isNew: true # } # { # name: 'name1' # $index: 1 # $isNew: true # } # { # name: 'name0' # $index: 2 # $isNew: true # } # ] # # this.collectionParam.removeMold(this.collectionParam.mold[1]) # this.collectionParam.child(1).setMold('name', '<NAME>') # assert.deepEqual _.compact(this.collectionParam.mold), [ # { # name: '<NAME>' # $index: 0 # $isNew: true # } # { # name: '<NAME>' # $index: 1 # $isNew: true # } # ] # # expect(this.collectionParam.save()).to.eventually.notify => # expect(Promise.resolve(this.collectionParam.mold)).to.eventually # .deep.equal([ # { # id: 0 # name: '<NAME>' # $index: 0 # } # { # id: 1 # name: '<NAME>' # $index: 1 # } # ]) # .notify(done) # # # TODO: проверить - удаленный элемент не должен сохраняться, так как он новосозданный
true
mold = require('../../src/index').default describe.skip 'Integration.', -> describe 'documentsCollection => nested document.', -> beforeEach () -> testSchema = () -> documentsCollection: type: 'documentsCollection' item: type: 'document' schema: id: {type: 'number', primary: true} # TODO: use pouch this.testSchema = testSchema() this.mold = mold( {silent: true}, this.testSchema ) _.set(this.mold.driverManager.$defaultMemoryDb, 'documentsCollection', [ {id: 0} ]) this.document = this.mold.child('documentsCollection[0]') it 'document empty instance', -> assert.equal(this.document.root, 'documentsCollection[0]') assert.equal(this.document._schemaPath, 'documentsCollection.item') assert.equal(this.document._storagePath, 'documentsCollection.documents[0]') assert.deepEqual(this.document.mold, {}) it 'load - check responce', (done) -> promise = this.document.load() expect(Promise.all([ expect(promise).to.eventually.property('body').deep.equal({id: 0}), expect(promise).to.eventually.property('request').deep.equal({ method: 'get', moldPath: 'documentsCollection[0]', url: 'documentsCollection/0', }), ])).to.eventually.notify(done) it 'load - check mold of document', (done) -> expect(this.document.load()).to.eventually.notify => expect(Promise.resolve(this.document.mold)).to.eventually .deep.equal({ $loading: false id: 0 }) .notify(done) it 'load - check storage', (done) -> expect(this.document.load()).to.eventually.notify => expect(Promise.resolve(this.document._main.$getWholeStorageState())).to.eventually .deep.equal({ documentsCollection: { action: load: [], state: {loading: []}, documents: { '0': { $loading: false id: 0 } } } }) .notify(done) describe 'set schema to specific mount point', -> beforeEach () -> testSchemaRoot = () -> container: type: 'container' schema: paramOfRootContainer: {type: 'string'} testSchemaChild = () -> type: 'container' schema: paramOfChildContainer: {type: 'string'} @testSchemaRoot = testSchemaRoot() @testSchemaChild = testSchemaChild() @mold = mold( {silent: true}, @testSchemaRoot ) it 'set schema', -> @mold.setNode('container.childContainer', @testSchemaChild) expect(@mold.schemaManager.getFullSchema()).to.be.deep.equal { container: { type: 'container' schema: { paramOfRootContainer: {type: 'string'} childContainer: { type: 'container' schema: { paramOfChildContainer: {type: 'string'} } } } } } ######################################## # describe 'complex collection', -> # beforeEach () -> # this.mold = mold( {}, testSchema() ) # this.collectionParam = this.mold.instance('inMemory.collectionParam') # # it 'Many manupulations with collection', (done) -> # this.collectionParam.unshift({name: 'name0'}) # this.collectionParam.unshift({name: 'name1'}) # this.collectionParam.unshift({name: 'name2'}) # # assert.deepEqual _.compact(this.collectionParam.mold), [ # { # name: 'namePI:NAME:<NAME>END_PI' # $index: 0 # $isNew: true # } # { # name: 'name1' # $index: 1 # $isNew: true # } # { # name: 'name0' # $index: 2 # $isNew: true # } # ] # # this.collectionParam.removeMold(this.collectionParam.mold[1]) # this.collectionParam.child(1).setMold('name', 'PI:NAME:<NAME>END_PI') # assert.deepEqual _.compact(this.collectionParam.mold), [ # { # name: 'PI:NAME:<NAME>END_PI' # $index: 0 # $isNew: true # } # { # name: 'PI:NAME:<NAME>END_PI' # $index: 1 # $isNew: true # } # ] # # expect(this.collectionParam.save()).to.eventually.notify => # expect(Promise.resolve(this.collectionParam.mold)).to.eventually # .deep.equal([ # { # id: 0 # name: 'PI:NAME:<NAME>END_PI' # $index: 0 # } # { # id: 1 # name: 'PI:NAME:<NAME>END_PI' # $index: 1 # } # ]) # .notify(done) # # # TODO: проверить - удаленный элемент не должен сохраняться, так как он новосозданный
[ { "context": "id\n\t\t\tfields = [{\n\t\t\t\t\ttype: 'String',\n\t\t\t\t\tname:'name',\n\t\t\t\t\twidth: 60,\n\t\t\t\t\ttitle: TAPi18n.__('space_u", "end": 1412, "score": 0.8797792196273804, "start": 1408, "tag": "NAME", "value": "name" }, { "context": "join(\",\")\n\t\t\t\t},{\n\t\t...
creator/packages/steedos-users-import/routes/api_space_users_export.coffee
yicone/steedos-platform
42
Meteor.startup -> WebApp.connectHandlers.use "/api/export/space_users", (req, res, next)-> try current_user_info = uuflowManager.check_authorization(req) query = req.query space_id = query.space_id org_id = query.org_id user_id = query['X-User-Id'] org = db.organizations.findOne({_id:org_id},{fields:{fullname:1}}) users_to_xls = new Array now = new Date if Steedos.isSpaceAdmin(space_id,user_id) users_to_xls = db.space_users.find({ space: space_id }, { sort: {name: 1} }).fetch() else org_ids = [] org_objs = db.organizations.find({_id:org_id,space:space_id},{fields:{_id:1,children:1}}).fetch() org_ids = _.pluck(org_objs,'_id') _.each org_objs,(org_obj)-> org_ids = _.union(org_ids,org_obj?.children) _.uniq(org_ids) users_to_xls = db.space_users.find({space:space_id,organizations:{$in:org_ids}},{sort: {sort_no: -1,name:1}}).fetch() ejs = require('ejs') str = Assets.getText('server/ejs/export_space_users.ejs') # 检测是否有语法错误 ejsLint = require('ejs-lint') error_obj = ejsLint.lint(str, {}) if error_obj console.error "===/api/contacts/export/space_users:" console.error error_obj template = ejs.compile(str) lang = 'en' if current_user_info.locale is 'zh-cn' lang = 'zh-CN' orgName = if org then org.fullname else org_id fields = [{ type: 'String', name:'name', width: 60, title: TAPi18n.__('space_users_name',{},lang) },{ type: 'String', name:'mobile', width: 100, title: TAPi18n.__('space_users_mobile',{},lang) },{ type: 'String', name:'work_phone', width: 100, title: TAPi18n.__('space_users_work_phone',{},lang) },{ type: 'String', name:'email', width: 100, title: TAPi18n.__('space_users_email',{},lang) },{ type: 'String', name:'company', width: 100, title: TAPi18n.__('space_users_company',{},lang) },{ type: 'String', name:'position', width: 100, title: TAPi18n.__('space_users_position',{},lang) },{ type: 'String', name:'organizations', width: 600, title: TAPi18n.__('space_users_organizations',{},lang), transform: (value)-> orgNames = db.organizations.find({_id: {$in: value}},{fields: {fullname: 1}}).map((item,index)-> return item.fullname ) return orgNames.join(",") },{ type: 'String', name:'manager', width: 60, title: TAPi18n.__('space_users_manager',{},lang) transform: (value)-> user = db.users.findOne({_id: value},{fields: {name: 1}}) return user?.name },{ type: 'String', name:'user', width: 60, title: TAPi18n.__('users_username',{},lang) transform: (value)-> user = db.users.findOne({_id: value},{fields: {username: 1}}) return user?.username },{ type: 'Number', name:'sort_no', width: 35, title: TAPi18n.__('space_users_sort_no',{},lang) },{ type: 'String', name:'user_accepted', width: 35, title: TAPi18n.__('space_users_user_accepted',{},lang) transform: (value)-> return if value then TAPi18n.__('space_users_user_accepted_yes',{},lang) else TAPi18n.__('space_users_user_accepted_no',{},lang) }] sheet_name = orgName?.replace(/\//g,"-") #不支持"/"符号 ret = template({ lang: lang, sheet_name: sheet_name, fields: fields, users_to_xls: users_to_xls }) fileName = "SteedOSContacts_" + moment().format('YYYYMMDDHHmm') + ".xls" res.setHeader("Content-type", "application/octet-stream") res.setHeader("Content-Disposition", "attachment;filename="+encodeURI(fileName)) res.end(ret) catch e console.error e.stack res.end(e.message)
184032
Meteor.startup -> WebApp.connectHandlers.use "/api/export/space_users", (req, res, next)-> try current_user_info = uuflowManager.check_authorization(req) query = req.query space_id = query.space_id org_id = query.org_id user_id = query['X-User-Id'] org = db.organizations.findOne({_id:org_id},{fields:{fullname:1}}) users_to_xls = new Array now = new Date if Steedos.isSpaceAdmin(space_id,user_id) users_to_xls = db.space_users.find({ space: space_id }, { sort: {name: 1} }).fetch() else org_ids = [] org_objs = db.organizations.find({_id:org_id,space:space_id},{fields:{_id:1,children:1}}).fetch() org_ids = _.pluck(org_objs,'_id') _.each org_objs,(org_obj)-> org_ids = _.union(org_ids,org_obj?.children) _.uniq(org_ids) users_to_xls = db.space_users.find({space:space_id,organizations:{$in:org_ids}},{sort: {sort_no: -1,name:1}}).fetch() ejs = require('ejs') str = Assets.getText('server/ejs/export_space_users.ejs') # 检测是否有语法错误 ejsLint = require('ejs-lint') error_obj = ejsLint.lint(str, {}) if error_obj console.error "===/api/contacts/export/space_users:" console.error error_obj template = ejs.compile(str) lang = 'en' if current_user_info.locale is 'zh-cn' lang = 'zh-CN' orgName = if org then org.fullname else org_id fields = [{ type: 'String', name:'<NAME>', width: 60, title: TAPi18n.__('space_users_name',{},lang) },{ type: 'String', name:'mobile', width: 100, title: TAPi18n.__('space_users_mobile',{},lang) },{ type: 'String', name:'work_phone', width: 100, title: TAPi18n.__('space_users_work_phone',{},lang) },{ type: 'String', name:'email', width: 100, title: TAPi18n.__('space_users_email',{},lang) },{ type: 'String', name:'company', width: 100, title: TAPi18n.__('space_users_company',{},lang) },{ type: 'String', name:'position', width: 100, title: TAPi18n.__('space_users_position',{},lang) },{ type: 'String', name:'organizations', width: 600, title: TAPi18n.__('space_users_organizations',{},lang), transform: (value)-> orgNames = db.organizations.find({_id: {$in: value}},{fields: {fullname: 1}}).map((item,index)-> return item.fullname ) return orgNames.join(",") },{ type: 'String', name:'<NAME>', width: 60, title: TAPi18n.__('space_users_manager',{},lang) transform: (value)-> user = db.users.findOne({_id: value},{fields: {name: 1}}) return user?.name },{ type: 'String', name:'<NAME>', width: 60, title: TAPi18n.__('users_username',{},lang) transform: (value)-> user = db.users.findOne({_id: value},{fields: {username: 1}}) return user?.username },{ type: 'Number', name:'sort_no', width: 35, title: TAPi18n.__('space_users_sort_no',{},lang) },{ type: 'String', name:'user_accepted', width: 35, title: TAPi18n.__('space_users_user_accepted',{},lang) transform: (value)-> return if value then TAPi18n.__('space_users_user_accepted_yes',{},lang) else TAPi18n.__('space_users_user_accepted_no',{},lang) }] sheet_name = orgName?.replace(/\//g,"-") #不支持"/"符号 ret = template({ lang: lang, sheet_name: sheet_name, fields: fields, users_to_xls: users_to_xls }) fileName = "SteedOSContacts_" + moment().format('YYYYMMDDHHmm') + ".xls" res.setHeader("Content-type", "application/octet-stream") res.setHeader("Content-Disposition", "attachment;filename="+encodeURI(fileName)) res.end(ret) catch e console.error e.stack res.end(e.message)
true
Meteor.startup -> WebApp.connectHandlers.use "/api/export/space_users", (req, res, next)-> try current_user_info = uuflowManager.check_authorization(req) query = req.query space_id = query.space_id org_id = query.org_id user_id = query['X-User-Id'] org = db.organizations.findOne({_id:org_id},{fields:{fullname:1}}) users_to_xls = new Array now = new Date if Steedos.isSpaceAdmin(space_id,user_id) users_to_xls = db.space_users.find({ space: space_id }, { sort: {name: 1} }).fetch() else org_ids = [] org_objs = db.organizations.find({_id:org_id,space:space_id},{fields:{_id:1,children:1}}).fetch() org_ids = _.pluck(org_objs,'_id') _.each org_objs,(org_obj)-> org_ids = _.union(org_ids,org_obj?.children) _.uniq(org_ids) users_to_xls = db.space_users.find({space:space_id,organizations:{$in:org_ids}},{sort: {sort_no: -1,name:1}}).fetch() ejs = require('ejs') str = Assets.getText('server/ejs/export_space_users.ejs') # 检测是否有语法错误 ejsLint = require('ejs-lint') error_obj = ejsLint.lint(str, {}) if error_obj console.error "===/api/contacts/export/space_users:" console.error error_obj template = ejs.compile(str) lang = 'en' if current_user_info.locale is 'zh-cn' lang = 'zh-CN' orgName = if org then org.fullname else org_id fields = [{ type: 'String', name:'PI:NAME:<NAME>END_PI', width: 60, title: TAPi18n.__('space_users_name',{},lang) },{ type: 'String', name:'mobile', width: 100, title: TAPi18n.__('space_users_mobile',{},lang) },{ type: 'String', name:'work_phone', width: 100, title: TAPi18n.__('space_users_work_phone',{},lang) },{ type: 'String', name:'email', width: 100, title: TAPi18n.__('space_users_email',{},lang) },{ type: 'String', name:'company', width: 100, title: TAPi18n.__('space_users_company',{},lang) },{ type: 'String', name:'position', width: 100, title: TAPi18n.__('space_users_position',{},lang) },{ type: 'String', name:'organizations', width: 600, title: TAPi18n.__('space_users_organizations',{},lang), transform: (value)-> orgNames = db.organizations.find({_id: {$in: value}},{fields: {fullname: 1}}).map((item,index)-> return item.fullname ) return orgNames.join(",") },{ type: 'String', name:'PI:NAME:<NAME>END_PI', width: 60, title: TAPi18n.__('space_users_manager',{},lang) transform: (value)-> user = db.users.findOne({_id: value},{fields: {name: 1}}) return user?.name },{ type: 'String', name:'PI:NAME:<NAME>END_PI', width: 60, title: TAPi18n.__('users_username',{},lang) transform: (value)-> user = db.users.findOne({_id: value},{fields: {username: 1}}) return user?.username },{ type: 'Number', name:'sort_no', width: 35, title: TAPi18n.__('space_users_sort_no',{},lang) },{ type: 'String', name:'user_accepted', width: 35, title: TAPi18n.__('space_users_user_accepted',{},lang) transform: (value)-> return if value then TAPi18n.__('space_users_user_accepted_yes',{},lang) else TAPi18n.__('space_users_user_accepted_no',{},lang) }] sheet_name = orgName?.replace(/\//g,"-") #不支持"/"符号 ret = template({ lang: lang, sheet_name: sheet_name, fields: fields, users_to_xls: users_to_xls }) fileName = "SteedOSContacts_" + moment().format('YYYYMMDDHHmm') + ".xls" res.setHeader("Content-type", "application/octet-stream") res.setHeader("Content-Disposition", "attachment;filename="+encodeURI(fileName)) res.end(ret) catch e console.error e.stack res.end(e.message)
[ { "context": "# Copyright (c) 2013, 2014, 2015 Michele Bini\n\ntest \"Verify catching impure reflective function", "end": 45, "score": 0.9998421669006348, "start": 33, "tag": "NAME", "value": "Michele Bini" } ]
test/reflection.coffee
rev22/reflective-coffeescript
0
# Copyright (c) 2013, 2014, 2015 Michele Bini test "Verify catching impure reflective functions", -> CoffeeScript.compile "@>@foo" CoffeeScript.compile "->foo" ok do (caught = false)-> try CoffeeScript.compile "@>foo" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>->foo" catch caught = true caught CoffeeScript.compile "@>@foo.x" CoffeeScript.compile "->foo.x" ok do (caught = false)-> try CoffeeScript.compile "@>foo.x" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>->foo.x" catch caught = true caught CoffeeScript.compile "@>@foo()" CoffeeScript.compile "->foo()" ok do (caught = false)-> try CoffeeScript.compile "@>foo()" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>->foo()" catch caught = true caught CoffeeScript.compile "@>{@foo}" CoffeeScript.compile "->{foo}" ok do (caught = false)-> try CoffeeScript.compile "@>{foo}" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>->{foo}" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@> -> { foo }" catch caught = true caught CoffeeScript.compile "@>{a:@foo}" CoffeeScript.compile "->{a:foo}" ok do (caught = false)-> try CoffeeScript.compile "@>{ a: foo }" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> { a: foo } " catch caught = true caught CoffeeScript.compile "@>a:@foo" CoffeeScript.compile "->a:foo" ok do (caught = false)-> try CoffeeScript.compile "@>a:foo" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> a: foo" catch caught = true caught CoffeeScript.compile "@>@x a:@foo" CoffeeScript.compile "->x a:foo" ok do (caught = false)-> try CoffeeScript.compile "@>@x a:foo" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x a: foo" catch caught = true caught CoffeeScript.compile "@>@x @z, a:@foo" CoffeeScript.compile "->x z, a:foo" ok do (caught = false)-> try CoffeeScript.compile "@>@x @z, a:foo" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x @z, a: foo" catch caught = true caught CoffeeScript.compile "@>@x(@z, a:@foo)" CoffeeScript.compile "->x( z, a:foo )" ok do (caught = false)-> try CoffeeScript.compile "@>@x(@z,a:foo)" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x( @z, a: foo )" catch caught = true caught CoffeeScript.compile "@>@x(@z,{a:@foo})" CoffeeScript.compile "->x( z, { a:foo } )" ok do (caught = false)-> try CoffeeScript.compile "@>@x(@z,{a:foo})" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x( @z, { a: foo } )" catch caught = true caught CoffeeScript.compile "@>@x @z,{a:@foo}" CoffeeScript.compile "->x z, { a:foo }" ok do (caught = false)-> try CoffeeScript.compile "@>@x @z,{a:foo}" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x @z, { a: foo }" catch caught = true caught test "Verify reflective functions source", -> ok ((@>).coffee is "@>") ok ((()@>@).coffee is "()@>@") ok (((x)@>x).coffee is "(x)@>x") foo = @> @console.log "hello" fooString = "@>\n @console.log \"hello\"\n " ok (foo.coffee is fooString) test "Declaration of variables in 'while' statements", -> ok do-> try c = CoffeeScript.compile """ @> while (x = @foo())? @foo(x) """ catch error c = false !!c test "Verify globals marked with @@", -> CoffeeScript.compile "@>@@Math" CoffeeScript.compile "->Math" CoffeeScript.compile "->@@Math" ok do (caught = false)-> try CoffeeScript.compile "@>Math" catch caught = true caught
103773
# Copyright (c) 2013, 2014, 2015 <NAME> test "Verify catching impure reflective functions", -> CoffeeScript.compile "@>@foo" CoffeeScript.compile "->foo" ok do (caught = false)-> try CoffeeScript.compile "@>foo" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>->foo" catch caught = true caught CoffeeScript.compile "@>@foo.x" CoffeeScript.compile "->foo.x" ok do (caught = false)-> try CoffeeScript.compile "@>foo.x" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>->foo.x" catch caught = true caught CoffeeScript.compile "@>@foo()" CoffeeScript.compile "->foo()" ok do (caught = false)-> try CoffeeScript.compile "@>foo()" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>->foo()" catch caught = true caught CoffeeScript.compile "@>{@foo}" CoffeeScript.compile "->{foo}" ok do (caught = false)-> try CoffeeScript.compile "@>{foo}" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>->{foo}" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@> -> { foo }" catch caught = true caught CoffeeScript.compile "@>{a:@foo}" CoffeeScript.compile "->{a:foo}" ok do (caught = false)-> try CoffeeScript.compile "@>{ a: foo }" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> { a: foo } " catch caught = true caught CoffeeScript.compile "@>a:@foo" CoffeeScript.compile "->a:foo" ok do (caught = false)-> try CoffeeScript.compile "@>a:foo" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> a: foo" catch caught = true caught CoffeeScript.compile "@>@x a:@foo" CoffeeScript.compile "->x a:foo" ok do (caught = false)-> try CoffeeScript.compile "@>@x a:foo" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x a: foo" catch caught = true caught CoffeeScript.compile "@>@x @z, a:@foo" CoffeeScript.compile "->x z, a:foo" ok do (caught = false)-> try CoffeeScript.compile "@>@x @z, a:foo" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x @z, a: foo" catch caught = true caught CoffeeScript.compile "@>@x(@z, a:@foo)" CoffeeScript.compile "->x( z, a:foo )" ok do (caught = false)-> try CoffeeScript.compile "@>@x(@z,a:foo)" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x( @z, a: foo )" catch caught = true caught CoffeeScript.compile "@>@x(@z,{a:@foo})" CoffeeScript.compile "->x( z, { a:foo } )" ok do (caught = false)-> try CoffeeScript.compile "@>@x(@z,{a:foo})" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x( @z, { a: foo } )" catch caught = true caught CoffeeScript.compile "@>@x @z,{a:@foo}" CoffeeScript.compile "->x z, { a:foo }" ok do (caught = false)-> try CoffeeScript.compile "@>@x @z,{a:foo}" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x @z, { a: foo }" catch caught = true caught test "Verify reflective functions source", -> ok ((@>).coffee is "@>") ok ((()@>@).coffee is "()@>@") ok (((x)@>x).coffee is "(x)@>x") foo = @> @console.log "hello" fooString = "@>\n @console.log \"hello\"\n " ok (foo.coffee is fooString) test "Declaration of variables in 'while' statements", -> ok do-> try c = CoffeeScript.compile """ @> while (x = @foo())? @foo(x) """ catch error c = false !!c test "Verify globals marked with @@", -> CoffeeScript.compile "@>@@Math" CoffeeScript.compile "->Math" CoffeeScript.compile "->@@Math" ok do (caught = false)-> try CoffeeScript.compile "@>Math" catch caught = true caught
true
# Copyright (c) 2013, 2014, 2015 PI:NAME:<NAME>END_PI test "Verify catching impure reflective functions", -> CoffeeScript.compile "@>@foo" CoffeeScript.compile "->foo" ok do (caught = false)-> try CoffeeScript.compile "@>foo" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>->foo" catch caught = true caught CoffeeScript.compile "@>@foo.x" CoffeeScript.compile "->foo.x" ok do (caught = false)-> try CoffeeScript.compile "@>foo.x" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>->foo.x" catch caught = true caught CoffeeScript.compile "@>@foo()" CoffeeScript.compile "->foo()" ok do (caught = false)-> try CoffeeScript.compile "@>foo()" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>->foo()" catch caught = true caught CoffeeScript.compile "@>{@foo}" CoffeeScript.compile "->{foo}" ok do (caught = false)-> try CoffeeScript.compile "@>{foo}" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>->{foo}" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@> -> { foo }" catch caught = true caught CoffeeScript.compile "@>{a:@foo}" CoffeeScript.compile "->{a:foo}" ok do (caught = false)-> try CoffeeScript.compile "@>{ a: foo }" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> { a: foo } " catch caught = true caught CoffeeScript.compile "@>a:@foo" CoffeeScript.compile "->a:foo" ok do (caught = false)-> try CoffeeScript.compile "@>a:foo" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> a: foo" catch caught = true caught CoffeeScript.compile "@>@x a:@foo" CoffeeScript.compile "->x a:foo" ok do (caught = false)-> try CoffeeScript.compile "@>@x a:foo" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x a: foo" catch caught = true caught CoffeeScript.compile "@>@x @z, a:@foo" CoffeeScript.compile "->x z, a:foo" ok do (caught = false)-> try CoffeeScript.compile "@>@x @z, a:foo" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x @z, a: foo" catch caught = true caught CoffeeScript.compile "@>@x(@z, a:@foo)" CoffeeScript.compile "->x( z, a:foo )" ok do (caught = false)-> try CoffeeScript.compile "@>@x(@z,a:foo)" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x( @z, a: foo )" catch caught = true caught CoffeeScript.compile "@>@x(@z,{a:@foo})" CoffeeScript.compile "->x( z, { a:foo } )" ok do (caught = false)-> try CoffeeScript.compile "@>@x(@z,{a:foo})" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x( @z, { a: foo } )" catch caught = true caught CoffeeScript.compile "@>@x @z,{a:@foo}" CoffeeScript.compile "->x z, { a:foo }" ok do (caught = false)-> try CoffeeScript.compile "@>@x @z,{a:foo}" catch caught = true caught ok do (caught = false)-> try CoffeeScript.compile "@>-> @x @z, { a: foo }" catch caught = true caught test "Verify reflective functions source", -> ok ((@>).coffee is "@>") ok ((()@>@).coffee is "()@>@") ok (((x)@>x).coffee is "(x)@>x") foo = @> @console.log "hello" fooString = "@>\n @console.log \"hello\"\n " ok (foo.coffee is fooString) test "Declaration of variables in 'while' statements", -> ok do-> try c = CoffeeScript.compile """ @> while (x = @foo())? @foo(x) """ catch error c = false !!c test "Verify globals marked with @@", -> CoffeeScript.compile "@>@@Math" CoffeeScript.compile "->Math" CoffeeScript.compile "->@@Math" ok do (caught = false)-> try CoffeeScript.compile "@>Math" catch caught = true caught
[ { "context": "# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplan", "end": 18, "score": 0.9998829960823059, "start": 10, "tag": "NAME", "value": "Tim Knip" }, { "context": "orplanner.com/ / tim at floorplanner.com\n# @author aladjev.andrew@gmail.com\n\n#= require new...
source/javascripts/new_src/loaders/collada/node.coffee
andrew-aladev/three.js
0
# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com # @author aladjev.andrew@gmail.com #= require new_src/core/matrix_4 #= require new_src/loaders/collada/transform #= require new_src/loaders/collada/instance_geometry #= require new_src/loaders/collada/instance_controller #= require new_src/loaders/collada/instance_camera class Node constructor: (loader) -> @id = "" @name = "" @sid = "" @nodes = [] @loader = loader @controllers = [] @transforms = [] @geometries = [] @channels = [] @matrix = new THREE.Matrix4() getChannelForTransform: (transformSid) -> length = @channels.length for i in [0...length] channel = @channels[i] parts = channel.target.split("/") id = parts.shift() sid = parts.shift() dotSyntax = sid.indexOf(".") >= 0 arrSyntax = sid.indexOf("(") >= 0 if dotSyntax parts = sid.split "." sid = parts.shift() member = parts.shift() else if arrSyntax arrIndices = sid.split "(" sid = arrIndices.shift() indices_length = arrIndices.length for j in [0...indices_length] arrIndices[j] = parseInt arrIndices[j].replace(/\)/, "") if sid is transformSid channel.info = sid: sid dotSyntax: dotSyntax arrSyntax: arrSyntax arrIndices: arrIndices return channel null getChildById: (id, recursive) -> return this if @id is id if recursive length = @nodes.length for i in [0...length] n = @nodes[i].getChildById id, recursive return n if n null getChildBySid: (sid, recursive) -> return this if @sid is sid if recursive length = @nodes.length for i in [0...length] n = @nodes[i].getChildBySid sid, recursive return n if n null getTransformBySid: (sid) -> length = @transforms.length for i in [0...length] return @transforms[i] if @transforms[i].sid is sid null parse: (element) -> @id = element.getAttribute "id" @sid = element.getAttribute "sid" @name = element.getAttribute "name" @type = element.getAttribute "type" if @type isnt "JOINT" @type = "NODE" @type = 1 @nodes = [] @transforms = [] @geometries = [] @cameras = [] @controllers = [] @matrix = new THREE.Matrix4() length = element.childNodes.length for i in [0...length] child = element.childNodes[i] unless child.nodeType is 1 continue switch child.nodeName when "node" @nodes.push new Node(@loader).parse child when "instance_camera" @cameras.push new THREE.Collada.InstanceCamera().parse child when "instance_controller" @controllers.push new THREE.Collada.InstanceController(@loader).parse child when "instance_geometry" @geometries.push new THREE.Collada.InstanceGeometry(@loader).parse child when "instance_light", "instance_node" url = child.getAttribute("url").replace /^#/, "" iNode = @loader.getLibraryNode url if iNode @nodes.push new Node(@loader).parse iNode when "rotate", "translate", "scale", "matrix", "lookat", "skew" @transforms.push new THREE.Collada.Transform(@loader).parse child else console.warn child.nodeName @channels = @loader.getChannelsForNode this @loader.bakeAnimations this @updateMatrix() this updateMatrix: -> @matrix.identity() length = @transforms.length for i in [0...length] @transforms[i].apply @matrix namespace "THREE.Collada", (exports) -> exports.Node = Node
181358
# @author <NAME> / http://www.floorplanner.com/ / tim at floorplanner.com # @author <EMAIL> #= require new_src/core/matrix_4 #= require new_src/loaders/collada/transform #= require new_src/loaders/collada/instance_geometry #= require new_src/loaders/collada/instance_controller #= require new_src/loaders/collada/instance_camera class Node constructor: (loader) -> @id = "" @name = "" @sid = "" @nodes = [] @loader = loader @controllers = [] @transforms = [] @geometries = [] @channels = [] @matrix = new THREE.Matrix4() getChannelForTransform: (transformSid) -> length = @channels.length for i in [0...length] channel = @channels[i] parts = channel.target.split("/") id = parts.shift() sid = parts.shift() dotSyntax = sid.indexOf(".") >= 0 arrSyntax = sid.indexOf("(") >= 0 if dotSyntax parts = sid.split "." sid = parts.shift() member = parts.shift() else if arrSyntax arrIndices = sid.split "(" sid = arrIndices.shift() indices_length = arrIndices.length for j in [0...indices_length] arrIndices[j] = parseInt arrIndices[j].replace(/\)/, "") if sid is transformSid channel.info = sid: sid dotSyntax: dotSyntax arrSyntax: arrSyntax arrIndices: arrIndices return channel null getChildById: (id, recursive) -> return this if @id is id if recursive length = @nodes.length for i in [0...length] n = @nodes[i].getChildById id, recursive return n if n null getChildBySid: (sid, recursive) -> return this if @sid is sid if recursive length = @nodes.length for i in [0...length] n = @nodes[i].getChildBySid sid, recursive return n if n null getTransformBySid: (sid) -> length = @transforms.length for i in [0...length] return @transforms[i] if @transforms[i].sid is sid null parse: (element) -> @id = element.getAttribute "id" @sid = element.getAttribute "sid" @name = element.getAttribute "name" @type = element.getAttribute "type" if @type isnt "JOINT" @type = "NODE" @type = 1 @nodes = [] @transforms = [] @geometries = [] @cameras = [] @controllers = [] @matrix = new THREE.Matrix4() length = element.childNodes.length for i in [0...length] child = element.childNodes[i] unless child.nodeType is 1 continue switch child.nodeName when "node" @nodes.push new Node(@loader).parse child when "instance_camera" @cameras.push new THREE.Collada.InstanceCamera().parse child when "instance_controller" @controllers.push new THREE.Collada.InstanceController(@loader).parse child when "instance_geometry" @geometries.push new THREE.Collada.InstanceGeometry(@loader).parse child when "instance_light", "instance_node" url = child.getAttribute("url").replace /^#/, "" iNode = @loader.getLibraryNode url if iNode @nodes.push new Node(@loader).parse iNode when "rotate", "translate", "scale", "matrix", "lookat", "skew" @transforms.push new THREE.Collada.Transform(@loader).parse child else console.warn child.nodeName @channels = @loader.getChannelsForNode this @loader.bakeAnimations this @updateMatrix() this updateMatrix: -> @matrix.identity() length = @transforms.length for i in [0...length] @transforms[i].apply @matrix namespace "THREE.Collada", (exports) -> exports.Node = Node
true
# @author PI:NAME:<NAME>END_PI / http://www.floorplanner.com/ / tim at floorplanner.com # @author PI:EMAIL:<EMAIL>END_PI #= require new_src/core/matrix_4 #= require new_src/loaders/collada/transform #= require new_src/loaders/collada/instance_geometry #= require new_src/loaders/collada/instance_controller #= require new_src/loaders/collada/instance_camera class Node constructor: (loader) -> @id = "" @name = "" @sid = "" @nodes = [] @loader = loader @controllers = [] @transforms = [] @geometries = [] @channels = [] @matrix = new THREE.Matrix4() getChannelForTransform: (transformSid) -> length = @channels.length for i in [0...length] channel = @channels[i] parts = channel.target.split("/") id = parts.shift() sid = parts.shift() dotSyntax = sid.indexOf(".") >= 0 arrSyntax = sid.indexOf("(") >= 0 if dotSyntax parts = sid.split "." sid = parts.shift() member = parts.shift() else if arrSyntax arrIndices = sid.split "(" sid = arrIndices.shift() indices_length = arrIndices.length for j in [0...indices_length] arrIndices[j] = parseInt arrIndices[j].replace(/\)/, "") if sid is transformSid channel.info = sid: sid dotSyntax: dotSyntax arrSyntax: arrSyntax arrIndices: arrIndices return channel null getChildById: (id, recursive) -> return this if @id is id if recursive length = @nodes.length for i in [0...length] n = @nodes[i].getChildById id, recursive return n if n null getChildBySid: (sid, recursive) -> return this if @sid is sid if recursive length = @nodes.length for i in [0...length] n = @nodes[i].getChildBySid sid, recursive return n if n null getTransformBySid: (sid) -> length = @transforms.length for i in [0...length] return @transforms[i] if @transforms[i].sid is sid null parse: (element) -> @id = element.getAttribute "id" @sid = element.getAttribute "sid" @name = element.getAttribute "name" @type = element.getAttribute "type" if @type isnt "JOINT" @type = "NODE" @type = 1 @nodes = [] @transforms = [] @geometries = [] @cameras = [] @controllers = [] @matrix = new THREE.Matrix4() length = element.childNodes.length for i in [0...length] child = element.childNodes[i] unless child.nodeType is 1 continue switch child.nodeName when "node" @nodes.push new Node(@loader).parse child when "instance_camera" @cameras.push new THREE.Collada.InstanceCamera().parse child when "instance_controller" @controllers.push new THREE.Collada.InstanceController(@loader).parse child when "instance_geometry" @geometries.push new THREE.Collada.InstanceGeometry(@loader).parse child when "instance_light", "instance_node" url = child.getAttribute("url").replace /^#/, "" iNode = @loader.getLibraryNode url if iNode @nodes.push new Node(@loader).parse iNode when "rotate", "translate", "scale", "matrix", "lookat", "skew" @transforms.push new THREE.Collada.Transform(@loader).parse child else console.warn child.nodeName @channels = @loader.getChannelsForNode this @loader.bakeAnimations this @updateMatrix() this updateMatrix: -> @matrix.identity() length = @transforms.length for i in [0...length] @transforms[i].apply @matrix namespace "THREE.Collada", (exports) -> exports.Node = Node
[ { "context": "n_out: null\n timer_created_at_key: 'totem:session_timer_created_at'\n\n actions:\n sign_out", "end": 2014, "score": 0.7297385334968567, "start": 2008, "tag": "KEY", "value": "totem:" }, { "context": " timer_created_at_key: 'totem:session_...
src/totem/client/totem-application/app/controllers/session_timeout.coffee
sixthedge/cellar
6
import ember from 'ember' import config from 'totem-config/config' import util from 'totem/util' import ajax from 'totem/ajax' import ts from 'totem/scope' # The 'session_timeout' controller is instantiated by 'totem_messages' when # @totem_messages.api_success() is called ('api_success' calls 'reset_session_timer'). # It can also be instantiated (or reset) directly by calling @totem_messages.reset_session_timer(). # A route's 'model' hook typically starts/resets the session timeout by calling # @totem_messages.api_success() after getting the model(s). # By default, totem/ajax will call @totem_messages.api_success(). # Note: The client and server timeouts need to be in sync so should be done on a server request. # Alternatively can call @totem-messages.reset_session_timer(stay_alive: true) to # send a sever 'stay_alive' request and reset the server's timeout. # TODO: Implement a technique to call @totem_messages.reset_session_timer(stay_alive: true) # when a user is performing 'client-only' activities. class TotemLaterTimer constructor: (@obj, @fn, @interval) -> @timer = null start: -> @timer = ember.run.later(@obj, @fn, @interval) cancel: -> ember.run.cancel(@timer) if @timer class TotemTimer constructor: (@options) -> @run_type = @options.run_type or 'later' delete(@options.run_type) @timers = [] reset: -> @cancel() @start() start: -> return unless @options and @run_type switch @run_type when 'later' @add_later args[0], key, args[1] for key, args of @options add_later: (obj, fn, interval) -> timer = new TotemLaterTimer(obj, fn, interval) timer.start() @timers.push timer cancel: -> for timer in @timers timer.cancel() timer = null @timers = [] session = (config and config.session_timeout) or {} export default ember.Controller.extend totem_outlet_messages: null seconds_remaining_before_sign_out: null timer_created_at_key: 'totem:session_timer_created_at' actions: sign_out: -> @cancel_session_timer(); @sign_out_user() continue: -> @reset_session_timer(stay_alive: true) init: -> @_super(arguments...) @totem_scope = ts @setup_session_timeout() @bind_to_storage() setup_session_timeout: -> @timeout_time = session.time or 0 # session timeout after time @warning_time = session.warning_time or 0 # time to display warning page @timeout_time = @timeout_time * 1000 * 60 # convert minutes to milliseconds @warning_time = @warning_time * 1000 * 60 # convert minutes to milliseconds # # Override timeout values for testing. # @timeout_time = 10 * 1000 # session timeout after time (10 seconds) # @warning_time = 5 * 1000 # time to display warning page (5 seconds) @warning_decrement = session.warning_decrement_by or 1 @warning_decrement = @warning_decrement * 1000 # convert seconds to milliseconds @warning_decrement = 1000 if @warning_decrement < 1000 # make decrement min of 1 second for practicality @warning_time = 0 if @timeout_time <= @warning_time if @timeout_time > 0 and @warning_time > 0 @session_timer = new TotemTimer show_session_timeout_warning: [@, (@timeout_time - @warning_time)] sign_out_user: [@, @timeout_time] @count_down_time = @warning_time / 1000 if @count_down_time > 0 @count_down_timer = new TotemTimer decrement_count_down_time: [@, @warning_decrement] @decrement_by = @warning_decrement / 1000 else if @timeout_time > 0 @session_timer = new TotemTimer sign_out_user: [@, @timeout_time] else @session_timer = null cancel_session_timer: -> @session_timer.cancel() if @session_timer @count_down_timer.cancel() if @count_down_timer reset_session_timer: (options) -> return unless @session_timer if options and options.stay_alive type = @totem_scope.get_current_user_type() action = 'stay_alive' # ## reset timer then send stay alive request ## # @reset_local_store() @session_timer.reset() ajax.object(model: type, action: action).then => @hide_session_timeout_warning() , (error) => @totem_messages.api_failure error, model: type, action: action else @reset_local_store() @session_timer.reset() @count_down_timer.cancel() if @count_down_timer reset_local_store: -> window.localStorage.setItem @get_timer_created_at_key(), new Date() show_session_timeout_warning: -> message = session.warning_message or "Your session is about to timeout!" @totem_messages.warn message @totem_messages.message_outlet template_name: 'totem_message_outlet/session_timeout_warning' outlet_controller: @ outlet_messages: message if @count_down_timer @set 'seconds_remaining_before_sign_out', @count_down_time @count_down_timer.reset() decrement_count_down_time: -> time_remaining = @get 'seconds_remaining_before_sign_out' if (time_remaining -= @decrement_by) > 0 @set 'seconds_remaining_before_sign_out', time_remaining @count_down_timer.reset() else @set 'seconds_remaining_before_sign_out', 'session timeout' @count_down_timer.cancel() hide_session_timeout_warning: -> @totem_messages.hide_message_outlet() sign_out_user: -> @totem_messages.sign_out_user() get_timer_created_at_key: -> @get 'timer_created_at_key' bind_to_storage: -> $(window).bind 'storage', (e) => if e.originalEvent.key == @get_timer_created_at_key() or e.key == @get_timer_created_at_key() @reset_session_timer() @hide_session_timeout_warning()
35689
import ember from 'ember' import config from 'totem-config/config' import util from 'totem/util' import ajax from 'totem/ajax' import ts from 'totem/scope' # The 'session_timeout' controller is instantiated by 'totem_messages' when # @totem_messages.api_success() is called ('api_success' calls 'reset_session_timer'). # It can also be instantiated (or reset) directly by calling @totem_messages.reset_session_timer(). # A route's 'model' hook typically starts/resets the session timeout by calling # @totem_messages.api_success() after getting the model(s). # By default, totem/ajax will call @totem_messages.api_success(). # Note: The client and server timeouts need to be in sync so should be done on a server request. # Alternatively can call @totem-messages.reset_session_timer(stay_alive: true) to # send a sever 'stay_alive' request and reset the server's timeout. # TODO: Implement a technique to call @totem_messages.reset_session_timer(stay_alive: true) # when a user is performing 'client-only' activities. class TotemLaterTimer constructor: (@obj, @fn, @interval) -> @timer = null start: -> @timer = ember.run.later(@obj, @fn, @interval) cancel: -> ember.run.cancel(@timer) if @timer class TotemTimer constructor: (@options) -> @run_type = @options.run_type or 'later' delete(@options.run_type) @timers = [] reset: -> @cancel() @start() start: -> return unless @options and @run_type switch @run_type when 'later' @add_later args[0], key, args[1] for key, args of @options add_later: (obj, fn, interval) -> timer = new TotemLaterTimer(obj, fn, interval) timer.start() @timers.push timer cancel: -> for timer in @timers timer.cancel() timer = null @timers = [] session = (config and config.session_timeout) or {} export default ember.Controller.extend totem_outlet_messages: null seconds_remaining_before_sign_out: null timer_created_at_key: '<KEY>session_<KEY>' actions: sign_out: -> @cancel_session_timer(); @sign_out_user() continue: -> @reset_session_timer(stay_alive: true) init: -> @_super(arguments...) @totem_scope = ts @setup_session_timeout() @bind_to_storage() setup_session_timeout: -> @timeout_time = session.time or 0 # session timeout after time @warning_time = session.warning_time or 0 # time to display warning page @timeout_time = @timeout_time * 1000 * 60 # convert minutes to milliseconds @warning_time = @warning_time * 1000 * 60 # convert minutes to milliseconds # # Override timeout values for testing. # @timeout_time = 10 * 1000 # session timeout after time (10 seconds) # @warning_time = 5 * 1000 # time to display warning page (5 seconds) @warning_decrement = session.warning_decrement_by or 1 @warning_decrement = @warning_decrement * 1000 # convert seconds to milliseconds @warning_decrement = 1000 if @warning_decrement < 1000 # make decrement min of 1 second for practicality @warning_time = 0 if @timeout_time <= @warning_time if @timeout_time > 0 and @warning_time > 0 @session_timer = new TotemTimer show_session_timeout_warning: [@, (@timeout_time - @warning_time)] sign_out_user: [@, @timeout_time] @count_down_time = @warning_time / 1000 if @count_down_time > 0 @count_down_timer = new TotemTimer decrement_count_down_time: [@, @warning_decrement] @decrement_by = @warning_decrement / 1000 else if @timeout_time > 0 @session_timer = new TotemTimer sign_out_user: [@, @timeout_time] else @session_timer = null cancel_session_timer: -> @session_timer.cancel() if @session_timer @count_down_timer.cancel() if @count_down_timer reset_session_timer: (options) -> return unless @session_timer if options and options.stay_alive type = @totem_scope.get_current_user_type() action = 'stay_alive' # ## reset timer then send stay alive request ## # @reset_local_store() @session_timer.reset() ajax.object(model: type, action: action).then => @hide_session_timeout_warning() , (error) => @totem_messages.api_failure error, model: type, action: action else @reset_local_store() @session_timer.reset() @count_down_timer.cancel() if @count_down_timer reset_local_store: -> window.localStorage.setItem @get_timer_created_at_key(), new Date() show_session_timeout_warning: -> message = session.warning_message or "Your session is about to timeout!" @totem_messages.warn message @totem_messages.message_outlet template_name: 'totem_message_outlet/session_timeout_warning' outlet_controller: @ outlet_messages: message if @count_down_timer @set 'seconds_remaining_before_sign_out', @count_down_time @count_down_timer.reset() decrement_count_down_time: -> time_remaining = @get 'seconds_remaining_before_sign_out' if (time_remaining -= @decrement_by) > 0 @set 'seconds_remaining_before_sign_out', time_remaining @count_down_timer.reset() else @set 'seconds_remaining_before_sign_out', 'session timeout' @count_down_timer.cancel() hide_session_timeout_warning: -> @totem_messages.hide_message_outlet() sign_out_user: -> @totem_messages.sign_out_user() get_timer_created_at_key: -> @get 'timer_created_at_key' bind_to_storage: -> $(window).bind 'storage', (e) => if e.originalEvent.key == @get_timer_created_at_key() or e.key == @get_timer_created_at_key() @reset_session_timer() @hide_session_timeout_warning()
true
import ember from 'ember' import config from 'totem-config/config' import util from 'totem/util' import ajax from 'totem/ajax' import ts from 'totem/scope' # The 'session_timeout' controller is instantiated by 'totem_messages' when # @totem_messages.api_success() is called ('api_success' calls 'reset_session_timer'). # It can also be instantiated (or reset) directly by calling @totem_messages.reset_session_timer(). # A route's 'model' hook typically starts/resets the session timeout by calling # @totem_messages.api_success() after getting the model(s). # By default, totem/ajax will call @totem_messages.api_success(). # Note: The client and server timeouts need to be in sync so should be done on a server request. # Alternatively can call @totem-messages.reset_session_timer(stay_alive: true) to # send a sever 'stay_alive' request and reset the server's timeout. # TODO: Implement a technique to call @totem_messages.reset_session_timer(stay_alive: true) # when a user is performing 'client-only' activities. class TotemLaterTimer constructor: (@obj, @fn, @interval) -> @timer = null start: -> @timer = ember.run.later(@obj, @fn, @interval) cancel: -> ember.run.cancel(@timer) if @timer class TotemTimer constructor: (@options) -> @run_type = @options.run_type or 'later' delete(@options.run_type) @timers = [] reset: -> @cancel() @start() start: -> return unless @options and @run_type switch @run_type when 'later' @add_later args[0], key, args[1] for key, args of @options add_later: (obj, fn, interval) -> timer = new TotemLaterTimer(obj, fn, interval) timer.start() @timers.push timer cancel: -> for timer in @timers timer.cancel() timer = null @timers = [] session = (config and config.session_timeout) or {} export default ember.Controller.extend totem_outlet_messages: null seconds_remaining_before_sign_out: null timer_created_at_key: 'PI:KEY:<KEY>END_PIsession_PI:KEY:<KEY>END_PI' actions: sign_out: -> @cancel_session_timer(); @sign_out_user() continue: -> @reset_session_timer(stay_alive: true) init: -> @_super(arguments...) @totem_scope = ts @setup_session_timeout() @bind_to_storage() setup_session_timeout: -> @timeout_time = session.time or 0 # session timeout after time @warning_time = session.warning_time or 0 # time to display warning page @timeout_time = @timeout_time * 1000 * 60 # convert minutes to milliseconds @warning_time = @warning_time * 1000 * 60 # convert minutes to milliseconds # # Override timeout values for testing. # @timeout_time = 10 * 1000 # session timeout after time (10 seconds) # @warning_time = 5 * 1000 # time to display warning page (5 seconds) @warning_decrement = session.warning_decrement_by or 1 @warning_decrement = @warning_decrement * 1000 # convert seconds to milliseconds @warning_decrement = 1000 if @warning_decrement < 1000 # make decrement min of 1 second for practicality @warning_time = 0 if @timeout_time <= @warning_time if @timeout_time > 0 and @warning_time > 0 @session_timer = new TotemTimer show_session_timeout_warning: [@, (@timeout_time - @warning_time)] sign_out_user: [@, @timeout_time] @count_down_time = @warning_time / 1000 if @count_down_time > 0 @count_down_timer = new TotemTimer decrement_count_down_time: [@, @warning_decrement] @decrement_by = @warning_decrement / 1000 else if @timeout_time > 0 @session_timer = new TotemTimer sign_out_user: [@, @timeout_time] else @session_timer = null cancel_session_timer: -> @session_timer.cancel() if @session_timer @count_down_timer.cancel() if @count_down_timer reset_session_timer: (options) -> return unless @session_timer if options and options.stay_alive type = @totem_scope.get_current_user_type() action = 'stay_alive' # ## reset timer then send stay alive request ## # @reset_local_store() @session_timer.reset() ajax.object(model: type, action: action).then => @hide_session_timeout_warning() , (error) => @totem_messages.api_failure error, model: type, action: action else @reset_local_store() @session_timer.reset() @count_down_timer.cancel() if @count_down_timer reset_local_store: -> window.localStorage.setItem @get_timer_created_at_key(), new Date() show_session_timeout_warning: -> message = session.warning_message or "Your session is about to timeout!" @totem_messages.warn message @totem_messages.message_outlet template_name: 'totem_message_outlet/session_timeout_warning' outlet_controller: @ outlet_messages: message if @count_down_timer @set 'seconds_remaining_before_sign_out', @count_down_time @count_down_timer.reset() decrement_count_down_time: -> time_remaining = @get 'seconds_remaining_before_sign_out' if (time_remaining -= @decrement_by) > 0 @set 'seconds_remaining_before_sign_out', time_remaining @count_down_timer.reset() else @set 'seconds_remaining_before_sign_out', 'session timeout' @count_down_timer.cancel() hide_session_timeout_warning: -> @totem_messages.hide_message_outlet() sign_out_user: -> @totem_messages.sign_out_user() get_timer_created_at_key: -> @get 'timer_created_at_key' bind_to_storage: -> $(window).bind 'storage', (e) => if e.originalEvent.key == @get_timer_created_at_key() or e.key == @get_timer_created_at_key() @reset_session_timer() @hide_session_timeout_warning()
[ { "context": " = new Date().getFullYear()\n printf(\"(c) 2022%s Hein Thant Maung Maung. Licensed under BSD-2-CLAUSE.\\n\\n\",\n if cu", "end": 1686, "score": 0.9998720288276672, "start": 1664, "tag": "NAME", "value": "Hein Thant Maung Maung" } ]
src/xuerun.coffee
heinthanth/xuerun
0
import { parse } from "https://deno.land/std@0.139.0/flags/mod.ts"; import { parse as parseYAML } from "https://deno.land/std@0.139.0/encoding/yaml.ts" import { YAMLError } from "https://deno.land/std@0.139.0/encoding/_yaml/error.ts" import { dirname, resolve } from "https://deno.land/std@0.139.0/path/mod.ts"; import { printf } from "https://deno.land/std@0.139.0/fmt/printf.ts" import { StructError } from "https://esm.sh/superstruct" import { runRecipe } from "./core.coffee" import createConfiguration from "./schema.coffee" loadXueRunTasks = (path) -> try content = Deno.readTextFileSync(path) return createConfiguration(parseYAML(content)) catch error if error instanceof YAMLError or error instanceof StructError console.error( "\nxuerun: oops, invalid .xuerun tasks.\nError:", error.message, "\n") else console.error( "\nxuerun: oops, can't read .xuerun tasks.\nError:", error.message, "\n") Deno.exit(1) printVersion = () -> console.log() # print padding ascii = [ 'y88b / 888~-_ ' ' y88b / 888 888 e88~~8e 888 \\ 888 888 888-~88e' ' y88b/ 888 888 d888 88b 888 | 888 888 888 888' ' /y88b 888 888 8888__888 888 / 888 888 888 888' ' / y88b 888 888 y888 , 888_-~ 888 888 888 888' '/ y88b "88_-888 "88___/ 888 ~-_ "88_-888 888 888'].join("\n") console.info("%s\n", ascii) printf("XueRun v%s ( %s / %s )\n", "1.0.0", Deno.build.os, Deno.build.arch) currentYear = new Date().getFullYear() printf("(c) 2022%s Hein Thant Maung Maung. Licensed under BSD-2-CLAUSE.\n\n", if currentYear == 2022 then "" else " - #{currentYear}") printHelp = (shouldPrintVersion = true) -> if shouldPrintVersion then printVersion() helpStrings = [ "General:", " xuerun [tasks]... [options]...", "", "Options:", " -t, --tasks path to xuerun tasks ( default: tasks.xuerun ).", " -n, --recon do nothing, print commands." "", " -v, --version print xuerun version and others.", " -h, --help print this help message.", "", "For docs, usage, etc., visit https://github.com/heinthanth/xuerun."].join("\n") console.info(helpStrings, "\n") actionKind = RUN_RECIPE: "RUN_RECIPE" PRINT_HELP: "PRINT_HELP" PRINT_VERSION: "PRINT_VERSION" parseCmdOption = () -> {'_': positional, '--': cliRest, ...options} = parse Deno.args, { "--": true } userOption = action: actionKind.RUN_RECIPE, recon: !1, recipes: [] options: {} tasksPath: "tasks.xuerun" # parse options Object.entries(options).forEach ([k, v]) -> switch k when "h", "help" then userOption.action = actionKind.PRINT_HELP when "v", "version" then userOption.action = actionKind.PRINT_VERSION when "t", "tasks" then userOption.tasksPath = if typeof v == "string" or typeof v == "number" then v.toString() else "tasks.xuerun" when "n", "recon" then userOption.recon = true # remove default CLI arguments {h, v, t, n, help, version, tasks, recon, ...restCLIargs} = options # parse options passed with -- --something {'_': _restPositional, ...optionsFromCLIrestOptions} = parse(cliRest) # combine options userOption.options = { ...restCLIargs, ...optionsFromCLIrestOptions } return { ...userOption, recipes: positional } programMain = () -> {recipes, tasksPath, action, options, recon} = parseCmdOption() if action == actionKind.PRINT_HELP then return printHelp() if action == actionKind.PRINT_VERSION then return printVersion() # load and run xueRunRc = loadXueRunTasks(tasksPath) # change dir to task path dir. Deno.chdir(dirname(resolve(tasksPath))) if recipes.length == 0 if xueRunRc.hasOwnProperty("all") return runRecipe(xueRunRc, "all", options, recon, !1) else console.error("\nxuerun: oops, no recipe given, nothing to do!\n"); Deno.exit(1) recipes.forEach (recipe) -> await runRecipe(xueRunRc, recipe, options, recon, !1) # call main function if import.meta.main then programMain()
150699
import { parse } from "https://deno.land/std@0.139.0/flags/mod.ts"; import { parse as parseYAML } from "https://deno.land/std@0.139.0/encoding/yaml.ts" import { YAMLError } from "https://deno.land/std@0.139.0/encoding/_yaml/error.ts" import { dirname, resolve } from "https://deno.land/std@0.139.0/path/mod.ts"; import { printf } from "https://deno.land/std@0.139.0/fmt/printf.ts" import { StructError } from "https://esm.sh/superstruct" import { runRecipe } from "./core.coffee" import createConfiguration from "./schema.coffee" loadXueRunTasks = (path) -> try content = Deno.readTextFileSync(path) return createConfiguration(parseYAML(content)) catch error if error instanceof YAMLError or error instanceof StructError console.error( "\nxuerun: oops, invalid .xuerun tasks.\nError:", error.message, "\n") else console.error( "\nxuerun: oops, can't read .xuerun tasks.\nError:", error.message, "\n") Deno.exit(1) printVersion = () -> console.log() # print padding ascii = [ 'y88b / 888~-_ ' ' y88b / 888 888 e88~~8e 888 \\ 888 888 888-~88e' ' y88b/ 888 888 d888 88b 888 | 888 888 888 888' ' /y88b 888 888 8888__888 888 / 888 888 888 888' ' / y88b 888 888 y888 , 888_-~ 888 888 888 888' '/ y88b "88_-888 "88___/ 888 ~-_ "88_-888 888 888'].join("\n") console.info("%s\n", ascii) printf("XueRun v%s ( %s / %s )\n", "1.0.0", Deno.build.os, Deno.build.arch) currentYear = new Date().getFullYear() printf("(c) 2022%s <NAME>. Licensed under BSD-2-CLAUSE.\n\n", if currentYear == 2022 then "" else " - #{currentYear}") printHelp = (shouldPrintVersion = true) -> if shouldPrintVersion then printVersion() helpStrings = [ "General:", " xuerun [tasks]... [options]...", "", "Options:", " -t, --tasks path to xuerun tasks ( default: tasks.xuerun ).", " -n, --recon do nothing, print commands." "", " -v, --version print xuerun version and others.", " -h, --help print this help message.", "", "For docs, usage, etc., visit https://github.com/heinthanth/xuerun."].join("\n") console.info(helpStrings, "\n") actionKind = RUN_RECIPE: "RUN_RECIPE" PRINT_HELP: "PRINT_HELP" PRINT_VERSION: "PRINT_VERSION" parseCmdOption = () -> {'_': positional, '--': cliRest, ...options} = parse Deno.args, { "--": true } userOption = action: actionKind.RUN_RECIPE, recon: !1, recipes: [] options: {} tasksPath: "tasks.xuerun" # parse options Object.entries(options).forEach ([k, v]) -> switch k when "h", "help" then userOption.action = actionKind.PRINT_HELP when "v", "version" then userOption.action = actionKind.PRINT_VERSION when "t", "tasks" then userOption.tasksPath = if typeof v == "string" or typeof v == "number" then v.toString() else "tasks.xuerun" when "n", "recon" then userOption.recon = true # remove default CLI arguments {h, v, t, n, help, version, tasks, recon, ...restCLIargs} = options # parse options passed with -- --something {'_': _restPositional, ...optionsFromCLIrestOptions} = parse(cliRest) # combine options userOption.options = { ...restCLIargs, ...optionsFromCLIrestOptions } return { ...userOption, recipes: positional } programMain = () -> {recipes, tasksPath, action, options, recon} = parseCmdOption() if action == actionKind.PRINT_HELP then return printHelp() if action == actionKind.PRINT_VERSION then return printVersion() # load and run xueRunRc = loadXueRunTasks(tasksPath) # change dir to task path dir. Deno.chdir(dirname(resolve(tasksPath))) if recipes.length == 0 if xueRunRc.hasOwnProperty("all") return runRecipe(xueRunRc, "all", options, recon, !1) else console.error("\nxuerun: oops, no recipe given, nothing to do!\n"); Deno.exit(1) recipes.forEach (recipe) -> await runRecipe(xueRunRc, recipe, options, recon, !1) # call main function if import.meta.main then programMain()
true
import { parse } from "https://deno.land/std@0.139.0/flags/mod.ts"; import { parse as parseYAML } from "https://deno.land/std@0.139.0/encoding/yaml.ts" import { YAMLError } from "https://deno.land/std@0.139.0/encoding/_yaml/error.ts" import { dirname, resolve } from "https://deno.land/std@0.139.0/path/mod.ts"; import { printf } from "https://deno.land/std@0.139.0/fmt/printf.ts" import { StructError } from "https://esm.sh/superstruct" import { runRecipe } from "./core.coffee" import createConfiguration from "./schema.coffee" loadXueRunTasks = (path) -> try content = Deno.readTextFileSync(path) return createConfiguration(parseYAML(content)) catch error if error instanceof YAMLError or error instanceof StructError console.error( "\nxuerun: oops, invalid .xuerun tasks.\nError:", error.message, "\n") else console.error( "\nxuerun: oops, can't read .xuerun tasks.\nError:", error.message, "\n") Deno.exit(1) printVersion = () -> console.log() # print padding ascii = [ 'y88b / 888~-_ ' ' y88b / 888 888 e88~~8e 888 \\ 888 888 888-~88e' ' y88b/ 888 888 d888 88b 888 | 888 888 888 888' ' /y88b 888 888 8888__888 888 / 888 888 888 888' ' / y88b 888 888 y888 , 888_-~ 888 888 888 888' '/ y88b "88_-888 "88___/ 888 ~-_ "88_-888 888 888'].join("\n") console.info("%s\n", ascii) printf("XueRun v%s ( %s / %s )\n", "1.0.0", Deno.build.os, Deno.build.arch) currentYear = new Date().getFullYear() printf("(c) 2022%s PI:NAME:<NAME>END_PI. Licensed under BSD-2-CLAUSE.\n\n", if currentYear == 2022 then "" else " - #{currentYear}") printHelp = (shouldPrintVersion = true) -> if shouldPrintVersion then printVersion() helpStrings = [ "General:", " xuerun [tasks]... [options]...", "", "Options:", " -t, --tasks path to xuerun tasks ( default: tasks.xuerun ).", " -n, --recon do nothing, print commands." "", " -v, --version print xuerun version and others.", " -h, --help print this help message.", "", "For docs, usage, etc., visit https://github.com/heinthanth/xuerun."].join("\n") console.info(helpStrings, "\n") actionKind = RUN_RECIPE: "RUN_RECIPE" PRINT_HELP: "PRINT_HELP" PRINT_VERSION: "PRINT_VERSION" parseCmdOption = () -> {'_': positional, '--': cliRest, ...options} = parse Deno.args, { "--": true } userOption = action: actionKind.RUN_RECIPE, recon: !1, recipes: [] options: {} tasksPath: "tasks.xuerun" # parse options Object.entries(options).forEach ([k, v]) -> switch k when "h", "help" then userOption.action = actionKind.PRINT_HELP when "v", "version" then userOption.action = actionKind.PRINT_VERSION when "t", "tasks" then userOption.tasksPath = if typeof v == "string" or typeof v == "number" then v.toString() else "tasks.xuerun" when "n", "recon" then userOption.recon = true # remove default CLI arguments {h, v, t, n, help, version, tasks, recon, ...restCLIargs} = options # parse options passed with -- --something {'_': _restPositional, ...optionsFromCLIrestOptions} = parse(cliRest) # combine options userOption.options = { ...restCLIargs, ...optionsFromCLIrestOptions } return { ...userOption, recipes: positional } programMain = () -> {recipes, tasksPath, action, options, recon} = parseCmdOption() if action == actionKind.PRINT_HELP then return printHelp() if action == actionKind.PRINT_VERSION then return printVersion() # load and run xueRunRc = loadXueRunTasks(tasksPath) # change dir to task path dir. Deno.chdir(dirname(resolve(tasksPath))) if recipes.length == 0 if xueRunRc.hasOwnProperty("all") return runRecipe(xueRunRc, "all", options, recon, !1) else console.error("\nxuerun: oops, no recipe given, nothing to do!\n"); Deno.exit(1) recipes.forEach (recipe) -> await runRecipe(xueRunRc, recipe, options, recon, !1) # call main function if import.meta.main then programMain()
[ { "context": "ends require('../abstract')\n\n cacheKeyAppendix: 'filerev'\n\n enabled: -> _.isObject(@getConfig().postp", "end": 147, "score": 0.5794306397438049, "start": 144, "tag": "KEY", "value": "fil" } ]
lib/grunt/task_helpers/filerev/abstract.coffee
wonderweblabs/graspi
0
_ = require 'lodash' File = require 'path' module.exports = class AbstractTaskHelper extends require('../abstract') cacheKeyAppendix: 'filerev' enabled: -> _.isObject(@getConfig().postpipeline.filerevision) # ------------------------------------------------------------ getMappingFile: -> File.join(@getTmpPath(), 'revision-mapping.json')
194456
_ = require 'lodash' File = require 'path' module.exports = class AbstractTaskHelper extends require('../abstract') cacheKeyAppendix: '<KEY>erev' enabled: -> _.isObject(@getConfig().postpipeline.filerevision) # ------------------------------------------------------------ getMappingFile: -> File.join(@getTmpPath(), 'revision-mapping.json')
true
_ = require 'lodash' File = require 'path' module.exports = class AbstractTaskHelper extends require('../abstract') cacheKeyAppendix: 'PI:KEY:<KEY>END_PIerev' enabled: -> _.isObject(@getConfig().postpipeline.filerevision) # ------------------------------------------------------------ getMappingFile: -> File.join(@getTmpPath(), 'revision-mapping.json')
[ { "context": "PresentationKey: ->\n key = @currentDoctype.toLowerCase()\n key += localStore.keys.separation + loc", "end": 3332, "score": 0.4901748299598694, "start": 3321, "tag": "KEY", "value": "toLowerCase" } ]
client/app/views/results_global_controls_view.coffee
aenario/cozy-databrowser
0
View = require './../lib/view' DeleteAllModel = require './../models/delete_all_model' app = require 'application' localStore = require './../helpers/oLocalStorageHelper' module.exports = class ResultsGlobalControlsView extends View el: '#results-global-controls' templateModal: require('./templates/modal_confirm') currentDoctype: '' events : 'mouseover #delete-all' : 'switchStyleOfDeleteButton' 'mouseout #delete-all' : 'switchStyleOfDeleteButton' 'click #delete-all' : 'confirmDeleteAll' 'click .about-doctype' : 'toogleMetaInfos' 'click .view-switcher' : 'switchToTableView' #-------------------------BEGIN VIEW BEHAVIOR------------------------------- template: -> require './templates/results_global_controls' initialize : (opt) -> @opt = opt #---- Clean and ensure that all methods are re-delegate to new controls $(@el).undelegate '.about-doctype', 'click' $(@el).undelegate '.view-switcher', 'click' $(@el).undelegate '#delete-all', 'mouseover' $(@el).undelegate '#delete-all', 'mouseout' $(@el).undelegate '#delete-all', 'click' #---- set current doctypes (waiting multiple doctype) if @opt.doctypes? @currentDoctype = @opt.doctypes[0] || '' #render view with options @render @opt render: (opt) => #----Prepare template datas templateData = {} #--icon associate to presentation isList = opt.presentation and (opt.presentation is 'list') iconPresentation = if isList then 'icon-th' else 'icon-list-alt' templateData['icon_presentation'] = iconPresentation #--general infos for 'currently exploring' templateData['range'] = if opt.range then '(' + opt.range + ')' || '' templateData['doctype'] = if opt.doctypes then opt.doctypes[0] else '' if opt.displayName and (opt.displayName isnt '') templateData['doctype'] = opt.displayName #--visibility of metainfos templateData['hasMetainfos'] = if opt.hasMetaInfos then true isMetaInfoVisible = @isMetaInfoVisible() templateData['isVisible'] = isMetaInfoVisible if isMetaInfoVisible then $('#results-meta-infos').show() #----apply ancestor method super templateData #--------------------------END VIEW BEHAVIOR-------------------------------- #----------------------BEGIN TABLE/LIST VIEW SWITCHER----------------------- switchToTableView: (event) => viewSwitcher = $(event.currentTarget) presentation = 'table' if @currentDoctype if viewSwitcher.hasClass('icon-th') presentation = 'table' viewSwitcher.removeClass('icon-th').addClass('icon-list-alt') else presentation = 'list' viewSwitcher.removeClass('icon-list-alt').addClass('icon-th') @storePresentation presentation presentationQuery = '&&presentation=' + presentation tableRoute = 'search/all/' + @currentDoctype + presentationQuery app.router.navigate tableRoute, replace: true trigger : true prepareStoragePresentationKey: -> key = @currentDoctype.toLowerCase() key += localStore.keys.separation + localStore.keys.isListPresentation return key isListPresentation: -> key = @prepareStoragePresentationKey() return localStore.getBoolean key storePresentation: (presentation) -> isList = if presentation isnt 'table' then true else false key = @prepareStoragePresentationKey() localStore.setBoolean key, isList #-----------------------END TABLE/LIST VIEW SWITCHER------------------------ #--------------------------BEGIN META INFORMATION--------------------------- isMetaInfoVisible : -> return localStore.getBoolean localStore.keys.isMetaInfoVisible toogleMetaInfos: (event) -> jqObj = $(event.currentTarget) if jqObj.hasClass 'white-and-green' jqObj.removeClass('white-and-green') $('#results-meta-infos').hide() localStore.setBoolean localStore.keys.isMetaInfoVisible, false else jqObj.addClass('white-and-green') $('#results-meta-infos').show() localStore.setBoolean localStore.keys.isMetaInfoVisible, true #---------------------------END META INFORMATION --------------------------- #----------------------------BEGIN DELETE ALL------------------------------- switchStyleOfDeleteButton: (event) -> jqObj = $(event.currentTarget) if not jqObj.hasClass 'btn-danger' jqObj.addClass 'btn-danger' jqObj.children('span').text t('delete all') + ' ' else jqObj.removeClass 'btn-danger' jqObj.children('span').empty() confirmDeleteAll : (e) -> e.preventDefault() data = title: t 'confirmation required' body: t 'are you absolutely sure' confirm: t 'delete permanently' $("body").prepend @templateModal(data) $("#confirmation-dialog").modal() $("#confirmation-dialog").modal("show") $("#confirmation-dialog-confirm").unbind 'click' $("#confirmation-dialog-confirm").bind "click", => @deleteAll() deleteAll: -> if @currentDoctype? and @currentDoctype isnt '' deleteAllModel = new DeleteAllModel() deleteAllModel.fetch type: 'DELETE' url : deleteAllModel.urlRoot + '?' + $.param doctype : @currentDoctype success : (col, data) -> app.router.navigate 'search', replace: true trigger : true location.reload() #-----------------------------END DELETE ALL--------------------------------
94652
View = require './../lib/view' DeleteAllModel = require './../models/delete_all_model' app = require 'application' localStore = require './../helpers/oLocalStorageHelper' module.exports = class ResultsGlobalControlsView extends View el: '#results-global-controls' templateModal: require('./templates/modal_confirm') currentDoctype: '' events : 'mouseover #delete-all' : 'switchStyleOfDeleteButton' 'mouseout #delete-all' : 'switchStyleOfDeleteButton' 'click #delete-all' : 'confirmDeleteAll' 'click .about-doctype' : 'toogleMetaInfos' 'click .view-switcher' : 'switchToTableView' #-------------------------BEGIN VIEW BEHAVIOR------------------------------- template: -> require './templates/results_global_controls' initialize : (opt) -> @opt = opt #---- Clean and ensure that all methods are re-delegate to new controls $(@el).undelegate '.about-doctype', 'click' $(@el).undelegate '.view-switcher', 'click' $(@el).undelegate '#delete-all', 'mouseover' $(@el).undelegate '#delete-all', 'mouseout' $(@el).undelegate '#delete-all', 'click' #---- set current doctypes (waiting multiple doctype) if @opt.doctypes? @currentDoctype = @opt.doctypes[0] || '' #render view with options @render @opt render: (opt) => #----Prepare template datas templateData = {} #--icon associate to presentation isList = opt.presentation and (opt.presentation is 'list') iconPresentation = if isList then 'icon-th' else 'icon-list-alt' templateData['icon_presentation'] = iconPresentation #--general infos for 'currently exploring' templateData['range'] = if opt.range then '(' + opt.range + ')' || '' templateData['doctype'] = if opt.doctypes then opt.doctypes[0] else '' if opt.displayName and (opt.displayName isnt '') templateData['doctype'] = opt.displayName #--visibility of metainfos templateData['hasMetainfos'] = if opt.hasMetaInfos then true isMetaInfoVisible = @isMetaInfoVisible() templateData['isVisible'] = isMetaInfoVisible if isMetaInfoVisible then $('#results-meta-infos').show() #----apply ancestor method super templateData #--------------------------END VIEW BEHAVIOR-------------------------------- #----------------------BEGIN TABLE/LIST VIEW SWITCHER----------------------- switchToTableView: (event) => viewSwitcher = $(event.currentTarget) presentation = 'table' if @currentDoctype if viewSwitcher.hasClass('icon-th') presentation = 'table' viewSwitcher.removeClass('icon-th').addClass('icon-list-alt') else presentation = 'list' viewSwitcher.removeClass('icon-list-alt').addClass('icon-th') @storePresentation presentation presentationQuery = '&&presentation=' + presentation tableRoute = 'search/all/' + @currentDoctype + presentationQuery app.router.navigate tableRoute, replace: true trigger : true prepareStoragePresentationKey: -> key = @currentDoctype.<KEY>() key += localStore.keys.separation + localStore.keys.isListPresentation return key isListPresentation: -> key = @prepareStoragePresentationKey() return localStore.getBoolean key storePresentation: (presentation) -> isList = if presentation isnt 'table' then true else false key = @prepareStoragePresentationKey() localStore.setBoolean key, isList #-----------------------END TABLE/LIST VIEW SWITCHER------------------------ #--------------------------BEGIN META INFORMATION--------------------------- isMetaInfoVisible : -> return localStore.getBoolean localStore.keys.isMetaInfoVisible toogleMetaInfos: (event) -> jqObj = $(event.currentTarget) if jqObj.hasClass 'white-and-green' jqObj.removeClass('white-and-green') $('#results-meta-infos').hide() localStore.setBoolean localStore.keys.isMetaInfoVisible, false else jqObj.addClass('white-and-green') $('#results-meta-infos').show() localStore.setBoolean localStore.keys.isMetaInfoVisible, true #---------------------------END META INFORMATION --------------------------- #----------------------------BEGIN DELETE ALL------------------------------- switchStyleOfDeleteButton: (event) -> jqObj = $(event.currentTarget) if not jqObj.hasClass 'btn-danger' jqObj.addClass 'btn-danger' jqObj.children('span').text t('delete all') + ' ' else jqObj.removeClass 'btn-danger' jqObj.children('span').empty() confirmDeleteAll : (e) -> e.preventDefault() data = title: t 'confirmation required' body: t 'are you absolutely sure' confirm: t 'delete permanently' $("body").prepend @templateModal(data) $("#confirmation-dialog").modal() $("#confirmation-dialog").modal("show") $("#confirmation-dialog-confirm").unbind 'click' $("#confirmation-dialog-confirm").bind "click", => @deleteAll() deleteAll: -> if @currentDoctype? and @currentDoctype isnt '' deleteAllModel = new DeleteAllModel() deleteAllModel.fetch type: 'DELETE' url : deleteAllModel.urlRoot + '?' + $.param doctype : @currentDoctype success : (col, data) -> app.router.navigate 'search', replace: true trigger : true location.reload() #-----------------------------END DELETE ALL--------------------------------
true
View = require './../lib/view' DeleteAllModel = require './../models/delete_all_model' app = require 'application' localStore = require './../helpers/oLocalStorageHelper' module.exports = class ResultsGlobalControlsView extends View el: '#results-global-controls' templateModal: require('./templates/modal_confirm') currentDoctype: '' events : 'mouseover #delete-all' : 'switchStyleOfDeleteButton' 'mouseout #delete-all' : 'switchStyleOfDeleteButton' 'click #delete-all' : 'confirmDeleteAll' 'click .about-doctype' : 'toogleMetaInfos' 'click .view-switcher' : 'switchToTableView' #-------------------------BEGIN VIEW BEHAVIOR------------------------------- template: -> require './templates/results_global_controls' initialize : (opt) -> @opt = opt #---- Clean and ensure that all methods are re-delegate to new controls $(@el).undelegate '.about-doctype', 'click' $(@el).undelegate '.view-switcher', 'click' $(@el).undelegate '#delete-all', 'mouseover' $(@el).undelegate '#delete-all', 'mouseout' $(@el).undelegate '#delete-all', 'click' #---- set current doctypes (waiting multiple doctype) if @opt.doctypes? @currentDoctype = @opt.doctypes[0] || '' #render view with options @render @opt render: (opt) => #----Prepare template datas templateData = {} #--icon associate to presentation isList = opt.presentation and (opt.presentation is 'list') iconPresentation = if isList then 'icon-th' else 'icon-list-alt' templateData['icon_presentation'] = iconPresentation #--general infos for 'currently exploring' templateData['range'] = if opt.range then '(' + opt.range + ')' || '' templateData['doctype'] = if opt.doctypes then opt.doctypes[0] else '' if opt.displayName and (opt.displayName isnt '') templateData['doctype'] = opt.displayName #--visibility of metainfos templateData['hasMetainfos'] = if opt.hasMetaInfos then true isMetaInfoVisible = @isMetaInfoVisible() templateData['isVisible'] = isMetaInfoVisible if isMetaInfoVisible then $('#results-meta-infos').show() #----apply ancestor method super templateData #--------------------------END VIEW BEHAVIOR-------------------------------- #----------------------BEGIN TABLE/LIST VIEW SWITCHER----------------------- switchToTableView: (event) => viewSwitcher = $(event.currentTarget) presentation = 'table' if @currentDoctype if viewSwitcher.hasClass('icon-th') presentation = 'table' viewSwitcher.removeClass('icon-th').addClass('icon-list-alt') else presentation = 'list' viewSwitcher.removeClass('icon-list-alt').addClass('icon-th') @storePresentation presentation presentationQuery = '&&presentation=' + presentation tableRoute = 'search/all/' + @currentDoctype + presentationQuery app.router.navigate tableRoute, replace: true trigger : true prepareStoragePresentationKey: -> key = @currentDoctype.PI:KEY:<KEY>END_PI() key += localStore.keys.separation + localStore.keys.isListPresentation return key isListPresentation: -> key = @prepareStoragePresentationKey() return localStore.getBoolean key storePresentation: (presentation) -> isList = if presentation isnt 'table' then true else false key = @prepareStoragePresentationKey() localStore.setBoolean key, isList #-----------------------END TABLE/LIST VIEW SWITCHER------------------------ #--------------------------BEGIN META INFORMATION--------------------------- isMetaInfoVisible : -> return localStore.getBoolean localStore.keys.isMetaInfoVisible toogleMetaInfos: (event) -> jqObj = $(event.currentTarget) if jqObj.hasClass 'white-and-green' jqObj.removeClass('white-and-green') $('#results-meta-infos').hide() localStore.setBoolean localStore.keys.isMetaInfoVisible, false else jqObj.addClass('white-and-green') $('#results-meta-infos').show() localStore.setBoolean localStore.keys.isMetaInfoVisible, true #---------------------------END META INFORMATION --------------------------- #----------------------------BEGIN DELETE ALL------------------------------- switchStyleOfDeleteButton: (event) -> jqObj = $(event.currentTarget) if not jqObj.hasClass 'btn-danger' jqObj.addClass 'btn-danger' jqObj.children('span').text t('delete all') + ' ' else jqObj.removeClass 'btn-danger' jqObj.children('span').empty() confirmDeleteAll : (e) -> e.preventDefault() data = title: t 'confirmation required' body: t 'are you absolutely sure' confirm: t 'delete permanently' $("body").prepend @templateModal(data) $("#confirmation-dialog").modal() $("#confirmation-dialog").modal("show") $("#confirmation-dialog-confirm").unbind 'click' $("#confirmation-dialog-confirm").bind "click", => @deleteAll() deleteAll: -> if @currentDoctype? and @currentDoctype isnt '' deleteAllModel = new DeleteAllModel() deleteAllModel.fetch type: 'DELETE' url : deleteAllModel.urlRoot + '?' + $.param doctype : @currentDoctype success : (col, data) -> app.router.navigate 'search', replace: true trigger : true location.reload() #-----------------------------END DELETE ALL--------------------------------
[ { "context": "http://elving.github.com/swag/>\n Copyright 2012 Elving Rodriguez <http://elving.me/>\n Available under MIT licen", "end": 88, "score": 0.9998801350593567, "start": 72, "tag": "NAME", "value": "Elving Rodriguez" }, { "context": "lable under MIT license <https://ra...
src/swag.coffee
SBoudrias/swag
0
### Swag v0.2.6 <http://elving.github.com/swag/> Copyright 2012 Elving Rodriguez <http://elving.me/> Available under MIT license <https://raw.github.com/elving/swag/master/LICENSE> ### if window? Handlebars = window.Handlebars window.Swag = Swag = {} if module? Handlebars = require 'handlebars' module.exports = Swag = {}
129764
### Swag v0.2.6 <http://elving.github.com/swag/> Copyright 2012 <NAME> <http://elving.me/> Available under MIT license <https://raw.github.com/elving/swag/master/LICENSE> ### if window? Handlebars = window.Handlebars window.Swag = Swag = {} if module? Handlebars = require 'handlebars' module.exports = Swag = {}
true
### Swag v0.2.6 <http://elving.github.com/swag/> Copyright 2012 PI:NAME:<NAME>END_PI <http://elving.me/> Available under MIT license <https://raw.github.com/elving/swag/master/LICENSE> ### if window? Handlebars = window.Handlebars window.Swag = Swag = {} if module? Handlebars = require 'handlebars' module.exports = Swag = {}
[ { "context": "Wrap: true\n \"exception-reporting\":\n userId: \"623d3757-a301-4179-88ab-3798c281a688\"\n \"formatters-python\":\n autopep8:\n binPa", "end": 327, "score": 0.7546429634094238, "start": 292, "tag": "PASSWORD", "value": "23d3757-a301-4179-88ab-3798c281a688" }, {...
config.cson
tpaclatee/atom-setup-python
0
"*": Hydrogen: {} "autocomplete-python": useKite: false useSnippets: "all" core: disabledPackages: [ "kite" ] telemetryConsent: "limited" uriHandlerRegistration: "always" editor: fontSize: 15 softWrap: true "exception-reporting": userId: "623d3757-a301-4179-88ab-3798c281a688" "formatters-python": autopep8: binPath: "C:\\Users\\msalerno\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\autopep8.exe" black: binPath: "C:\\Users\\msalerno\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\black.exe" formatOrder: [ "yapf" "autopep8" "black" "isort" ] isort: binPath: "C:\\Users\\msalerno\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\isort.exe" cmdArgs: [ "--profile black --overwrite-in-place" ] onSave: saveOrder: [ "yapf" "autopep8" "black" "isort" ] yapf: binPath: "C:\\Users\\msalerno\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\isort.exe" "highlight-selected": highlightBackground: true lightTheme: true kite: showWelcomeNotificationOnStartup: false "linter-flake8": flakeErrors: true pycodestyleErrorsToWarnings: true "linter-ui-default": showPanel: true minimap: independentMinimapScroll: true moveCursorOnMinimapClick: true plugins: "git-diff": true "git-diffDecorationsZIndex": 0 "highlight-selected": true "highlight-selectedDecorationsZIndex": 0 scrollAnimation: true "python-autopep8": formatOnSave: true "python-black": {} welcome: {}
8167
"*": Hydrogen: {} "autocomplete-python": useKite: false useSnippets: "all" core: disabledPackages: [ "kite" ] telemetryConsent: "limited" uriHandlerRegistration: "always" editor: fontSize: 15 softWrap: true "exception-reporting": userId: "6<PASSWORD>" "formatters-python": autopep8: binPath: "C:\\Users\\msalerno\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\autopep8.exe" black: binPath: "C:\\Users\\msalerno\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\black.exe" formatOrder: [ "yapf" "autopep8" "black" "isort" ] isort: binPath: "C:\\Users\\msalerno\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\isort.exe" cmdArgs: [ "--profile black --overwrite-in-place" ] onSave: saveOrder: [ "yapf" "autopep8" "black" "isort" ] yapf: binPath: "C:\\Users\\msalerno\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\isort.exe" "highlight-selected": highlightBackground: true lightTheme: true kite: showWelcomeNotificationOnStartup: false "linter-flake8": flakeErrors: true pycodestyleErrorsToWarnings: true "linter-ui-default": showPanel: true minimap: independentMinimapScroll: true moveCursorOnMinimapClick: true plugins: "git-diff": true "git-diffDecorationsZIndex": 0 "highlight-selected": true "highlight-selectedDecorationsZIndex": 0 scrollAnimation: true "python-autopep8": formatOnSave: true "python-black": {} welcome: {}
true
"*": Hydrogen: {} "autocomplete-python": useKite: false useSnippets: "all" core: disabledPackages: [ "kite" ] telemetryConsent: "limited" uriHandlerRegistration: "always" editor: fontSize: 15 softWrap: true "exception-reporting": userId: "6PI:PASSWORD:<PASSWORD>END_PI" "formatters-python": autopep8: binPath: "C:\\Users\\msalerno\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\autopep8.exe" black: binPath: "C:\\Users\\msalerno\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\black.exe" formatOrder: [ "yapf" "autopep8" "black" "isort" ] isort: binPath: "C:\\Users\\msalerno\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\isort.exe" cmdArgs: [ "--profile black --overwrite-in-place" ] onSave: saveOrder: [ "yapf" "autopep8" "black" "isort" ] yapf: binPath: "C:\\Users\\msalerno\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\isort.exe" "highlight-selected": highlightBackground: true lightTheme: true kite: showWelcomeNotificationOnStartup: false "linter-flake8": flakeErrors: true pycodestyleErrorsToWarnings: true "linter-ui-default": showPanel: true minimap: independentMinimapScroll: true moveCursorOnMinimapClick: true plugins: "git-diff": true "git-diffDecorationsZIndex": 0 "highlight-selected": true "highlight-selectedDecorationsZIndex": 0 scrollAnimation: true "python-autopep8": formatOnSave: true "python-black": {} welcome: {}
[ { "context": "# TokenField\n#\n# Author: Bjarne Mogstad\n# Url: https://github.com/mogstad/token-field\n\ncl", "end": 39, "score": 0.9998869895935059, "start": 25, "tag": "NAME", "value": "Bjarne Mogstad" }, { "context": " Author: Bjarne Mogstad\n# Url: https://github.com/mogstad/tok...
lib/sensu-dashboard/assets/javascripts/libs/token.field.coffee
sensu-og/sensu-dashboard
14
# TokenField # # Author: Bjarne Mogstad # Url: https://github.com/mogstad/token-field class @TokenField extends Backbone.View tagName: "ul" className: "token-field" events: "blur input": -> @$el.removeClass("focus") @selectTokenAtIndex(Infinity) "focus input": -> @$el.addClass("focus") "click": -> @inputTester.focus() "click input": -> @selectTokenAtIndex(Infinity) "keyup input": "keyup" "keydown input": "keydown" "keypress input": "keypress" "mousedown ul li": (e) -> e.preventDefault() "click ul li": "clickToken" "click .close": "clickToCloseToken" initialize: (options = {}) -> super @selectedIndex = Infinity @tokens = [] @delegate = options.delegate render: -> @container = document.createElement("li") @container.className = "tokens" @textContent = document.createElement("span") @inputTester = document.createElement("input") @inputTester.setAttribute("placeholder", "Add filters...") @inputTester.setAttribute("autocorrect", "off") @inputTester.setAttribute("autocapitalize", "off") @inputTester.setAttribute("autocomplete", "off") @container.appendChild(@textContent) @container.appendChild(@inputTester) @el.appendChild(@container) return this insertToken: (object) -> token = @prepareObject(object) @el.insertBefore(token.node, @container) @tokens.push(token) prepareObject: (object) -> data = @delegate.visualisationForObject(object, this) if _.isString data node = document.createElement("li") node.innerHTML = data token = {object: object, node: node || data} return token tokenize: -> string = @inputTester.value object = @delegate.objectForString(string, this) @insertToken(object) @textContent.innerHTML = @inputTester.value = "" selectPreviousToken: -> if @selectedIndex < 1 return if @selectedIndex == Infinity @selectTokenAtIndex(@tokens.length - 1) else @selectTokenAtIndex(@selectedIndex - 1) selectNextToken: -> if @selectedIndex == Infinity return if @selectedIndex < @tokens.length - 1 @selectTokenAtIndex(@selectedIndex + 1) else @selectTokenAtIndex(Infinity) selectTokenAtIndex: (index) -> if @selectedIndex != Infinity $(@tokens[@selectedIndex].node).removeClass("selected") if index == Infinity @selectedIndex = Infinity @$el.removeClass("selected-token") return if 0 <= index < @tokens.length @selectedIndex = index @$el.addClass("selected-token") if @inputTester.value.length == 0 $(@tokens[@selectedIndex].node).addClass("selected") deleteTokenAtIndex: (index, deselect) -> if index < @tokens.length token = @tokens.splice(index, 1) @el.removeChild(token[0].node) if !deselect @selectedIndex = Infinity if @tokens.length @selectTokenAtIndex(Math.max(index - 1, 0)) else @selectTokenAtIndex(Infinity) clickToken: (e) -> e.stopPropagation() target = e.currentTarget if (index = @_indexForTarget(target)) >= 0 @selectTokenAtIndex(index) @inputTester.focus() clickToCloseToken: (e) -> e.stopPropagation() target = $(e.currentTarget).closest("li")[0] return if (index = @_indexForTarget(target)) < 0 @deleteTokenAtIndex(index, true) return if @selectedIndex == Infinity if @tokens.length == 0 @selectedIndex = Infinity @selectTokenAtIndex(Infinity) return if index <= @selectedIndex @selectedIndex = Math.max(index - 1, 0) return _indexForTarget: (target) -> for token, index in @tokens when target == token.node return index keyup: (e) -> @textContent.innerHTML = @inputTester.value switch e.keyCode when 13 @tokenize() keydown: (e) -> switch e.keyCode when 8 # Backspace if @selectedIndex != Infinity @deleteTokenAtIndex(@selectedIndex) e.preventDefault() else if @inputTester.selectionStart == 0 && @inputTester.selectionEnd == 0 @selectTokenAtIndex(@tokens.length - 1) e.preventDefault() when 37 # Left arrow if @inputTester.selectionStart == 0 || @selectedIndex != Infinity e.preventDefault() @selectPreviousToken() when 39 # Right arrow if @selectedIndex != Infinity e.preventDefault() @selectNextToken() keypress: (e) -> if @selectedIndex != Infinity @deleteTokenAtIndex(@selectedIndex, true) @selectedIndex = Infinity @selectTokenAtIndex(Infinity)
40312
# TokenField # # Author: <NAME> # Url: https://github.com/mogstad/token-field class @TokenField extends Backbone.View tagName: "ul" className: "token-field" events: "blur input": -> @$el.removeClass("focus") @selectTokenAtIndex(Infinity) "focus input": -> @$el.addClass("focus") "click": -> @inputTester.focus() "click input": -> @selectTokenAtIndex(Infinity) "keyup input": "keyup" "keydown input": "keydown" "keypress input": "keypress" "mousedown ul li": (e) -> e.preventDefault() "click ul li": "clickToken" "click .close": "clickToCloseToken" initialize: (options = {}) -> super @selectedIndex = Infinity @tokens = [] @delegate = options.delegate render: -> @container = document.createElement("li") @container.className = "tokens" @textContent = document.createElement("span") @inputTester = document.createElement("input") @inputTester.setAttribute("placeholder", "Add filters...") @inputTester.setAttribute("autocorrect", "off") @inputTester.setAttribute("autocapitalize", "off") @inputTester.setAttribute("autocomplete", "off") @container.appendChild(@textContent) @container.appendChild(@inputTester) @el.appendChild(@container) return this insertToken: (object) -> token = @prepareObject(object) @el.insertBefore(token.node, @container) @tokens.push(token) prepareObject: (object) -> data = @delegate.visualisationForObject(object, this) if _.isString data node = document.createElement("li") node.innerHTML = data token = {object: object, node: node || data} return token tokenize: -> string = @inputTester.value object = @delegate.objectForString(string, this) @insertToken(object) @textContent.innerHTML = @inputTester.value = "" selectPreviousToken: -> if @selectedIndex < 1 return if @selectedIndex == Infinity @selectTokenAtIndex(@tokens.length - 1) else @selectTokenAtIndex(@selectedIndex - 1) selectNextToken: -> if @selectedIndex == Infinity return if @selectedIndex < @tokens.length - 1 @selectTokenAtIndex(@selectedIndex + 1) else @selectTokenAtIndex(Infinity) selectTokenAtIndex: (index) -> if @selectedIndex != Infinity $(@tokens[@selectedIndex].node).removeClass("selected") if index == Infinity @selectedIndex = Infinity @$el.removeClass("selected-token") return if 0 <= index < @tokens.length @selectedIndex = index @$el.addClass("selected-token") if @inputTester.value.length == 0 $(@tokens[@selectedIndex].node).addClass("selected") deleteTokenAtIndex: (index, deselect) -> if index < @tokens.length token = @tokens.splice(index, 1) @el.removeChild(token[0].node) if !deselect @selectedIndex = Infinity if @tokens.length @selectTokenAtIndex(Math.max(index - 1, 0)) else @selectTokenAtIndex(Infinity) clickToken: (e) -> e.stopPropagation() target = e.currentTarget if (index = @_indexForTarget(target)) >= 0 @selectTokenAtIndex(index) @inputTester.focus() clickToCloseToken: (e) -> e.stopPropagation() target = $(e.currentTarget).closest("li")[0] return if (index = @_indexForTarget(target)) < 0 @deleteTokenAtIndex(index, true) return if @selectedIndex == Infinity if @tokens.length == 0 @selectedIndex = Infinity @selectTokenAtIndex(Infinity) return if index <= @selectedIndex @selectedIndex = Math.max(index - 1, 0) return _indexForTarget: (target) -> for token, index in @tokens when target == token.node return index keyup: (e) -> @textContent.innerHTML = @inputTester.value switch e.keyCode when 13 @tokenize() keydown: (e) -> switch e.keyCode when 8 # Backspace if @selectedIndex != Infinity @deleteTokenAtIndex(@selectedIndex) e.preventDefault() else if @inputTester.selectionStart == 0 && @inputTester.selectionEnd == 0 @selectTokenAtIndex(@tokens.length - 1) e.preventDefault() when 37 # Left arrow if @inputTester.selectionStart == 0 || @selectedIndex != Infinity e.preventDefault() @selectPreviousToken() when 39 # Right arrow if @selectedIndex != Infinity e.preventDefault() @selectNextToken() keypress: (e) -> if @selectedIndex != Infinity @deleteTokenAtIndex(@selectedIndex, true) @selectedIndex = Infinity @selectTokenAtIndex(Infinity)
true
# TokenField # # Author: PI:NAME:<NAME>END_PI # Url: https://github.com/mogstad/token-field class @TokenField extends Backbone.View tagName: "ul" className: "token-field" events: "blur input": -> @$el.removeClass("focus") @selectTokenAtIndex(Infinity) "focus input": -> @$el.addClass("focus") "click": -> @inputTester.focus() "click input": -> @selectTokenAtIndex(Infinity) "keyup input": "keyup" "keydown input": "keydown" "keypress input": "keypress" "mousedown ul li": (e) -> e.preventDefault() "click ul li": "clickToken" "click .close": "clickToCloseToken" initialize: (options = {}) -> super @selectedIndex = Infinity @tokens = [] @delegate = options.delegate render: -> @container = document.createElement("li") @container.className = "tokens" @textContent = document.createElement("span") @inputTester = document.createElement("input") @inputTester.setAttribute("placeholder", "Add filters...") @inputTester.setAttribute("autocorrect", "off") @inputTester.setAttribute("autocapitalize", "off") @inputTester.setAttribute("autocomplete", "off") @container.appendChild(@textContent) @container.appendChild(@inputTester) @el.appendChild(@container) return this insertToken: (object) -> token = @prepareObject(object) @el.insertBefore(token.node, @container) @tokens.push(token) prepareObject: (object) -> data = @delegate.visualisationForObject(object, this) if _.isString data node = document.createElement("li") node.innerHTML = data token = {object: object, node: node || data} return token tokenize: -> string = @inputTester.value object = @delegate.objectForString(string, this) @insertToken(object) @textContent.innerHTML = @inputTester.value = "" selectPreviousToken: -> if @selectedIndex < 1 return if @selectedIndex == Infinity @selectTokenAtIndex(@tokens.length - 1) else @selectTokenAtIndex(@selectedIndex - 1) selectNextToken: -> if @selectedIndex == Infinity return if @selectedIndex < @tokens.length - 1 @selectTokenAtIndex(@selectedIndex + 1) else @selectTokenAtIndex(Infinity) selectTokenAtIndex: (index) -> if @selectedIndex != Infinity $(@tokens[@selectedIndex].node).removeClass("selected") if index == Infinity @selectedIndex = Infinity @$el.removeClass("selected-token") return if 0 <= index < @tokens.length @selectedIndex = index @$el.addClass("selected-token") if @inputTester.value.length == 0 $(@tokens[@selectedIndex].node).addClass("selected") deleteTokenAtIndex: (index, deselect) -> if index < @tokens.length token = @tokens.splice(index, 1) @el.removeChild(token[0].node) if !deselect @selectedIndex = Infinity if @tokens.length @selectTokenAtIndex(Math.max(index - 1, 0)) else @selectTokenAtIndex(Infinity) clickToken: (e) -> e.stopPropagation() target = e.currentTarget if (index = @_indexForTarget(target)) >= 0 @selectTokenAtIndex(index) @inputTester.focus() clickToCloseToken: (e) -> e.stopPropagation() target = $(e.currentTarget).closest("li")[0] return if (index = @_indexForTarget(target)) < 0 @deleteTokenAtIndex(index, true) return if @selectedIndex == Infinity if @tokens.length == 0 @selectedIndex = Infinity @selectTokenAtIndex(Infinity) return if index <= @selectedIndex @selectedIndex = Math.max(index - 1, 0) return _indexForTarget: (target) -> for token, index in @tokens when target == token.node return index keyup: (e) -> @textContent.innerHTML = @inputTester.value switch e.keyCode when 13 @tokenize() keydown: (e) -> switch e.keyCode when 8 # Backspace if @selectedIndex != Infinity @deleteTokenAtIndex(@selectedIndex) e.preventDefault() else if @inputTester.selectionStart == 0 && @inputTester.selectionEnd == 0 @selectTokenAtIndex(@tokens.length - 1) e.preventDefault() when 37 # Left arrow if @inputTester.selectionStart == 0 || @selectedIndex != Infinity e.preventDefault() @selectPreviousToken() when 39 # Right arrow if @selectedIndex != Infinity e.preventDefault() @selectNextToken() keypress: (e) -> if @selectedIndex != Infinity @deleteTokenAtIndex(@selectedIndex, true) @selectedIndex = Infinity @selectTokenAtIndex(Infinity)
[ { "context": " the round-robin DNS case.\", (done)->\n ips = ['17.172.224.35', '17.178.96.29', '17.142.160.29']\n NetUtil.re", "end": 1451, "score": 0.999725878238678, "start": 1438, "tag": "IP_ADDRESS", "value": "17.172.224.35" }, { "context": "DNS case.\", (done)->\n ips =...
test/test-net-util.coffee
intellinote/inote-util
1
require 'coffee-errors' #------------------------------------------------------------------------------# assert = require 'assert' should = require 'should' fs = require 'fs' path = require 'path' HOME_DIR = path.join(__dirname,'..') LIB_COV = path.join(HOME_DIR,'lib-cov') LIB_DIR = if fs.existsSync(LIB_COV) then LIB_COV else path.join(HOME_DIR,'lib') NetUtil = require(path.join(LIB_DIR,'net-util')).NetUtil describe 'NetUtil',-> it "can get the current pid",(done)=> (typeof NetUtil.get_pid()).should.equal "number" done() it "can get a random port in the given range",(done)=> port = NetUtil.random_port(2000,100) port.should.not.be.below 2000 port.should.not.be.above 2100 done() # it "can get an unused port",(done)=> # port = NetUtil.get_unused_port() # (typeof port).should.equal "number" # NetUtil.is_port_in_use port, (err, in_use)=> # should.not.exist err # in_use.should.equal false # done() # port.should.not.be.below 2000 it "resolve_hostname calls-back with an error if the hostname does not resolve", (done)-> NetUtil.resolve_hostname 'itunesssssss.com', (err, res)-> assert err?.code is 'ENOTFOUND' assert not res? done() # this is a brittle test - since the host address for itunes can change any time it "resolve_hostname returns a working IP address in the round-robin DNS case.", (done)-> ips = ['17.172.224.35', '17.178.96.29', '17.142.160.29'] NetUtil.resolve_hostname 'itunes.com', (err,res)-> assert.ok not err?, err assert.equal res in ips, true, 'address mismatch' assert.ok NetUtil._dns_resolve_cache?["itunes.com"]?.expires_at? assert.ok NetUtil._dns_resolve_cache?["itunes.com"]?.ips? NetUtil.clear_resolve_hostname_cache("not.itunes.com") assert.ok NetUtil._dns_resolve_cache?["itunes.com"]?.expires_at? assert.ok NetUtil._dns_resolve_cache?["itunes.com"]?.ips? NetUtil.clear_resolve_hostname_cache() assert.ok not NetUtil._dns_resolve_cache?["itunes.com"]?.expires_at? assert.ok not NetUtil._dns_resolve_cache?["itunes.com"]?.ips? done() it "resolve_hostname returns an IP address in the single-entry DNS case.", (done)-> NetUtil.resolve_hostname 'www.team-one.com', (err,res)-> assert.ok not err?, err assert.ok /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/.test res done()
128978
require 'coffee-errors' #------------------------------------------------------------------------------# assert = require 'assert' should = require 'should' fs = require 'fs' path = require 'path' HOME_DIR = path.join(__dirname,'..') LIB_COV = path.join(HOME_DIR,'lib-cov') LIB_DIR = if fs.existsSync(LIB_COV) then LIB_COV else path.join(HOME_DIR,'lib') NetUtil = require(path.join(LIB_DIR,'net-util')).NetUtil describe 'NetUtil',-> it "can get the current pid",(done)=> (typeof NetUtil.get_pid()).should.equal "number" done() it "can get a random port in the given range",(done)=> port = NetUtil.random_port(2000,100) port.should.not.be.below 2000 port.should.not.be.above 2100 done() # it "can get an unused port",(done)=> # port = NetUtil.get_unused_port() # (typeof port).should.equal "number" # NetUtil.is_port_in_use port, (err, in_use)=> # should.not.exist err # in_use.should.equal false # done() # port.should.not.be.below 2000 it "resolve_hostname calls-back with an error if the hostname does not resolve", (done)-> NetUtil.resolve_hostname 'itunesssssss.com', (err, res)-> assert err?.code is 'ENOTFOUND' assert not res? done() # this is a brittle test - since the host address for itunes can change any time it "resolve_hostname returns a working IP address in the round-robin DNS case.", (done)-> ips = ['172.16.31.10', '172.16.31.10', '192.168.127.12'] NetUtil.resolve_hostname 'itunes.com', (err,res)-> assert.ok not err?, err assert.equal res in ips, true, 'address mismatch' assert.ok NetUtil._dns_resolve_cache?["itunes.com"]?.expires_at? assert.ok NetUtil._dns_resolve_cache?["itunes.com"]?.ips? NetUtil.clear_resolve_hostname_cache("not.itunes.com") assert.ok NetUtil._dns_resolve_cache?["itunes.com"]?.expires_at? assert.ok NetUtil._dns_resolve_cache?["itunes.com"]?.ips? NetUtil.clear_resolve_hostname_cache() assert.ok not NetUtil._dns_resolve_cache?["itunes.com"]?.expires_at? assert.ok not NetUtil._dns_resolve_cache?["itunes.com"]?.ips? done() it "resolve_hostname returns an IP address in the single-entry DNS case.", (done)-> NetUtil.resolve_hostname 'www.team-one.com', (err,res)-> assert.ok not err?, err assert.ok /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/.test res done()
true
require 'coffee-errors' #------------------------------------------------------------------------------# assert = require 'assert' should = require 'should' fs = require 'fs' path = require 'path' HOME_DIR = path.join(__dirname,'..') LIB_COV = path.join(HOME_DIR,'lib-cov') LIB_DIR = if fs.existsSync(LIB_COV) then LIB_COV else path.join(HOME_DIR,'lib') NetUtil = require(path.join(LIB_DIR,'net-util')).NetUtil describe 'NetUtil',-> it "can get the current pid",(done)=> (typeof NetUtil.get_pid()).should.equal "number" done() it "can get a random port in the given range",(done)=> port = NetUtil.random_port(2000,100) port.should.not.be.below 2000 port.should.not.be.above 2100 done() # it "can get an unused port",(done)=> # port = NetUtil.get_unused_port() # (typeof port).should.equal "number" # NetUtil.is_port_in_use port, (err, in_use)=> # should.not.exist err # in_use.should.equal false # done() # port.should.not.be.below 2000 it "resolve_hostname calls-back with an error if the hostname does not resolve", (done)-> NetUtil.resolve_hostname 'itunesssssss.com', (err, res)-> assert err?.code is 'ENOTFOUND' assert not res? done() # this is a brittle test - since the host address for itunes can change any time it "resolve_hostname returns a working IP address in the round-robin DNS case.", (done)-> ips = ['PI:IP_ADDRESS:172.16.31.10END_PI', 'PI:IP_ADDRESS:172.16.31.10END_PI', 'PI:IP_ADDRESS:192.168.127.12END_PI'] NetUtil.resolve_hostname 'itunes.com', (err,res)-> assert.ok not err?, err assert.equal res in ips, true, 'address mismatch' assert.ok NetUtil._dns_resolve_cache?["itunes.com"]?.expires_at? assert.ok NetUtil._dns_resolve_cache?["itunes.com"]?.ips? NetUtil.clear_resolve_hostname_cache("not.itunes.com") assert.ok NetUtil._dns_resolve_cache?["itunes.com"]?.expires_at? assert.ok NetUtil._dns_resolve_cache?["itunes.com"]?.ips? NetUtil.clear_resolve_hostname_cache() assert.ok not NetUtil._dns_resolve_cache?["itunes.com"]?.expires_at? assert.ok not NetUtil._dns_resolve_cache?["itunes.com"]?.ips? done() it "resolve_hostname returns an IP address in the single-entry DNS case.", (done)-> NetUtil.resolve_hostname 'www.team-one.com', (err,res)-> assert.ok not err?, err assert.ok /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/.test res done()
[ { "context": " passed data', ->\n data1 = 12\n data2 = 'tasty cake'\n\n el1 = list.add(data1)\n el2 ", "end": 419, "score": 0.5425951480865479, "start": 418, "tag": "PASSWORD", "value": "t" } ]
test/linkedlist.coffee
VincentToups/Kran
0
Llist = require('../kran').LinkedList describe 'linked list', -> list = null beforeEach -> list = new Llist() it 'should construct an object', -> list.should.be.an('object') it 'should make it possible to add list elements', -> el = list.add() el.should.be.an('object') describe 'a linked list element', -> it 'should give access to passed data', -> data1 = 12 data2 = 'tasty cake' el1 = list.add(data1) el2 = list.add(data2) el1.data.should.equal(data1) el2.data.should.equal(data2) it 'should point to previous and next elements', -> el1 = list.add() el2 = list.add() el3 = list.add() should.not.exist(el1.prev) el1.next.should.equal(el2) el2.prev.should.equal(el1) el2.next.should.equal(el3) el3.prev.should.equal(el2) should.not.exist(el3.next) it 'should be removeable', -> el1 = list.add() el2 = list.add() el3 = list.add() el2.remove() el1.next.should.equal(el3) el3.prev.should.equal(el1) it 'should point to the first added element', -> el = list.add() list.add() list.head.should.equal(el) it 'have both tail and head points to the same when there is only one', -> el = list.add() list.head.should.equal(el) list.tail.should.equal(el) it 'should still point to first element after removals', -> el1 = list.add() el2 = list.add() list.head.should.equal(el1) el1.remove() list.head.should.equal(el2) el2.remove() should.not.exist(list.head) it 'should point to the last added element', -> list.add() el = list.add() list.tail.should.equal(el) it 'should still point to last element after removals', -> el1 = list.add() el2 = list.add() list.tail.should.equal(el2) el2.remove() list.tail.should.equal(el1) el1.remove() should.not.exist(list.tail) it 'should allow for executing a function for every item', -> el1 = list.add() el2 = list.add() el3 = list.add() spy = sinon.spy() list.forEach(spy) spy.should.have.been.calledThrice
85973
Llist = require('../kran').LinkedList describe 'linked list', -> list = null beforeEach -> list = new Llist() it 'should construct an object', -> list.should.be.an('object') it 'should make it possible to add list elements', -> el = list.add() el.should.be.an('object') describe 'a linked list element', -> it 'should give access to passed data', -> data1 = 12 data2 = '<PASSWORD>asty cake' el1 = list.add(data1) el2 = list.add(data2) el1.data.should.equal(data1) el2.data.should.equal(data2) it 'should point to previous and next elements', -> el1 = list.add() el2 = list.add() el3 = list.add() should.not.exist(el1.prev) el1.next.should.equal(el2) el2.prev.should.equal(el1) el2.next.should.equal(el3) el3.prev.should.equal(el2) should.not.exist(el3.next) it 'should be removeable', -> el1 = list.add() el2 = list.add() el3 = list.add() el2.remove() el1.next.should.equal(el3) el3.prev.should.equal(el1) it 'should point to the first added element', -> el = list.add() list.add() list.head.should.equal(el) it 'have both tail and head points to the same when there is only one', -> el = list.add() list.head.should.equal(el) list.tail.should.equal(el) it 'should still point to first element after removals', -> el1 = list.add() el2 = list.add() list.head.should.equal(el1) el1.remove() list.head.should.equal(el2) el2.remove() should.not.exist(list.head) it 'should point to the last added element', -> list.add() el = list.add() list.tail.should.equal(el) it 'should still point to last element after removals', -> el1 = list.add() el2 = list.add() list.tail.should.equal(el2) el2.remove() list.tail.should.equal(el1) el1.remove() should.not.exist(list.tail) it 'should allow for executing a function for every item', -> el1 = list.add() el2 = list.add() el3 = list.add() spy = sinon.spy() list.forEach(spy) spy.should.have.been.calledThrice
true
Llist = require('../kran').LinkedList describe 'linked list', -> list = null beforeEach -> list = new Llist() it 'should construct an object', -> list.should.be.an('object') it 'should make it possible to add list elements', -> el = list.add() el.should.be.an('object') describe 'a linked list element', -> it 'should give access to passed data', -> data1 = 12 data2 = 'PI:PASSWORD:<PASSWORD>END_PIasty cake' el1 = list.add(data1) el2 = list.add(data2) el1.data.should.equal(data1) el2.data.should.equal(data2) it 'should point to previous and next elements', -> el1 = list.add() el2 = list.add() el3 = list.add() should.not.exist(el1.prev) el1.next.should.equal(el2) el2.prev.should.equal(el1) el2.next.should.equal(el3) el3.prev.should.equal(el2) should.not.exist(el3.next) it 'should be removeable', -> el1 = list.add() el2 = list.add() el3 = list.add() el2.remove() el1.next.should.equal(el3) el3.prev.should.equal(el1) it 'should point to the first added element', -> el = list.add() list.add() list.head.should.equal(el) it 'have both tail and head points to the same when there is only one', -> el = list.add() list.head.should.equal(el) list.tail.should.equal(el) it 'should still point to first element after removals', -> el1 = list.add() el2 = list.add() list.head.should.equal(el1) el1.remove() list.head.should.equal(el2) el2.remove() should.not.exist(list.head) it 'should point to the last added element', -> list.add() el = list.add() list.tail.should.equal(el) it 'should still point to last element after removals', -> el1 = list.add() el2 = list.add() list.tail.should.equal(el2) el2.remove() list.tail.should.equal(el1) el1.remove() should.not.exist(list.tail) it 'should allow for executing a function for every item', -> el1 = list.add() el2 = list.add() el3 = list.add() spy = sinon.spy() list.forEach(spy) spy.should.have.been.calledThrice
[ { "context": "action: spy\n\n\t\t\tcliManager.execute command: 'hello John', (error) ->\n\t\t\t\texpect(error).to.not.exist\n\t\t\t\te", "end": 3039, "score": 0.9887856841087341, "start": 3035, "tag": "NAME", "value": "John" }, { "context": "ce\n\t\t\t\texpect(spy).to.have.been.calle...
tests/capitano.spec.coffee
resin-io/capitano
19
_ = require('lodash') sinon = require('sinon') chai = require('chai') chai.use(require('sinon-chai')) expect = chai.expect cliManager = require('../lib/capitano') utils = require('../lib/utils') describe 'Capitano:', -> beforeEach -> cliManager.state.commands = [] cliManager.state.globalOptions = [] cliManager.state.permissions = {} describe '#permission()', -> it 'should throw an error if no name', -> expect -> cliManager.permission() .to.throw('Missing permission name') it 'should throw an error if name is not a string', -> expect -> cliManager.permission([ 'permissions' ]) .to.throw('Invalid permission name') it 'should throw an error if no function', -> expect -> cliManager.permission('hello') .to.throw('Missing permission function') it 'should throw an error if function is not a function', -> expect -> cliManager.permission('name', [ 'function' ]) .to.throw('Invalid permission function') it 'should add a permissions', -> expect(cliManager.state.permissions.user).to.not.exist cliManager.permission('user', _.noop) expect(cliManager.state.permissions.user).to.exist expect(cliManager.state.permissions.user).to.equal(_.noop) describe '#command()', -> it 'should add a command', -> expect(cliManager.state.commands).to.have.length(0) cliManager.command signature: 'hello <name>' action: _.noop expect(cliManager.state.commands).to.have.length(1) command = cliManager.state.commands[0] expect(command.signature.toString()).to.equal('hello <name>') it 'should add a command with options', -> expect -> cliManager.command signature: 'hello <name>' action: _.noop options: [ { signature: 'quiet' boolean: true } { signature: 'yes' boolean: true } ] .to.not.throw(Error) commandOptions = cliManager.state.commands[0].options expect(commandOptions[0].signature.toString()).to.equal('quiet') expect(commandOptions[1].signature.toString()).to.equal('yes') # Caused by command() modifying the original object it 'should allow using the same option object multiple times', -> yesOption = signature: 'yes' boolean: true cliManager.command signature: 'foo <bar>' action: _.noop options: [ yesOption ] expect -> cliManager.command signature: 'hello <name>' action: _.noop options: [ yesOption ] .to.not.throw(Error) describe '#option()', -> it 'should add an option', -> expect(cliManager.state.globalOptions).to.have.length(0) cliManager.globalOption signature: 'quiet' boolean: true expect(cliManager.state.globalOptions).to.have.length(1) option = cliManager.state.globalOptions[0] expect(option.signature.toString()).to.equal('quiet') describe '#execute()', -> it 'should execute a command', (done) -> spy = sinon.spy() cliManager.command signature: 'hello <name>' action: spy cliManager.execute command: 'hello John', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith(name: 'John') done() it 'should call commandNotFound if command not found', -> commandNotFoundStub = sinon.stub(cliManager.defaults.actions, 'commandNotFound') cliManager.execute(command: 'not valid command') expect(commandNotFoundStub).to.have.been.called expect(commandNotFoundStub).to.have.been.calledWith('not valid command') commandNotFoundStub.restore() it 'should return an error if there was an error executing the command', (done) -> commandNotFoundStub = sinon.stub(cliManager.defaults.actions, 'commandNotFound') cliManager.command signature: 'hello <name>' action: _.noop cliManager.execute command: 'hello', (error) -> expect(error).to.be.an.instanceof(Error) expect(error.message).to.equal('Missing name') commandNotFoundStub.restore() done() it 'should pass an execution error to the default handler', (done) -> actionError = new Error('action error') cliManager.command signature: 'hello' action: (params, options, callback) -> return callback(actionError) cliManager.execute command: 'hello', (error) -> expect(error).to.deep.equal(actionError) done() it 'should pass an async execution error to the default handler', (done) -> actionError = new Error('action error') cliManager.command signature: 'hello' action: (params, options, callback) -> setTimeout -> return callback(actionError) , 1 cliManager.execute command: 'hello', (error) -> expect(error).to.deep.equal(actionError) done() it 'should not throw an error if missing callback', -> cliManager.command signature: 'hello' action: (params, options, callback) -> return callback(actionError) expect -> cliManager.execute(command: 'hello') .to.not.throw(Error) describe 'given a stdin command', -> describe 'if parameter was passed', -> it 'should execute correctly', (done) -> spy = sinon.spy() cliManager.command signature: 'hello <|name>' action: spy cliManager.execute command: 'hello John', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith(name: 'John') done() describe 'if stdin was passed', -> beforeEach -> @utilsGetStdinStub = sinon.stub(utils, 'getStdin') @utilsGetStdinStub.callsArgWithAsync(0, 'Jane') afterEach -> @utilsGetStdinStub.restore() it 'should execute correctly', (done) -> spy = sinon.spy() cliManager.command signature: 'hello <|name>' action: spy cliManager.execute command: 'hello', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith(name: 'Jane') done() describe '#run()', -> it 'should parse and execute a command', (done) -> spy = sinon.spy() cliManager.command signature: 'hello <name>' action: spy cliManager.run 'hello John', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith(name: 'John') done() it 'should pass an option value starting with a number correctly', (done) -> spy = sinon.spy() cliManager.command signature: 'hello' action: spy options: [ signature: 'application' parameter: 'application' ] cliManager.run 'hello --application 10Jun2014', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith({}, application: '10Jun2014') done() it 'should pass any error to the callback', (done) -> cliManager.command signature: 'hello <name>' action: (params, options, callback) -> return callback(new Error()) cliManager.run 'hello', (error) -> expect(error).to.be.an.instanceof(Error) expect(error.message).to.equal('Missing name') done()
189103
_ = require('lodash') sinon = require('sinon') chai = require('chai') chai.use(require('sinon-chai')) expect = chai.expect cliManager = require('../lib/capitano') utils = require('../lib/utils') describe 'Capitano:', -> beforeEach -> cliManager.state.commands = [] cliManager.state.globalOptions = [] cliManager.state.permissions = {} describe '#permission()', -> it 'should throw an error if no name', -> expect -> cliManager.permission() .to.throw('Missing permission name') it 'should throw an error if name is not a string', -> expect -> cliManager.permission([ 'permissions' ]) .to.throw('Invalid permission name') it 'should throw an error if no function', -> expect -> cliManager.permission('hello') .to.throw('Missing permission function') it 'should throw an error if function is not a function', -> expect -> cliManager.permission('name', [ 'function' ]) .to.throw('Invalid permission function') it 'should add a permissions', -> expect(cliManager.state.permissions.user).to.not.exist cliManager.permission('user', _.noop) expect(cliManager.state.permissions.user).to.exist expect(cliManager.state.permissions.user).to.equal(_.noop) describe '#command()', -> it 'should add a command', -> expect(cliManager.state.commands).to.have.length(0) cliManager.command signature: 'hello <name>' action: _.noop expect(cliManager.state.commands).to.have.length(1) command = cliManager.state.commands[0] expect(command.signature.toString()).to.equal('hello <name>') it 'should add a command with options', -> expect -> cliManager.command signature: 'hello <name>' action: _.noop options: [ { signature: 'quiet' boolean: true } { signature: 'yes' boolean: true } ] .to.not.throw(Error) commandOptions = cliManager.state.commands[0].options expect(commandOptions[0].signature.toString()).to.equal('quiet') expect(commandOptions[1].signature.toString()).to.equal('yes') # Caused by command() modifying the original object it 'should allow using the same option object multiple times', -> yesOption = signature: 'yes' boolean: true cliManager.command signature: 'foo <bar>' action: _.noop options: [ yesOption ] expect -> cliManager.command signature: 'hello <name>' action: _.noop options: [ yesOption ] .to.not.throw(Error) describe '#option()', -> it 'should add an option', -> expect(cliManager.state.globalOptions).to.have.length(0) cliManager.globalOption signature: 'quiet' boolean: true expect(cliManager.state.globalOptions).to.have.length(1) option = cliManager.state.globalOptions[0] expect(option.signature.toString()).to.equal('quiet') describe '#execute()', -> it 'should execute a command', (done) -> spy = sinon.spy() cliManager.command signature: 'hello <name>' action: spy cliManager.execute command: 'hello <NAME>', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith(name: '<NAME>') done() it 'should call commandNotFound if command not found', -> commandNotFoundStub = sinon.stub(cliManager.defaults.actions, 'commandNotFound') cliManager.execute(command: 'not valid command') expect(commandNotFoundStub).to.have.been.called expect(commandNotFoundStub).to.have.been.calledWith('not valid command') commandNotFoundStub.restore() it 'should return an error if there was an error executing the command', (done) -> commandNotFoundStub = sinon.stub(cliManager.defaults.actions, 'commandNotFound') cliManager.command signature: 'hello <name>' action: _.noop cliManager.execute command: 'hello', (error) -> expect(error).to.be.an.instanceof(Error) expect(error.message).to.equal('Missing name') commandNotFoundStub.restore() done() it 'should pass an execution error to the default handler', (done) -> actionError = new Error('action error') cliManager.command signature: 'hello' action: (params, options, callback) -> return callback(actionError) cliManager.execute command: 'hello', (error) -> expect(error).to.deep.equal(actionError) done() it 'should pass an async execution error to the default handler', (done) -> actionError = new Error('action error') cliManager.command signature: 'hello' action: (params, options, callback) -> setTimeout -> return callback(actionError) , 1 cliManager.execute command: 'hello', (error) -> expect(error).to.deep.equal(actionError) done() it 'should not throw an error if missing callback', -> cliManager.command signature: 'hello' action: (params, options, callback) -> return callback(actionError) expect -> cliManager.execute(command: 'hello') .to.not.throw(Error) describe 'given a stdin command', -> describe 'if parameter was passed', -> it 'should execute correctly', (done) -> spy = sinon.spy() cliManager.command signature: 'hello <|name>' action: spy cliManager.execute command: 'hello <NAME>', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith(name: '<NAME>') done() describe 'if stdin was passed', -> beforeEach -> @utilsGetStdinStub = sinon.stub(utils, 'getStdin') @utilsGetStdinStub.callsArgWithAsync(0, '<NAME>') afterEach -> @utilsGetStdinStub.restore() it 'should execute correctly', (done) -> spy = sinon.spy() cliManager.command signature: 'hello <|name>' action: spy cliManager.execute command: 'hello', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith(name: '<NAME>') done() describe '#run()', -> it 'should parse and execute a command', (done) -> spy = sinon.spy() cliManager.command signature: 'hello <name>' action: spy cliManager.run 'hello <NAME>', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith(name: '<NAME>') done() it 'should pass an option value starting with a number correctly', (done) -> spy = sinon.spy() cliManager.command signature: 'hello' action: spy options: [ signature: 'application' parameter: 'application' ] cliManager.run 'hello --application 10Jun2014', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith({}, application: '10Jun2014') done() it 'should pass any error to the callback', (done) -> cliManager.command signature: 'hello <name>' action: (params, options, callback) -> return callback(new Error()) cliManager.run 'hello', (error) -> expect(error).to.be.an.instanceof(Error) expect(error.message).to.equal('Missing name') done()
true
_ = require('lodash') sinon = require('sinon') chai = require('chai') chai.use(require('sinon-chai')) expect = chai.expect cliManager = require('../lib/capitano') utils = require('../lib/utils') describe 'Capitano:', -> beforeEach -> cliManager.state.commands = [] cliManager.state.globalOptions = [] cliManager.state.permissions = {} describe '#permission()', -> it 'should throw an error if no name', -> expect -> cliManager.permission() .to.throw('Missing permission name') it 'should throw an error if name is not a string', -> expect -> cliManager.permission([ 'permissions' ]) .to.throw('Invalid permission name') it 'should throw an error if no function', -> expect -> cliManager.permission('hello') .to.throw('Missing permission function') it 'should throw an error if function is not a function', -> expect -> cliManager.permission('name', [ 'function' ]) .to.throw('Invalid permission function') it 'should add a permissions', -> expect(cliManager.state.permissions.user).to.not.exist cliManager.permission('user', _.noop) expect(cliManager.state.permissions.user).to.exist expect(cliManager.state.permissions.user).to.equal(_.noop) describe '#command()', -> it 'should add a command', -> expect(cliManager.state.commands).to.have.length(0) cliManager.command signature: 'hello <name>' action: _.noop expect(cliManager.state.commands).to.have.length(1) command = cliManager.state.commands[0] expect(command.signature.toString()).to.equal('hello <name>') it 'should add a command with options', -> expect -> cliManager.command signature: 'hello <name>' action: _.noop options: [ { signature: 'quiet' boolean: true } { signature: 'yes' boolean: true } ] .to.not.throw(Error) commandOptions = cliManager.state.commands[0].options expect(commandOptions[0].signature.toString()).to.equal('quiet') expect(commandOptions[1].signature.toString()).to.equal('yes') # Caused by command() modifying the original object it 'should allow using the same option object multiple times', -> yesOption = signature: 'yes' boolean: true cliManager.command signature: 'foo <bar>' action: _.noop options: [ yesOption ] expect -> cliManager.command signature: 'hello <name>' action: _.noop options: [ yesOption ] .to.not.throw(Error) describe '#option()', -> it 'should add an option', -> expect(cliManager.state.globalOptions).to.have.length(0) cliManager.globalOption signature: 'quiet' boolean: true expect(cliManager.state.globalOptions).to.have.length(1) option = cliManager.state.globalOptions[0] expect(option.signature.toString()).to.equal('quiet') describe '#execute()', -> it 'should execute a command', (done) -> spy = sinon.spy() cliManager.command signature: 'hello <name>' action: spy cliManager.execute command: 'hello PI:NAME:<NAME>END_PI', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith(name: 'PI:NAME:<NAME>END_PI') done() it 'should call commandNotFound if command not found', -> commandNotFoundStub = sinon.stub(cliManager.defaults.actions, 'commandNotFound') cliManager.execute(command: 'not valid command') expect(commandNotFoundStub).to.have.been.called expect(commandNotFoundStub).to.have.been.calledWith('not valid command') commandNotFoundStub.restore() it 'should return an error if there was an error executing the command', (done) -> commandNotFoundStub = sinon.stub(cliManager.defaults.actions, 'commandNotFound') cliManager.command signature: 'hello <name>' action: _.noop cliManager.execute command: 'hello', (error) -> expect(error).to.be.an.instanceof(Error) expect(error.message).to.equal('Missing name') commandNotFoundStub.restore() done() it 'should pass an execution error to the default handler', (done) -> actionError = new Error('action error') cliManager.command signature: 'hello' action: (params, options, callback) -> return callback(actionError) cliManager.execute command: 'hello', (error) -> expect(error).to.deep.equal(actionError) done() it 'should pass an async execution error to the default handler', (done) -> actionError = new Error('action error') cliManager.command signature: 'hello' action: (params, options, callback) -> setTimeout -> return callback(actionError) , 1 cliManager.execute command: 'hello', (error) -> expect(error).to.deep.equal(actionError) done() it 'should not throw an error if missing callback', -> cliManager.command signature: 'hello' action: (params, options, callback) -> return callback(actionError) expect -> cliManager.execute(command: 'hello') .to.not.throw(Error) describe 'given a stdin command', -> describe 'if parameter was passed', -> it 'should execute correctly', (done) -> spy = sinon.spy() cliManager.command signature: 'hello <|name>' action: spy cliManager.execute command: 'hello PI:NAME:<NAME>END_PI', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith(name: 'PI:NAME:<NAME>END_PI') done() describe 'if stdin was passed', -> beforeEach -> @utilsGetStdinStub = sinon.stub(utils, 'getStdin') @utilsGetStdinStub.callsArgWithAsync(0, 'PI:NAME:<NAME>END_PI') afterEach -> @utilsGetStdinStub.restore() it 'should execute correctly', (done) -> spy = sinon.spy() cliManager.command signature: 'hello <|name>' action: spy cliManager.execute command: 'hello', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith(name: 'PI:NAME:<NAME>END_PI') done() describe '#run()', -> it 'should parse and execute a command', (done) -> spy = sinon.spy() cliManager.command signature: 'hello <name>' action: spy cliManager.run 'hello PI:NAME:<NAME>END_PI', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith(name: 'PI:NAME:<NAME>END_PI') done() it 'should pass an option value starting with a number correctly', (done) -> spy = sinon.spy() cliManager.command signature: 'hello' action: spy options: [ signature: 'application' parameter: 'application' ] cliManager.run 'hello --application 10Jun2014', (error) -> expect(error).to.not.exist expect(spy).to.have.been.calledOnce expect(spy).to.have.been.calledWith({}, application: '10Jun2014') done() it 'should pass any error to the callback', (done) -> cliManager.command signature: 'hello <name>' action: (params, options, callback) -> return callback(new Error()) cliManager.run 'hello', (error) -> expect(error).to.be.an.instanceof(Error) expect(error.message).to.equal('Missing name') done()
[ { "context": "it, time: timestamp}\n else\n {author: \"YOU\", commit: '<none>', time: '<none>'}\n formatt", "end": 4990, "score": 0.8177962303161621, "start": 4987, "tag": "NAME", "value": "YOU" } ]
lib/simple-git.coffee
mauricioszabo/simple-git
10
{CompositeDisposable} = require 'atom' h = require './helper-fns' DiffView = require './diff-view' {Diff2Html} = require 'diff2html' {ScrollView} = require 'atom-space-pen-views' class Scroll extends ScrollView @content: -> @div() initialize: (txt) -> super @text(txt) module.exports = config: denyCommit: description: "Deny commits on master branch" type: 'boolean' default: true denyPush: description: "Deny pushes to remote master branch" type: 'boolean' default: true activate: (state) -> atom.workspace.addOpener (uri) => if uri.startsWith("diff://") return new DiffView(uri.replace(/\s\(diff\)/, "").replace(/diff:\/\//, "")) atom.commands.add 'atom-workspace', 'git-repository:update-master', => h.runAsyncGitCommand('checkout', 'master').then (code) => if code == 0 h.runAsyncGitCommand('pull', 'origin').then => @refreshRepos() atom.commands.add 'atom-workspace', 'git:quick-commit-current-file', => @commitWithDiff(['diff', 'HEAD', h.getFilename()], h.getFilename()) atom.commands.add 'atom-workspace', 'git:commit', => @commitWithDiff(['diff', '--staged']) atom.commands.add 'atom-workspace', 'git:push-current-branch', -> if atom.config.get('simple-git.denyPush') && h.currentBranch() == "master" atom.notifications.addError("Failed to push", detail: "You can't push to master.\nPlease create a branch and push from there") return h.runAsyncGitCommand('push', '--set-upstream', 'origin', h.currentBranch()) atom.commands.add 'atom-workspace', 'git:add-current-file', -> h.treatErrors h.runGitCommand('add', h.getFilename()) atom.commands.add 'atom-workspace', 'git:revert-current-file', -> h.treatErrors h.runGitCommand('checkout', h.getFilename()) atom.commands.add 'atom-workspace', 'git:new-branch-from-current', => h.prompt "Branch's name", (branch) => h.treatErrors h.runGitCommand('checkout', '-b', branch) @refreshRepos() atom.commands.add 'atom-workspace', 'git:show-diff-for-current-file', -> path = atom.workspace.getActiveTextEditor().getPath() atom.workspace.open("diff://#{path}") atom.commands.add 'atom-workspace', 'git:show-diff-for-project', -> path = atom.workspace.getActiveTextEditor().getPath() atom.workspace.open("diff://Full Project") atom.commands.add 'atom-workspace', 'git:toggle-blame', => @toggleBlame() commitWithDiff: (gitParams, filename) -> if atom.config.get('simple-git.denyCommit') && h.currentBranch() == "master" atom.notifications.addError("Failed to commit", detail: "You can't commit into master.\nPlease create a branch and commit from there") return cont = h.runGitCommand(gitParams...).stdout.toString() if cont div = h.prompt "Type your commit message", (commit) => if filename h.treatErrors h.runGitCommand('commit', filename, '-m', commit) else h.treatErrors h.runGitCommand('commit', '-m', commit) @refreshRepos() parentDiv = document.createElement('div') div.append(parentDiv) div2 = document.createElement('div') div2.classList.add('diff-view', 'commit') div2.innerHTML = Diff2Html.getPrettyHtml(cont) parentDiv.classList.add('parent-diff-view', 'commit') parentDiv.appendChild(div2) else atom.notifications.addError("Failed to commit", detail: "Nothing to commit... Did you forgot to add files, or the current file have any changes?") refreshRepos: -> atom.project.getRepositories().forEach (repo) => repo.refreshIndex() repo.refreshStatus() toggleBlame: -> editor = atom.workspace.getActiveTextEditor() if !editor.blameDecorations editor.blameDecorations = [] editor.onDidSave => @toggleBlame() @toggleBlame() if editor.blameDecorations.length == 0 blames = @getBlames(editor.getPath()) for line, {author, commit, time} of blames div = document.createElement('div') div.textContent = "#{author} made these changes on commit #{commit} at #{time}" div.classList.add('blame') div.classList.add('decoration') marker = editor.markScreenPosition([parseInt(line), 0]) editor.blameDecorations.push(marker) editor.decorateMarker(marker, type: 'block', position: 'before', item: div) else editor.blameDecorations.forEach (m) -> m.destroy() editor.blameDecorations = [] getBlames: (path) -> formatted = {} blames = h.runGitCommand('blame', '-M', '-w', '-c', path).stdout.toString().split("\n") lastLine = {} blames.forEach (row, number) => [commit, author, timestamp] = row.split("\t") data = if author && commit != '00000000' {author: author.substring(1).trim(), commit: commit, time: timestamp} else {author: "YOU", commit: '<none>', time: '<none>'} formatted[number] = data if !@sameLines(data, lastLine) lastLine = data formatted sameLines: (d1, d2) -> {author, commit, time} = d1 [a1, c1, t1] = [author, commit, time] {author, commit, time} = d2 [a2, c2, t2] = [author, commit, time] a1 == a2 && c1 == c2 && t1 == t2 # # deactivate() { # }, # # serialize() { # }, # };
58266
{CompositeDisposable} = require 'atom' h = require './helper-fns' DiffView = require './diff-view' {Diff2Html} = require 'diff2html' {ScrollView} = require 'atom-space-pen-views' class Scroll extends ScrollView @content: -> @div() initialize: (txt) -> super @text(txt) module.exports = config: denyCommit: description: "Deny commits on master branch" type: 'boolean' default: true denyPush: description: "Deny pushes to remote master branch" type: 'boolean' default: true activate: (state) -> atom.workspace.addOpener (uri) => if uri.startsWith("diff://") return new DiffView(uri.replace(/\s\(diff\)/, "").replace(/diff:\/\//, "")) atom.commands.add 'atom-workspace', 'git-repository:update-master', => h.runAsyncGitCommand('checkout', 'master').then (code) => if code == 0 h.runAsyncGitCommand('pull', 'origin').then => @refreshRepos() atom.commands.add 'atom-workspace', 'git:quick-commit-current-file', => @commitWithDiff(['diff', 'HEAD', h.getFilename()], h.getFilename()) atom.commands.add 'atom-workspace', 'git:commit', => @commitWithDiff(['diff', '--staged']) atom.commands.add 'atom-workspace', 'git:push-current-branch', -> if atom.config.get('simple-git.denyPush') && h.currentBranch() == "master" atom.notifications.addError("Failed to push", detail: "You can't push to master.\nPlease create a branch and push from there") return h.runAsyncGitCommand('push', '--set-upstream', 'origin', h.currentBranch()) atom.commands.add 'atom-workspace', 'git:add-current-file', -> h.treatErrors h.runGitCommand('add', h.getFilename()) atom.commands.add 'atom-workspace', 'git:revert-current-file', -> h.treatErrors h.runGitCommand('checkout', h.getFilename()) atom.commands.add 'atom-workspace', 'git:new-branch-from-current', => h.prompt "Branch's name", (branch) => h.treatErrors h.runGitCommand('checkout', '-b', branch) @refreshRepos() atom.commands.add 'atom-workspace', 'git:show-diff-for-current-file', -> path = atom.workspace.getActiveTextEditor().getPath() atom.workspace.open("diff://#{path}") atom.commands.add 'atom-workspace', 'git:show-diff-for-project', -> path = atom.workspace.getActiveTextEditor().getPath() atom.workspace.open("diff://Full Project") atom.commands.add 'atom-workspace', 'git:toggle-blame', => @toggleBlame() commitWithDiff: (gitParams, filename) -> if atom.config.get('simple-git.denyCommit') && h.currentBranch() == "master" atom.notifications.addError("Failed to commit", detail: "You can't commit into master.\nPlease create a branch and commit from there") return cont = h.runGitCommand(gitParams...).stdout.toString() if cont div = h.prompt "Type your commit message", (commit) => if filename h.treatErrors h.runGitCommand('commit', filename, '-m', commit) else h.treatErrors h.runGitCommand('commit', '-m', commit) @refreshRepos() parentDiv = document.createElement('div') div.append(parentDiv) div2 = document.createElement('div') div2.classList.add('diff-view', 'commit') div2.innerHTML = Diff2Html.getPrettyHtml(cont) parentDiv.classList.add('parent-diff-view', 'commit') parentDiv.appendChild(div2) else atom.notifications.addError("Failed to commit", detail: "Nothing to commit... Did you forgot to add files, or the current file have any changes?") refreshRepos: -> atom.project.getRepositories().forEach (repo) => repo.refreshIndex() repo.refreshStatus() toggleBlame: -> editor = atom.workspace.getActiveTextEditor() if !editor.blameDecorations editor.blameDecorations = [] editor.onDidSave => @toggleBlame() @toggleBlame() if editor.blameDecorations.length == 0 blames = @getBlames(editor.getPath()) for line, {author, commit, time} of blames div = document.createElement('div') div.textContent = "#{author} made these changes on commit #{commit} at #{time}" div.classList.add('blame') div.classList.add('decoration') marker = editor.markScreenPosition([parseInt(line), 0]) editor.blameDecorations.push(marker) editor.decorateMarker(marker, type: 'block', position: 'before', item: div) else editor.blameDecorations.forEach (m) -> m.destroy() editor.blameDecorations = [] getBlames: (path) -> formatted = {} blames = h.runGitCommand('blame', '-M', '-w', '-c', path).stdout.toString().split("\n") lastLine = {} blames.forEach (row, number) => [commit, author, timestamp] = row.split("\t") data = if author && commit != '00000000' {author: author.substring(1).trim(), commit: commit, time: timestamp} else {author: "<NAME>", commit: '<none>', time: '<none>'} formatted[number] = data if !@sameLines(data, lastLine) lastLine = data formatted sameLines: (d1, d2) -> {author, commit, time} = d1 [a1, c1, t1] = [author, commit, time] {author, commit, time} = d2 [a2, c2, t2] = [author, commit, time] a1 == a2 && c1 == c2 && t1 == t2 # # deactivate() { # }, # # serialize() { # }, # };
true
{CompositeDisposable} = require 'atom' h = require './helper-fns' DiffView = require './diff-view' {Diff2Html} = require 'diff2html' {ScrollView} = require 'atom-space-pen-views' class Scroll extends ScrollView @content: -> @div() initialize: (txt) -> super @text(txt) module.exports = config: denyCommit: description: "Deny commits on master branch" type: 'boolean' default: true denyPush: description: "Deny pushes to remote master branch" type: 'boolean' default: true activate: (state) -> atom.workspace.addOpener (uri) => if uri.startsWith("diff://") return new DiffView(uri.replace(/\s\(diff\)/, "").replace(/diff:\/\//, "")) atom.commands.add 'atom-workspace', 'git-repository:update-master', => h.runAsyncGitCommand('checkout', 'master').then (code) => if code == 0 h.runAsyncGitCommand('pull', 'origin').then => @refreshRepos() atom.commands.add 'atom-workspace', 'git:quick-commit-current-file', => @commitWithDiff(['diff', 'HEAD', h.getFilename()], h.getFilename()) atom.commands.add 'atom-workspace', 'git:commit', => @commitWithDiff(['diff', '--staged']) atom.commands.add 'atom-workspace', 'git:push-current-branch', -> if atom.config.get('simple-git.denyPush') && h.currentBranch() == "master" atom.notifications.addError("Failed to push", detail: "You can't push to master.\nPlease create a branch and push from there") return h.runAsyncGitCommand('push', '--set-upstream', 'origin', h.currentBranch()) atom.commands.add 'atom-workspace', 'git:add-current-file', -> h.treatErrors h.runGitCommand('add', h.getFilename()) atom.commands.add 'atom-workspace', 'git:revert-current-file', -> h.treatErrors h.runGitCommand('checkout', h.getFilename()) atom.commands.add 'atom-workspace', 'git:new-branch-from-current', => h.prompt "Branch's name", (branch) => h.treatErrors h.runGitCommand('checkout', '-b', branch) @refreshRepos() atom.commands.add 'atom-workspace', 'git:show-diff-for-current-file', -> path = atom.workspace.getActiveTextEditor().getPath() atom.workspace.open("diff://#{path}") atom.commands.add 'atom-workspace', 'git:show-diff-for-project', -> path = atom.workspace.getActiveTextEditor().getPath() atom.workspace.open("diff://Full Project") atom.commands.add 'atom-workspace', 'git:toggle-blame', => @toggleBlame() commitWithDiff: (gitParams, filename) -> if atom.config.get('simple-git.denyCommit') && h.currentBranch() == "master" atom.notifications.addError("Failed to commit", detail: "You can't commit into master.\nPlease create a branch and commit from there") return cont = h.runGitCommand(gitParams...).stdout.toString() if cont div = h.prompt "Type your commit message", (commit) => if filename h.treatErrors h.runGitCommand('commit', filename, '-m', commit) else h.treatErrors h.runGitCommand('commit', '-m', commit) @refreshRepos() parentDiv = document.createElement('div') div.append(parentDiv) div2 = document.createElement('div') div2.classList.add('diff-view', 'commit') div2.innerHTML = Diff2Html.getPrettyHtml(cont) parentDiv.classList.add('parent-diff-view', 'commit') parentDiv.appendChild(div2) else atom.notifications.addError("Failed to commit", detail: "Nothing to commit... Did you forgot to add files, or the current file have any changes?") refreshRepos: -> atom.project.getRepositories().forEach (repo) => repo.refreshIndex() repo.refreshStatus() toggleBlame: -> editor = atom.workspace.getActiveTextEditor() if !editor.blameDecorations editor.blameDecorations = [] editor.onDidSave => @toggleBlame() @toggleBlame() if editor.blameDecorations.length == 0 blames = @getBlames(editor.getPath()) for line, {author, commit, time} of blames div = document.createElement('div') div.textContent = "#{author} made these changes on commit #{commit} at #{time}" div.classList.add('blame') div.classList.add('decoration') marker = editor.markScreenPosition([parseInt(line), 0]) editor.blameDecorations.push(marker) editor.decorateMarker(marker, type: 'block', position: 'before', item: div) else editor.blameDecorations.forEach (m) -> m.destroy() editor.blameDecorations = [] getBlames: (path) -> formatted = {} blames = h.runGitCommand('blame', '-M', '-w', '-c', path).stdout.toString().split("\n") lastLine = {} blames.forEach (row, number) => [commit, author, timestamp] = row.split("\t") data = if author && commit != '00000000' {author: author.substring(1).trim(), commit: commit, time: timestamp} else {author: "PI:NAME:<NAME>END_PI", commit: '<none>', time: '<none>'} formatted[number] = data if !@sameLines(data, lastLine) lastLine = data formatted sameLines: (d1, d2) -> {author, commit, time} = d1 [a1, c1, t1] = [author, commit, time] {author, commit, time} = d2 [a2, c2, t2] = [author, commit, time] a1 == a2 && c1 == c2 && t1 == t2 # # deactivate() { # }, # # serialize() { # }, # };
[ { "context": "_getConnection: (callback) ->\n {hostname, port, username, password, keyfile, useAgent, passphrase, readyTi", "end": 3244, "score": 0.9710964560508728, "start": 3236, "tag": "USERNAME", "value": "username" }, { "context": " host: hostname\n port: port\n u...
lib/transports/ScpTransport.coffee
octoshrimpy/remote-sync-test
0
SSHConnection = null mkdirp = null fs = null path = require "path" module.exports = class ScpTransport constructor: (@logger, @settings, @projectPath) -> dispose: -> if @connection @connection.end() @connection = null delete: (localFilePath, callback) -> targetFilePath = path.join(@settings.target, path.relative(@projectPath, localFilePath)) .replace(/\\/g, "/") errorHandler = (err) => @logger.error err callback() @_getConnection (err, c) => return errorHandler err if err end = @logger.log "Remote delete: #{targetFilePath} ..." c.sftp (err, sftp) -> return errorHandler err if err c.exec "rm -rf \"#{targetFilePath}\"", (err) -> return errorHandler err if err end() sftp.end() callback() upload: (localFilePath, callback) -> fs = require "fs" if not fs targetFilePath = path.join(@settings.target, path.relative(fs.realpathSync(@projectPath), fs.realpathSync(localFilePath))) .replace(/\\/g, "/") errorHandler = (err) => @logger.error err callback() @_getConnection (err, c) => return errorHandler err if err end = @logger.log "Upload: #{localFilePath} to #{targetFilePath} ..." c.sftp (err, sftp) -> return errorHandler err if err c.exec "mkdir -p \"#{path.dirname(targetFilePath)}\"", (err) -> return errorHandler err if err sftp.fastPut localFilePath, targetFilePath, (err) -> return errorHandler err if err end() sftp.end() callback() download: (targetFilePath, localFilePath, callback) -> if not localFilePath localFilePath = @projectPath localFilePath = path.resolve(localFilePath, path.relative(@settings.target, targetFilePath)) errorHandler = (err) => @logger.error err @_getConnection (err, c) => return errorHandler err if err end = @logger.log "Download: #{targetFilePath} to #{localFilePath} ..." c.sftp (err, sftp) -> return errorHandler err if err mkdirp = require "mkdirp" if not mkdirp mkdirp path.dirname(localFilePath), (err) -> return errorHandler err if err sftp.fastGet targetFilePath, localFilePath, (err) -> return errorHandler err if err end() sftp.end() callback?() fetchFileTree: (localPath, callback) -> {target, isIgnore} = @settings targetPath = path.join(target, path.relative(@projectPath, localPath)) .replace(/\\/g, "/") @_getConnection (err, c) -> return callback err if err c.exec "find \"#{targetPath}\" -type f", (err, result) -> return callback err if err buf = "" result.on "data", (data) -> buf += data.toString() result.on "end", -> files = buf.split("\n").filter((f) -> return f and not isIgnore(f, target)) callback null, files _getConnection: (callback) -> {hostname, port, username, password, keyfile, useAgent, passphrase, readyTimeout} = @settings if @connection return callback null, @connection @logger.log "Connecting: #{username}@#{hostname}:#{port}" SSHConnection = require "ssh2" if not SSHConnection connection = new SSHConnection wasReady = false connection.on "ready", -> wasReady = true callback null, connection connection.on "error", (err) => unless wasReady callback err @connection = null connection.on "end", => @connection = null if keyfile fs = require "fs" if not fs privateKey = fs.readFileSync keyfile else privateKey = null agent = switch when useAgent is true if /windows/i.test process.env['OS'] process.env['SSH_AUTH_SOCK'] or "pageant" else process.env['SSH_AUTH_SOCK'] or null when typeof useAgent is "string" useAgent else null connection.connect host: hostname port: port username: username password: password privateKey: privateKey passphrase: passphrase readyTimeout: readyTimeout agent: agent @connection = connection
143465
SSHConnection = null mkdirp = null fs = null path = require "path" module.exports = class ScpTransport constructor: (@logger, @settings, @projectPath) -> dispose: -> if @connection @connection.end() @connection = null delete: (localFilePath, callback) -> targetFilePath = path.join(@settings.target, path.relative(@projectPath, localFilePath)) .replace(/\\/g, "/") errorHandler = (err) => @logger.error err callback() @_getConnection (err, c) => return errorHandler err if err end = @logger.log "Remote delete: #{targetFilePath} ..." c.sftp (err, sftp) -> return errorHandler err if err c.exec "rm -rf \"#{targetFilePath}\"", (err) -> return errorHandler err if err end() sftp.end() callback() upload: (localFilePath, callback) -> fs = require "fs" if not fs targetFilePath = path.join(@settings.target, path.relative(fs.realpathSync(@projectPath), fs.realpathSync(localFilePath))) .replace(/\\/g, "/") errorHandler = (err) => @logger.error err callback() @_getConnection (err, c) => return errorHandler err if err end = @logger.log "Upload: #{localFilePath} to #{targetFilePath} ..." c.sftp (err, sftp) -> return errorHandler err if err c.exec "mkdir -p \"#{path.dirname(targetFilePath)}\"", (err) -> return errorHandler err if err sftp.fastPut localFilePath, targetFilePath, (err) -> return errorHandler err if err end() sftp.end() callback() download: (targetFilePath, localFilePath, callback) -> if not localFilePath localFilePath = @projectPath localFilePath = path.resolve(localFilePath, path.relative(@settings.target, targetFilePath)) errorHandler = (err) => @logger.error err @_getConnection (err, c) => return errorHandler err if err end = @logger.log "Download: #{targetFilePath} to #{localFilePath} ..." c.sftp (err, sftp) -> return errorHandler err if err mkdirp = require "mkdirp" if not mkdirp mkdirp path.dirname(localFilePath), (err) -> return errorHandler err if err sftp.fastGet targetFilePath, localFilePath, (err) -> return errorHandler err if err end() sftp.end() callback?() fetchFileTree: (localPath, callback) -> {target, isIgnore} = @settings targetPath = path.join(target, path.relative(@projectPath, localPath)) .replace(/\\/g, "/") @_getConnection (err, c) -> return callback err if err c.exec "find \"#{targetPath}\" -type f", (err, result) -> return callback err if err buf = "" result.on "data", (data) -> buf += data.toString() result.on "end", -> files = buf.split("\n").filter((f) -> return f and not isIgnore(f, target)) callback null, files _getConnection: (callback) -> {hostname, port, username, password, keyfile, useAgent, passphrase, readyTimeout} = @settings if @connection return callback null, @connection @logger.log "Connecting: #{username}@#{hostname}:#{port}" SSHConnection = require "ssh2" if not SSHConnection connection = new SSHConnection wasReady = false connection.on "ready", -> wasReady = true callback null, connection connection.on "error", (err) => unless wasReady callback err @connection = null connection.on "end", => @connection = null if keyfile fs = require "fs" if not fs privateKey = fs.readFileSync keyfile else privateKey = null agent = switch when useAgent is true if /windows/i.test process.env['OS'] process.env['SSH_AUTH_SOCK'] or "pageant" else process.env['SSH_AUTH_SOCK'] or null when typeof useAgent is "string" useAgent else null connection.connect host: hostname port: port username: username password: <PASSWORD> privateKey: privateKey passphrase: <PASSWORD> readyTimeout: readyTimeout agent: agent @connection = connection
true
SSHConnection = null mkdirp = null fs = null path = require "path" module.exports = class ScpTransport constructor: (@logger, @settings, @projectPath) -> dispose: -> if @connection @connection.end() @connection = null delete: (localFilePath, callback) -> targetFilePath = path.join(@settings.target, path.relative(@projectPath, localFilePath)) .replace(/\\/g, "/") errorHandler = (err) => @logger.error err callback() @_getConnection (err, c) => return errorHandler err if err end = @logger.log "Remote delete: #{targetFilePath} ..." c.sftp (err, sftp) -> return errorHandler err if err c.exec "rm -rf \"#{targetFilePath}\"", (err) -> return errorHandler err if err end() sftp.end() callback() upload: (localFilePath, callback) -> fs = require "fs" if not fs targetFilePath = path.join(@settings.target, path.relative(fs.realpathSync(@projectPath), fs.realpathSync(localFilePath))) .replace(/\\/g, "/") errorHandler = (err) => @logger.error err callback() @_getConnection (err, c) => return errorHandler err if err end = @logger.log "Upload: #{localFilePath} to #{targetFilePath} ..." c.sftp (err, sftp) -> return errorHandler err if err c.exec "mkdir -p \"#{path.dirname(targetFilePath)}\"", (err) -> return errorHandler err if err sftp.fastPut localFilePath, targetFilePath, (err) -> return errorHandler err if err end() sftp.end() callback() download: (targetFilePath, localFilePath, callback) -> if not localFilePath localFilePath = @projectPath localFilePath = path.resolve(localFilePath, path.relative(@settings.target, targetFilePath)) errorHandler = (err) => @logger.error err @_getConnection (err, c) => return errorHandler err if err end = @logger.log "Download: #{targetFilePath} to #{localFilePath} ..." c.sftp (err, sftp) -> return errorHandler err if err mkdirp = require "mkdirp" if not mkdirp mkdirp path.dirname(localFilePath), (err) -> return errorHandler err if err sftp.fastGet targetFilePath, localFilePath, (err) -> return errorHandler err if err end() sftp.end() callback?() fetchFileTree: (localPath, callback) -> {target, isIgnore} = @settings targetPath = path.join(target, path.relative(@projectPath, localPath)) .replace(/\\/g, "/") @_getConnection (err, c) -> return callback err if err c.exec "find \"#{targetPath}\" -type f", (err, result) -> return callback err if err buf = "" result.on "data", (data) -> buf += data.toString() result.on "end", -> files = buf.split("\n").filter((f) -> return f and not isIgnore(f, target)) callback null, files _getConnection: (callback) -> {hostname, port, username, password, keyfile, useAgent, passphrase, readyTimeout} = @settings if @connection return callback null, @connection @logger.log "Connecting: #{username}@#{hostname}:#{port}" SSHConnection = require "ssh2" if not SSHConnection connection = new SSHConnection wasReady = false connection.on "ready", -> wasReady = true callback null, connection connection.on "error", (err) => unless wasReady callback err @connection = null connection.on "end", => @connection = null if keyfile fs = require "fs" if not fs privateKey = fs.readFileSync keyfile else privateKey = null agent = switch when useAgent is true if /windows/i.test process.env['OS'] process.env['SSH_AUTH_SOCK'] or "pageant" else process.env['SSH_AUTH_SOCK'] or null when typeof useAgent is "string" useAgent else null connection.connect host: hostname port: port username: username password: PI:PASSWORD:<PASSWORD>END_PI privateKey: privateKey passphrase: PI:PASSWORD:<PASSWORD>END_PI readyTimeout: readyTimeout agent: agent @connection = connection
[ { "context": "kLayoutAsFixed()\n\n # Simple Diff function\n # (C) Paul Butler 2008 <http://www.paulbutler.org/>\n # https://git", "end": 10335, "score": 0.9996294975280762, "start": 10324, "tag": "NAME", "value": "Paul Butler" }, { "context": "ttp://www.paulbutler.org/>\n # https...
src/patch-programming/DiffingPatchNodeWdgt.coffee
intensifier/Fizzygum
110
# this file is excluded from the fizzygum homepage build class DiffingPatchNodeWdgt extends Widget @augmentWith ControllerMixin tempPromptEntryField: nil defaultContents: nil textMorph: nil output: nil input1: nil input2: nil # we need to keep track of which inputs are # connected because we wait for those to be # all updated before the node fires setInput1IsConnected: false setInput2IsConnected: false setInput1HotIsConnected: false setInput2HotConnected: false # to keep track of whether each input is # up-to-date or not input1connectionsCalculationToken: 0 input2connectionsCalculationToken: 0 # the external padding is the space between the edges # of the container and all of its internals. The reason # you often set this to zero is because windows already put # contents inside themselves with a little padding, so this # external padding is not needed. Useful to keep it # separate and know that it's working though. externalPadding: 0 # the internal padding is the space between the internal # components. It doesn't necessarily need to be equal to the # external padding internalPadding: 5 constructor: (@defaultContents = "") -> super new Point 200,400 @buildAndConnectChildren() @input1 = "" @input2 = "" colloquialName: -> "Diffing patch node" setInput1: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @input1connectionsCalculationToken then return else if !connectionsCalculationToken? then @input1connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @input1connectionsCalculationToken = connectionsCalculationToken @input1 = newvalue @updateTarget @input1connectionsCalculationToken setInput2: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @input2connectionsCalculationToken then return else if !connectionsCalculationToken? then @input2connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @input2connectionsCalculationToken = connectionsCalculationToken @input1 = newvalue @updateTarget @input2connectionsCalculationToken # TODO note that only the first hot input will cause the widget to fire # in this cycle - so the order of arrivals might matter. setInput1Hot: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @connectionsCalculationToken then return else if !connectionsCalculationToken? then @connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @connectionsCalculationToken = connectionsCalculationToken @input1 = newvalue @updateTarget @connectionsCalculationToken, false, true setInput2Hot: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @connectionsCalculationToken then return else if !connectionsCalculationToken? then @connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @connectionsCalculationToken = connectionsCalculationToken @input2 = newvalue @updateTarget @connectionsCalculationToken, false, true # the bang makes the node fire the current output value bang: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @connectionsCalculationToken then return else if !connectionsCalculationToken? then @connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @connectionsCalculationToken = connectionsCalculationToken @updateTarget @connectionsCalculationToken, true openTargetPropertySelector: (ignored, ignored2, theTarget) -> [menuEntriesStrings, functionNamesStrings] = theTarget.numericalSetters() menu = new MenuMorph @, false, @, true, true, "choose target property:" for i in [0...menuEntriesStrings.length] menu.addMenuItem menuEntriesStrings[i], true, @, "setTargetAndActionWithOnesPickedFromMenu", nil, nil, nil, nil, nil, theTarget, functionNamesStrings[i] if menuEntriesStrings.length == 0 menu = new MenuMorph @, false, @, true, true, "no target properties available" menu.popUpAtHand() updateTarget: (connectionsCalculationToken, fireBecauseBang, fireBecauseOneHotInputHasBeenUpdated) -> # if there is no input connected, then bail # TODO we could be more lenient, one could enter the node value in a box in the widget for example # and we might issue a bang, so we'd expect the output to be pushed to the target if !@setInput1IsConnected and !@setInput2IsConnected and !@setInput1HotIsConnected and !@setInput2HotIsConnected return # if all connected inputs are updated in the very same connectors update cycle, # (althought of course they would get updated one at a time) # then allConnectedInputsAreFresh is true, and we'll fire for sure allConnectedInputsAreFresh = true if @setInput1IsConnected if @input1connectionsCalculationToken != connectionsCalculationToken allConnectedInputsAreFresh = false if @setInput2IsConnected if @input2connectionsCalculationToken != connectionsCalculationToken allConnectedInputsAreFresh = false # if we are firing via bang then we use # the existing output value, we don't # recalculate a new one # # otherwise (we are not firing via bang) # if both inputs are fresh OR only one of them is but it's a HOT input, then # we have to recalculate the diff if (allConnectedInputsAreFresh or fireBecauseOneHotInputHasBeenUpdated) and !fireBecauseBang # note that we calculate an output value # even if this node has no target. This # is because the node might be visualising the # output in some other way. @recalculateOutput() # if # * all the connected inputs are fresh OR # * we are firing via bang OR # * one hot input has been updated if allConnectedInputsAreFresh or fireBecauseOneHotInputHasBeenUpdated or fireBecauseBang # AND if the widget still has to fire if connectionPropagationToken != @connectionPropagationToken # THEN we update the target with the output value @fireOutputToTarget connectionsCalculationToken return fireOutputToTarget: (calculationToken) -> # mark this node as fired. # if the update DOES come from the "bang!", then # @connectionsCalculationToken has already been updated # but we keep it simple and re-assign it here, not # worth complicating things with an additional check @connectionsCalculationToken = calculationToken if @action and @action != "" @target[@action].call @target, @output, nil, @connectionsCalculationToken reactToTargetConnection: -> # we generate a new calculation token, that's OK because # we are definitely not in the middle of the calculation here # but we might be starting a new chain of calculations @fireOutputToTarget world.makeNewConnectionsCalculationToken() recalculateOutput: -> @output = @formattedDiff @input1, @input2 @textMorph.setText @output stringSetters: (menuEntriesStrings, functionNamesStrings) -> [menuEntriesStrings, functionNamesStrings] = super menuEntriesStrings, functionNamesStrings menuEntriesStrings.push "bang!", "in1", "in2", "in1 hot", "in2 hot" functionNamesStrings.push "bang", "setInput1", "setInput2", "setInput1Hot", "setInput2Hot" return @deduplicateSettersAndSortByMenuEntryString menuEntriesStrings, functionNamesStrings numericalSetters: (menuEntriesStrings, functionNamesStrings) -> [menuEntriesStrings, functionNamesStrings] = super menuEntriesStrings, functionNamesStrings menuEntriesStrings.push "bang!", "in1", "in2", "in1 hot", "in2 hot" functionNamesStrings.push "bang", "setInput1", "setInput2", "setInput1Hot", "setInput2Hot" return @deduplicateSettersAndSortByMenuEntryString menuEntriesStrings, functionNamesStrings addMorphSpecificMenuEntries: (morphOpeningThePopUp, menu) -> super menu.addLine() if world.isIndexPage menu.addMenuItem "connect to ➜", true, @, "openTargetSelector", "connect to\nanother widget" else menu.addMenuItem "set target", true, @, "openTargetSelector", "choose another morph\nwhose numerical property\n will be" + " controlled by this one" buildAndConnectChildren: -> if Automator? and Automator.state != Automator.IDLE and Automator.alignmentOfMorphIDsMechanism world.alignIDsOfNextMorphsInSystemTests() @tempPromptEntryField = new SimplePlainTextScrollPanelWdgt @defaultContents, false, 5 @tempPromptEntryField.disableDrops() @tempPromptEntryField.contents.disableDrops() @tempPromptEntryField.color = Color.WHITE @textMorph = @tempPromptEntryField.textWdgt @textMorph.backgroundColor = Color.TRANSPARENT @textMorph.setFontName nil, nil, @textMorph.monoFontStack @textMorph.isEditable = true @textMorph.enableSelecting() @add @tempPromptEntryField @invalidateLayout() doLayout: (newBoundsForThisLayout) -> #if !window.recalculatingLayouts then debugger if @_handleCollapsedStateShouldWeReturn() then return # here we are disabling all the broken # rectangles. The reason is that all the # submorphs of the inspector are within the # bounds of the parent Widget. This means that # if only the parent morph breaks its rectangle # then everything is OK. # Also note that if you attach something else to its # boundary in a way that sticks out, that's still # going to be painted and moved OK. world.disableTrackChanges() textHeight = @height() - 2 * @externalPadding if @tempPromptEntryField.parent == @ @tempPromptEntryField.fullRawMoveTo new Point @left() + @externalPadding, @top() + @externalPadding @tempPromptEntryField.rawSetExtent new Point @width() - 2 * @externalPadding, textHeight world.maybeEnableTrackChanges() @fullChanged() if Automator? and Automator.state != Automator.IDLE and Automator.alignmentOfMorphIDsMechanism world.alignIDsOfNextMorphsInSystemTests() super @markLayoutAsFixed() # Simple Diff function # (C) Paul Butler 2008 <http://www.paulbutler.org/> # https://github.com/paulgb/simplediff/blob/master/coffeescript/simplediff.coffee diff: (before, after) -> # Find the differences between two lists. Returns a list of pairs, where the first value # is in ['+','-','='] and represents an insertion, deletion, or no change for that list. # The second value of the pair is the element. # Build a hash map with elements from before as keys, and # a list of indexes as values ohash = {} for val, i in before if val not of ohash ohash[val] = [] ohash[val].push i # Find the largest substring common to before and after lastRow = (0 for i in [0 ... before.length]) subStartBefore = subStartAfter = subLength = 0 for val, j in after thisRow = (0 for i in [0 ... before.length]) for k in ohash[val] ? [] thisRow[k] = (if k and lastRow[k - 1] then 1 else 0) + 1 if thisRow[k] > subLength subLength = thisRow[k] subStartBefore = k - subLength + 1 subStartAfter = j - subLength + 1 lastRow = thisRow # If no common substring is found, assume that an insert and # delete has taken place if subLength == 0 [].concat( (if before.length then [['-', before]] else []), (if after.length then [['+', after]] else []), ) # Otherwise, the common substring is considered to have no change, and we recurse # on the text before and after the substring else [].concat( @diff(before[...subStartBefore], after[...subStartAfter]), [['=', after[subStartAfter...subStartAfter + subLength]]], @diff(before[subStartBefore + subLength...], after[subStartAfter + subLength...]) ) # The below functions are intended for simple tests and experimentation; you will want to write more sophisticated wrapper functions for real use stringDiff: (before, after) -> # Returns the difference between the before and after strings when split on whitespace. Considers punctuation a part of the word @diff(before.split(/[ ]+/), after.split(/[ ]+/)) formattedDiff: (before, after) -> con = '=': ((x) -> x), '+': ((x) -> '+(' + x + ')'), '-': ((x) -> '-(' + x + ')') ((con[a])(b.join ' ') for [a, b] in @stringDiff(before, after)).join ' '
76486
# this file is excluded from the fizzygum homepage build class DiffingPatchNodeWdgt extends Widget @augmentWith ControllerMixin tempPromptEntryField: nil defaultContents: nil textMorph: nil output: nil input1: nil input2: nil # we need to keep track of which inputs are # connected because we wait for those to be # all updated before the node fires setInput1IsConnected: false setInput2IsConnected: false setInput1HotIsConnected: false setInput2HotConnected: false # to keep track of whether each input is # up-to-date or not input1connectionsCalculationToken: 0 input2connectionsCalculationToken: 0 # the external padding is the space between the edges # of the container and all of its internals. The reason # you often set this to zero is because windows already put # contents inside themselves with a little padding, so this # external padding is not needed. Useful to keep it # separate and know that it's working though. externalPadding: 0 # the internal padding is the space between the internal # components. It doesn't necessarily need to be equal to the # external padding internalPadding: 5 constructor: (@defaultContents = "") -> super new Point 200,400 @buildAndConnectChildren() @input1 = "" @input2 = "" colloquialName: -> "Diffing patch node" setInput1: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @input1connectionsCalculationToken then return else if !connectionsCalculationToken? then @input1connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @input1connectionsCalculationToken = connectionsCalculationToken @input1 = newvalue @updateTarget @input1connectionsCalculationToken setInput2: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @input2connectionsCalculationToken then return else if !connectionsCalculationToken? then @input2connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @input2connectionsCalculationToken = connectionsCalculationToken @input1 = newvalue @updateTarget @input2connectionsCalculationToken # TODO note that only the first hot input will cause the widget to fire # in this cycle - so the order of arrivals might matter. setInput1Hot: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @connectionsCalculationToken then return else if !connectionsCalculationToken? then @connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @connectionsCalculationToken = connectionsCalculationToken @input1 = newvalue @updateTarget @connectionsCalculationToken, false, true setInput2Hot: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @connectionsCalculationToken then return else if !connectionsCalculationToken? then @connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @connectionsCalculationToken = connectionsCalculationToken @input2 = newvalue @updateTarget @connectionsCalculationToken, false, true # the bang makes the node fire the current output value bang: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @connectionsCalculationToken then return else if !connectionsCalculationToken? then @connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @connectionsCalculationToken = connectionsCalculationToken @updateTarget @connectionsCalculationToken, true openTargetPropertySelector: (ignored, ignored2, theTarget) -> [menuEntriesStrings, functionNamesStrings] = theTarget.numericalSetters() menu = new MenuMorph @, false, @, true, true, "choose target property:" for i in [0...menuEntriesStrings.length] menu.addMenuItem menuEntriesStrings[i], true, @, "setTargetAndActionWithOnesPickedFromMenu", nil, nil, nil, nil, nil, theTarget, functionNamesStrings[i] if menuEntriesStrings.length == 0 menu = new MenuMorph @, false, @, true, true, "no target properties available" menu.popUpAtHand() updateTarget: (connectionsCalculationToken, fireBecauseBang, fireBecauseOneHotInputHasBeenUpdated) -> # if there is no input connected, then bail # TODO we could be more lenient, one could enter the node value in a box in the widget for example # and we might issue a bang, so we'd expect the output to be pushed to the target if !@setInput1IsConnected and !@setInput2IsConnected and !@setInput1HotIsConnected and !@setInput2HotIsConnected return # if all connected inputs are updated in the very same connectors update cycle, # (althought of course they would get updated one at a time) # then allConnectedInputsAreFresh is true, and we'll fire for sure allConnectedInputsAreFresh = true if @setInput1IsConnected if @input1connectionsCalculationToken != connectionsCalculationToken allConnectedInputsAreFresh = false if @setInput2IsConnected if @input2connectionsCalculationToken != connectionsCalculationToken allConnectedInputsAreFresh = false # if we are firing via bang then we use # the existing output value, we don't # recalculate a new one # # otherwise (we are not firing via bang) # if both inputs are fresh OR only one of them is but it's a HOT input, then # we have to recalculate the diff if (allConnectedInputsAreFresh or fireBecauseOneHotInputHasBeenUpdated) and !fireBecauseBang # note that we calculate an output value # even if this node has no target. This # is because the node might be visualising the # output in some other way. @recalculateOutput() # if # * all the connected inputs are fresh OR # * we are firing via bang OR # * one hot input has been updated if allConnectedInputsAreFresh or fireBecauseOneHotInputHasBeenUpdated or fireBecauseBang # AND if the widget still has to fire if connectionPropagationToken != @connectionPropagationToken # THEN we update the target with the output value @fireOutputToTarget connectionsCalculationToken return fireOutputToTarget: (calculationToken) -> # mark this node as fired. # if the update DOES come from the "bang!", then # @connectionsCalculationToken has already been updated # but we keep it simple and re-assign it here, not # worth complicating things with an additional check @connectionsCalculationToken = calculationToken if @action and @action != "" @target[@action].call @target, @output, nil, @connectionsCalculationToken reactToTargetConnection: -> # we generate a new calculation token, that's OK because # we are definitely not in the middle of the calculation here # but we might be starting a new chain of calculations @fireOutputToTarget world.makeNewConnectionsCalculationToken() recalculateOutput: -> @output = @formattedDiff @input1, @input2 @textMorph.setText @output stringSetters: (menuEntriesStrings, functionNamesStrings) -> [menuEntriesStrings, functionNamesStrings] = super menuEntriesStrings, functionNamesStrings menuEntriesStrings.push "bang!", "in1", "in2", "in1 hot", "in2 hot" functionNamesStrings.push "bang", "setInput1", "setInput2", "setInput1Hot", "setInput2Hot" return @deduplicateSettersAndSortByMenuEntryString menuEntriesStrings, functionNamesStrings numericalSetters: (menuEntriesStrings, functionNamesStrings) -> [menuEntriesStrings, functionNamesStrings] = super menuEntriesStrings, functionNamesStrings menuEntriesStrings.push "bang!", "in1", "in2", "in1 hot", "in2 hot" functionNamesStrings.push "bang", "setInput1", "setInput2", "setInput1Hot", "setInput2Hot" return @deduplicateSettersAndSortByMenuEntryString menuEntriesStrings, functionNamesStrings addMorphSpecificMenuEntries: (morphOpeningThePopUp, menu) -> super menu.addLine() if world.isIndexPage menu.addMenuItem "connect to ➜", true, @, "openTargetSelector", "connect to\nanother widget" else menu.addMenuItem "set target", true, @, "openTargetSelector", "choose another morph\nwhose numerical property\n will be" + " controlled by this one" buildAndConnectChildren: -> if Automator? and Automator.state != Automator.IDLE and Automator.alignmentOfMorphIDsMechanism world.alignIDsOfNextMorphsInSystemTests() @tempPromptEntryField = new SimplePlainTextScrollPanelWdgt @defaultContents, false, 5 @tempPromptEntryField.disableDrops() @tempPromptEntryField.contents.disableDrops() @tempPromptEntryField.color = Color.WHITE @textMorph = @tempPromptEntryField.textWdgt @textMorph.backgroundColor = Color.TRANSPARENT @textMorph.setFontName nil, nil, @textMorph.monoFontStack @textMorph.isEditable = true @textMorph.enableSelecting() @add @tempPromptEntryField @invalidateLayout() doLayout: (newBoundsForThisLayout) -> #if !window.recalculatingLayouts then debugger if @_handleCollapsedStateShouldWeReturn() then return # here we are disabling all the broken # rectangles. The reason is that all the # submorphs of the inspector are within the # bounds of the parent Widget. This means that # if only the parent morph breaks its rectangle # then everything is OK. # Also note that if you attach something else to its # boundary in a way that sticks out, that's still # going to be painted and moved OK. world.disableTrackChanges() textHeight = @height() - 2 * @externalPadding if @tempPromptEntryField.parent == @ @tempPromptEntryField.fullRawMoveTo new Point @left() + @externalPadding, @top() + @externalPadding @tempPromptEntryField.rawSetExtent new Point @width() - 2 * @externalPadding, textHeight world.maybeEnableTrackChanges() @fullChanged() if Automator? and Automator.state != Automator.IDLE and Automator.alignmentOfMorphIDsMechanism world.alignIDsOfNextMorphsInSystemTests() super @markLayoutAsFixed() # Simple Diff function # (C) <NAME> 2008 <http://www.paulbutler.org/> # https://github.com/paulgb/simplediff/blob/master/coffeescript/simplediff.coffee diff: (before, after) -> # Find the differences between two lists. Returns a list of pairs, where the first value # is in ['+','-','='] and represents an insertion, deletion, or no change for that list. # The second value of the pair is the element. # Build a hash map with elements from before as keys, and # a list of indexes as values ohash = {} for val, i in before if val not of ohash ohash[val] = [] ohash[val].push i # Find the largest substring common to before and after lastRow = (0 for i in [0 ... before.length]) subStartBefore = subStartAfter = subLength = 0 for val, j in after thisRow = (0 for i in [0 ... before.length]) for k in ohash[val] ? [] thisRow[k] = (if k and lastRow[k - 1] then 1 else 0) + 1 if thisRow[k] > subLength subLength = thisRow[k] subStartBefore = k - subLength + 1 subStartAfter = j - subLength + 1 lastRow = thisRow # If no common substring is found, assume that an insert and # delete has taken place if subLength == 0 [].concat( (if before.length then [['-', before]] else []), (if after.length then [['+', after]] else []), ) # Otherwise, the common substring is considered to have no change, and we recurse # on the text before and after the substring else [].concat( @diff(before[...subStartBefore], after[...subStartAfter]), [['=', after[subStartAfter...subStartAfter + subLength]]], @diff(before[subStartBefore + subLength...], after[subStartAfter + subLength...]) ) # The below functions are intended for simple tests and experimentation; you will want to write more sophisticated wrapper functions for real use stringDiff: (before, after) -> # Returns the difference between the before and after strings when split on whitespace. Considers punctuation a part of the word @diff(before.split(/[ ]+/), after.split(/[ ]+/)) formattedDiff: (before, after) -> con = '=': ((x) -> x), '+': ((x) -> '+(' + x + ')'), '-': ((x) -> '-(' + x + ')') ((con[a])(b.join ' ') for [a, b] in @stringDiff(before, after)).join ' '
true
# this file is excluded from the fizzygum homepage build class DiffingPatchNodeWdgt extends Widget @augmentWith ControllerMixin tempPromptEntryField: nil defaultContents: nil textMorph: nil output: nil input1: nil input2: nil # we need to keep track of which inputs are # connected because we wait for those to be # all updated before the node fires setInput1IsConnected: false setInput2IsConnected: false setInput1HotIsConnected: false setInput2HotConnected: false # to keep track of whether each input is # up-to-date or not input1connectionsCalculationToken: 0 input2connectionsCalculationToken: 0 # the external padding is the space between the edges # of the container and all of its internals. The reason # you often set this to zero is because windows already put # contents inside themselves with a little padding, so this # external padding is not needed. Useful to keep it # separate and know that it's working though. externalPadding: 0 # the internal padding is the space between the internal # components. It doesn't necessarily need to be equal to the # external padding internalPadding: 5 constructor: (@defaultContents = "") -> super new Point 200,400 @buildAndConnectChildren() @input1 = "" @input2 = "" colloquialName: -> "Diffing patch node" setInput1: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @input1connectionsCalculationToken then return else if !connectionsCalculationToken? then @input1connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @input1connectionsCalculationToken = connectionsCalculationToken @input1 = newvalue @updateTarget @input1connectionsCalculationToken setInput2: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @input2connectionsCalculationToken then return else if !connectionsCalculationToken? then @input2connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @input2connectionsCalculationToken = connectionsCalculationToken @input1 = newvalue @updateTarget @input2connectionsCalculationToken # TODO note that only the first hot input will cause the widget to fire # in this cycle - so the order of arrivals might matter. setInput1Hot: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @connectionsCalculationToken then return else if !connectionsCalculationToken? then @connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @connectionsCalculationToken = connectionsCalculationToken @input1 = newvalue @updateTarget @connectionsCalculationToken, false, true setInput2Hot: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @connectionsCalculationToken then return else if !connectionsCalculationToken? then @connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @connectionsCalculationToken = connectionsCalculationToken @input2 = newvalue @updateTarget @connectionsCalculationToken, false, true # the bang makes the node fire the current output value bang: (newvalue, ignored, connectionsCalculationToken, superCall) -> if !superCall and connectionsCalculationToken == @connectionsCalculationToken then return else if !connectionsCalculationToken? then @connectionsCalculationToken = world.makeNewConnectionsCalculationToken() else @connectionsCalculationToken = connectionsCalculationToken @updateTarget @connectionsCalculationToken, true openTargetPropertySelector: (ignored, ignored2, theTarget) -> [menuEntriesStrings, functionNamesStrings] = theTarget.numericalSetters() menu = new MenuMorph @, false, @, true, true, "choose target property:" for i in [0...menuEntriesStrings.length] menu.addMenuItem menuEntriesStrings[i], true, @, "setTargetAndActionWithOnesPickedFromMenu", nil, nil, nil, nil, nil, theTarget, functionNamesStrings[i] if menuEntriesStrings.length == 0 menu = new MenuMorph @, false, @, true, true, "no target properties available" menu.popUpAtHand() updateTarget: (connectionsCalculationToken, fireBecauseBang, fireBecauseOneHotInputHasBeenUpdated) -> # if there is no input connected, then bail # TODO we could be more lenient, one could enter the node value in a box in the widget for example # and we might issue a bang, so we'd expect the output to be pushed to the target if !@setInput1IsConnected and !@setInput2IsConnected and !@setInput1HotIsConnected and !@setInput2HotIsConnected return # if all connected inputs are updated in the very same connectors update cycle, # (althought of course they would get updated one at a time) # then allConnectedInputsAreFresh is true, and we'll fire for sure allConnectedInputsAreFresh = true if @setInput1IsConnected if @input1connectionsCalculationToken != connectionsCalculationToken allConnectedInputsAreFresh = false if @setInput2IsConnected if @input2connectionsCalculationToken != connectionsCalculationToken allConnectedInputsAreFresh = false # if we are firing via bang then we use # the existing output value, we don't # recalculate a new one # # otherwise (we are not firing via bang) # if both inputs are fresh OR only one of them is but it's a HOT input, then # we have to recalculate the diff if (allConnectedInputsAreFresh or fireBecauseOneHotInputHasBeenUpdated) and !fireBecauseBang # note that we calculate an output value # even if this node has no target. This # is because the node might be visualising the # output in some other way. @recalculateOutput() # if # * all the connected inputs are fresh OR # * we are firing via bang OR # * one hot input has been updated if allConnectedInputsAreFresh or fireBecauseOneHotInputHasBeenUpdated or fireBecauseBang # AND if the widget still has to fire if connectionPropagationToken != @connectionPropagationToken # THEN we update the target with the output value @fireOutputToTarget connectionsCalculationToken return fireOutputToTarget: (calculationToken) -> # mark this node as fired. # if the update DOES come from the "bang!", then # @connectionsCalculationToken has already been updated # but we keep it simple and re-assign it here, not # worth complicating things with an additional check @connectionsCalculationToken = calculationToken if @action and @action != "" @target[@action].call @target, @output, nil, @connectionsCalculationToken reactToTargetConnection: -> # we generate a new calculation token, that's OK because # we are definitely not in the middle of the calculation here # but we might be starting a new chain of calculations @fireOutputToTarget world.makeNewConnectionsCalculationToken() recalculateOutput: -> @output = @formattedDiff @input1, @input2 @textMorph.setText @output stringSetters: (menuEntriesStrings, functionNamesStrings) -> [menuEntriesStrings, functionNamesStrings] = super menuEntriesStrings, functionNamesStrings menuEntriesStrings.push "bang!", "in1", "in2", "in1 hot", "in2 hot" functionNamesStrings.push "bang", "setInput1", "setInput2", "setInput1Hot", "setInput2Hot" return @deduplicateSettersAndSortByMenuEntryString menuEntriesStrings, functionNamesStrings numericalSetters: (menuEntriesStrings, functionNamesStrings) -> [menuEntriesStrings, functionNamesStrings] = super menuEntriesStrings, functionNamesStrings menuEntriesStrings.push "bang!", "in1", "in2", "in1 hot", "in2 hot" functionNamesStrings.push "bang", "setInput1", "setInput2", "setInput1Hot", "setInput2Hot" return @deduplicateSettersAndSortByMenuEntryString menuEntriesStrings, functionNamesStrings addMorphSpecificMenuEntries: (morphOpeningThePopUp, menu) -> super menu.addLine() if world.isIndexPage menu.addMenuItem "connect to ➜", true, @, "openTargetSelector", "connect to\nanother widget" else menu.addMenuItem "set target", true, @, "openTargetSelector", "choose another morph\nwhose numerical property\n will be" + " controlled by this one" buildAndConnectChildren: -> if Automator? and Automator.state != Automator.IDLE and Automator.alignmentOfMorphIDsMechanism world.alignIDsOfNextMorphsInSystemTests() @tempPromptEntryField = new SimplePlainTextScrollPanelWdgt @defaultContents, false, 5 @tempPromptEntryField.disableDrops() @tempPromptEntryField.contents.disableDrops() @tempPromptEntryField.color = Color.WHITE @textMorph = @tempPromptEntryField.textWdgt @textMorph.backgroundColor = Color.TRANSPARENT @textMorph.setFontName nil, nil, @textMorph.monoFontStack @textMorph.isEditable = true @textMorph.enableSelecting() @add @tempPromptEntryField @invalidateLayout() doLayout: (newBoundsForThisLayout) -> #if !window.recalculatingLayouts then debugger if @_handleCollapsedStateShouldWeReturn() then return # here we are disabling all the broken # rectangles. The reason is that all the # submorphs of the inspector are within the # bounds of the parent Widget. This means that # if only the parent morph breaks its rectangle # then everything is OK. # Also note that if you attach something else to its # boundary in a way that sticks out, that's still # going to be painted and moved OK. world.disableTrackChanges() textHeight = @height() - 2 * @externalPadding if @tempPromptEntryField.parent == @ @tempPromptEntryField.fullRawMoveTo new Point @left() + @externalPadding, @top() + @externalPadding @tempPromptEntryField.rawSetExtent new Point @width() - 2 * @externalPadding, textHeight world.maybeEnableTrackChanges() @fullChanged() if Automator? and Automator.state != Automator.IDLE and Automator.alignmentOfMorphIDsMechanism world.alignIDsOfNextMorphsInSystemTests() super @markLayoutAsFixed() # Simple Diff function # (C) PI:NAME:<NAME>END_PI 2008 <http://www.paulbutler.org/> # https://github.com/paulgb/simplediff/blob/master/coffeescript/simplediff.coffee diff: (before, after) -> # Find the differences between two lists. Returns a list of pairs, where the first value # is in ['+','-','='] and represents an insertion, deletion, or no change for that list. # The second value of the pair is the element. # Build a hash map with elements from before as keys, and # a list of indexes as values ohash = {} for val, i in before if val not of ohash ohash[val] = [] ohash[val].push i # Find the largest substring common to before and after lastRow = (0 for i in [0 ... before.length]) subStartBefore = subStartAfter = subLength = 0 for val, j in after thisRow = (0 for i in [0 ... before.length]) for k in ohash[val] ? [] thisRow[k] = (if k and lastRow[k - 1] then 1 else 0) + 1 if thisRow[k] > subLength subLength = thisRow[k] subStartBefore = k - subLength + 1 subStartAfter = j - subLength + 1 lastRow = thisRow # If no common substring is found, assume that an insert and # delete has taken place if subLength == 0 [].concat( (if before.length then [['-', before]] else []), (if after.length then [['+', after]] else []), ) # Otherwise, the common substring is considered to have no change, and we recurse # on the text before and after the substring else [].concat( @diff(before[...subStartBefore], after[...subStartAfter]), [['=', after[subStartAfter...subStartAfter + subLength]]], @diff(before[subStartBefore + subLength...], after[subStartAfter + subLength...]) ) # The below functions are intended for simple tests and experimentation; you will want to write more sophisticated wrapper functions for real use stringDiff: (before, after) -> # Returns the difference between the before and after strings when split on whitespace. Considers punctuation a part of the word @diff(before.split(/[ ]+/), after.split(/[ ]+/)) formattedDiff: (before, after) -> con = '=': ((x) -> x), '+': ((x) -> '+(' + x + ')'), '-': ((x) -> '-(' + x + ')') ((con[a])(b.join ' ') for [a, b] in @stringDiff(before, after)).join ' '
[ { "context": "efer msgs\n asp = new util.ASP {}\n userid = \"anon@keybase.io\"\n for msg in msgs\n await KeyManager.impor", "end": 1268, "score": 0.9998974800109863, "start": 1253, "tag": "EMAIL", "value": "anon@keybase.io" } ]
dev/clearsign.iced
samkenxstream/kbpgp
464
#!/usr/bin/env iced fs = require 'fs' {make_esc} = require 'iced-error' armor = require '../lib/openpgp/armor' util = require '../lib/util' {do_message,Message} = require '../lib/openpgp/processor' {Literal} = require '../lib/openpgp/packet/literal' {PgpKeyRing} = require '../lib/keyring' {KeyManager} = require '../lib/keymanager' {clear_sign} = require '../lib/openpgp/clearsign' C = require '../lib/const' {unix_time} = require '../lib/util' iced.catchExceptions() #================================================================= argv = require('optimist') .alias("m", "msg") .alias("k","keyfile") .usage("$0 -m <msg> -k <keyfile> -p <passphrase>") .alias("p","passphrase").argv #================================================================= class Runner #---------- constructor : (@argv) -> @ring = new PgpKeyRing #---------- _read_file : (fn, cb) -> esc = make_esc cb, "read_file #{fn}" await fs.readFile fn, esc defer data [err, msgs] = armor.mdecode data await util.athrow err, esc defer() cb null, msgs #---------- read_keys : (cb) -> esc = make_esc cb, "read_keys" await @_read_file @argv.keyfile, esc defer msgs asp = new util.ASP {} userid = "anon@keybase.io" for msg in msgs await KeyManager.import_from_pgp_message { msg, asp, userid }, esc defer km if km.is_pgp_locked() and @need_private_keys() await km.unlock_pgp { passphrase : @argv.passphrase }, esc defer() @ring.add_key_manager km cb null #---------- read_msg : (cb) -> esc = make_esc cb, "read_msg" await @_read_file @argv.msg, esc defer msgs @msg = msgs[0] cb null #---------- read_input : (cb) -> await fs.readFile @argv.msg, defer err, msg cb err, msg #---------- verify : (cb) -> esc = make_esc cb, "verify" await @read_input esc defer msg await do_message { armored : msg, keyfetch : @ring }, esc defer() cb null #---------- to_pgp : (cb) -> esc = make_esc cb, "to_pgp/burn" await @read_input esc defer msg signing_key = null await @ring.find_best_key { key_id : (Buffer.from(@argv.s, 'hex')), flags : C.openpgp.key_flags.sign_data }, esc defer signing_key await clearnsign { msg, signing_key }, esc defer out console.log out cb null #---------- need_private_keys : () -> true #---------- parse_args : (cb) -> ok = false err = if not @argv.msg? new Error "need a msg file to operate on" else if not @argv.keyfile? new Error "need a keyfile to read keys from" else if @need_private_keys() and not @argv.passphrase new Error "need a passphrase to unlock a signing or decrypting key" else null cb err #---------- run : (cb) -> esc = make_esc cb, "run" await @parse_args esc defer() await @read_keys esc defer() await @verify esc defer() cb null #================================================================= runner = new Runner argv await runner.run defer err throw err if err? process.exit 0
205261
#!/usr/bin/env iced fs = require 'fs' {make_esc} = require 'iced-error' armor = require '../lib/openpgp/armor' util = require '../lib/util' {do_message,Message} = require '../lib/openpgp/processor' {Literal} = require '../lib/openpgp/packet/literal' {PgpKeyRing} = require '../lib/keyring' {KeyManager} = require '../lib/keymanager' {clear_sign} = require '../lib/openpgp/clearsign' C = require '../lib/const' {unix_time} = require '../lib/util' iced.catchExceptions() #================================================================= argv = require('optimist') .alias("m", "msg") .alias("k","keyfile") .usage("$0 -m <msg> -k <keyfile> -p <passphrase>") .alias("p","passphrase").argv #================================================================= class Runner #---------- constructor : (@argv) -> @ring = new PgpKeyRing #---------- _read_file : (fn, cb) -> esc = make_esc cb, "read_file #{fn}" await fs.readFile fn, esc defer data [err, msgs] = armor.mdecode data await util.athrow err, esc defer() cb null, msgs #---------- read_keys : (cb) -> esc = make_esc cb, "read_keys" await @_read_file @argv.keyfile, esc defer msgs asp = new util.ASP {} userid = "<EMAIL>" for msg in msgs await KeyManager.import_from_pgp_message { msg, asp, userid }, esc defer km if km.is_pgp_locked() and @need_private_keys() await km.unlock_pgp { passphrase : @argv.passphrase }, esc defer() @ring.add_key_manager km cb null #---------- read_msg : (cb) -> esc = make_esc cb, "read_msg" await @_read_file @argv.msg, esc defer msgs @msg = msgs[0] cb null #---------- read_input : (cb) -> await fs.readFile @argv.msg, defer err, msg cb err, msg #---------- verify : (cb) -> esc = make_esc cb, "verify" await @read_input esc defer msg await do_message { armored : msg, keyfetch : @ring }, esc defer() cb null #---------- to_pgp : (cb) -> esc = make_esc cb, "to_pgp/burn" await @read_input esc defer msg signing_key = null await @ring.find_best_key { key_id : (Buffer.from(@argv.s, 'hex')), flags : C.openpgp.key_flags.sign_data }, esc defer signing_key await clearnsign { msg, signing_key }, esc defer out console.log out cb null #---------- need_private_keys : () -> true #---------- parse_args : (cb) -> ok = false err = if not @argv.msg? new Error "need a msg file to operate on" else if not @argv.keyfile? new Error "need a keyfile to read keys from" else if @need_private_keys() and not @argv.passphrase new Error "need a passphrase to unlock a signing or decrypting key" else null cb err #---------- run : (cb) -> esc = make_esc cb, "run" await @parse_args esc defer() await @read_keys esc defer() await @verify esc defer() cb null #================================================================= runner = new Runner argv await runner.run defer err throw err if err? process.exit 0
true
#!/usr/bin/env iced fs = require 'fs' {make_esc} = require 'iced-error' armor = require '../lib/openpgp/armor' util = require '../lib/util' {do_message,Message} = require '../lib/openpgp/processor' {Literal} = require '../lib/openpgp/packet/literal' {PgpKeyRing} = require '../lib/keyring' {KeyManager} = require '../lib/keymanager' {clear_sign} = require '../lib/openpgp/clearsign' C = require '../lib/const' {unix_time} = require '../lib/util' iced.catchExceptions() #================================================================= argv = require('optimist') .alias("m", "msg") .alias("k","keyfile") .usage("$0 -m <msg> -k <keyfile> -p <passphrase>") .alias("p","passphrase").argv #================================================================= class Runner #---------- constructor : (@argv) -> @ring = new PgpKeyRing #---------- _read_file : (fn, cb) -> esc = make_esc cb, "read_file #{fn}" await fs.readFile fn, esc defer data [err, msgs] = armor.mdecode data await util.athrow err, esc defer() cb null, msgs #---------- read_keys : (cb) -> esc = make_esc cb, "read_keys" await @_read_file @argv.keyfile, esc defer msgs asp = new util.ASP {} userid = "PI:EMAIL:<EMAIL>END_PI" for msg in msgs await KeyManager.import_from_pgp_message { msg, asp, userid }, esc defer km if km.is_pgp_locked() and @need_private_keys() await km.unlock_pgp { passphrase : @argv.passphrase }, esc defer() @ring.add_key_manager km cb null #---------- read_msg : (cb) -> esc = make_esc cb, "read_msg" await @_read_file @argv.msg, esc defer msgs @msg = msgs[0] cb null #---------- read_input : (cb) -> await fs.readFile @argv.msg, defer err, msg cb err, msg #---------- verify : (cb) -> esc = make_esc cb, "verify" await @read_input esc defer msg await do_message { armored : msg, keyfetch : @ring }, esc defer() cb null #---------- to_pgp : (cb) -> esc = make_esc cb, "to_pgp/burn" await @read_input esc defer msg signing_key = null await @ring.find_best_key { key_id : (Buffer.from(@argv.s, 'hex')), flags : C.openpgp.key_flags.sign_data }, esc defer signing_key await clearnsign { msg, signing_key }, esc defer out console.log out cb null #---------- need_private_keys : () -> true #---------- parse_args : (cb) -> ok = false err = if not @argv.msg? new Error "need a msg file to operate on" else if not @argv.keyfile? new Error "need a keyfile to read keys from" else if @need_private_keys() and not @argv.passphrase new Error "need a passphrase to unlock a signing or decrypting key" else null cb err #---------- run : (cb) -> esc = make_esc cb, "run" await @parse_args esc defer() await @read_keys esc defer() await @verify esc defer() cb null #================================================================= runner = new Runner argv await runner.run defer err throw err if err? process.exit 0
[ { "context": "at you're doing\n#\n# Notes\n# None\n#\n# Author:\n# Morgan Wigmanich <okize123@gmail.com> (https://github.com/okize)\n\n", "end": 241, "score": 0.9998681545257568, "start": 225, "tag": "NAME", "value": "Morgan Wigmanich" }, { "context": " Notes\n# None\n#\n# Auth...
src/ihavenoidea.coffee
okize/hubot-has-no-idea
2
# Description: # Hubot script to display "I have no idea what I'm doing" images # # Dependencies: # None # # Configuration: # None # # Commands: # you have no idea what you're doing # # Notes # None # # Author: # Morgan Wigmanich <okize123@gmail.com> (https://github.com/okize) module.exports = (robot) -> robot.hear regex, (msg) -> msg.send msg.random images images = require './data/images.json' gaffes = [ 'i ha(ve|s) no idea', 'i don\'t know', '\\b(wh|)oops(|ie)\\b', 'my (bad|mistake|fault)', 'd(\')oh' ] regex = new RegExp gaffes.join('|'), 'ig'
140187
# Description: # Hubot script to display "I have no idea what I'm doing" images # # Dependencies: # None # # Configuration: # None # # Commands: # you have no idea what you're doing # # Notes # None # # Author: # <NAME> <<EMAIL>> (https://github.com/okize) module.exports = (robot) -> robot.hear regex, (msg) -> msg.send msg.random images images = require './data/images.json' gaffes = [ 'i ha(ve|s) no idea', 'i don\'t know', '\\b(wh|)oops(|ie)\\b', 'my (bad|mistake|fault)', 'd(\')oh' ] regex = new RegExp gaffes.join('|'), 'ig'
true
# Description: # Hubot script to display "I have no idea what I'm doing" images # # Dependencies: # None # # Configuration: # None # # Commands: # you have no idea what you're doing # # Notes # None # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (https://github.com/okize) module.exports = (robot) -> robot.hear regex, (msg) -> msg.send msg.random images images = require './data/images.json' gaffes = [ 'i ha(ve|s) no idea', 'i don\'t know', '\\b(wh|)oops(|ie)\\b', 'my (bad|mistake|fault)', 'd(\')oh' ] regex = new RegExp gaffes.join('|'), 'ig'
[ { "context": "###\n# scripts/directives/style.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n###\n'use strict'\n\n", "end": 60, "score": 0.9995200037956238, "start": 49, "tag": "NAME", "value": "Dan Nichols" } ]
app/scripts/directives/tabs.coffee
dlnichols/h_media
0
### # scripts/directives/style.coffee # # © 2014 Dan Nichols # See LICENSE for more details ### 'use strict' angular.module 'hMediaApp' .controller 'tabsetController', ($scope, $state) -> ctrl = @ tabs = ctrl.tabs = $scope.tabs = [] ctrl.state = $state ctrl.addTab = (tab) -> tabs.push tab return ctrl.removeTab = (tab) -> index = tabs.indexOf tab tabs.splice index, 1 return return .directive 'tabset', -> restrict: 'EA' transclude: true replace: true scope: type: '@' controller: 'tabsetController' template: '<ul class="nav nav-{{type || \'tabs\'}}" ng-class="{\'nav-stacked\': vertical}" ng-transclude></ul>' link: (scope, element, attrs) -> scope.vertical = if angular.isDefined(attrs.vertical) then scope.$parent.$eval(attrs.vertical) else false return .directive 'tab', ($parse) -> require: '^tabset' restrict: 'EA' transclude: true replace: true scope: active: '=?' controller: -> template: '<li ng-class="{active: active(), disabled: disabled}"><a ng-transclude></a></li>' compile: (elm, attrs) -> (scope, elm, attrs, ctrl) -> ctrl.addTab scope scope.$on '$destroy', -> ctrl.removeTab scope scope.active = -> attrs.uiSref is ctrl.state.current.name
217123
### # scripts/directives/style.coffee # # © 2014 <NAME> # See LICENSE for more details ### 'use strict' angular.module 'hMediaApp' .controller 'tabsetController', ($scope, $state) -> ctrl = @ tabs = ctrl.tabs = $scope.tabs = [] ctrl.state = $state ctrl.addTab = (tab) -> tabs.push tab return ctrl.removeTab = (tab) -> index = tabs.indexOf tab tabs.splice index, 1 return return .directive 'tabset', -> restrict: 'EA' transclude: true replace: true scope: type: '@' controller: 'tabsetController' template: '<ul class="nav nav-{{type || \'tabs\'}}" ng-class="{\'nav-stacked\': vertical}" ng-transclude></ul>' link: (scope, element, attrs) -> scope.vertical = if angular.isDefined(attrs.vertical) then scope.$parent.$eval(attrs.vertical) else false return .directive 'tab', ($parse) -> require: '^tabset' restrict: 'EA' transclude: true replace: true scope: active: '=?' controller: -> template: '<li ng-class="{active: active(), disabled: disabled}"><a ng-transclude></a></li>' compile: (elm, attrs) -> (scope, elm, attrs, ctrl) -> ctrl.addTab scope scope.$on '$destroy', -> ctrl.removeTab scope scope.active = -> attrs.uiSref is ctrl.state.current.name
true
### # scripts/directives/style.coffee # # © 2014 PI:NAME:<NAME>END_PI # See LICENSE for more details ### 'use strict' angular.module 'hMediaApp' .controller 'tabsetController', ($scope, $state) -> ctrl = @ tabs = ctrl.tabs = $scope.tabs = [] ctrl.state = $state ctrl.addTab = (tab) -> tabs.push tab return ctrl.removeTab = (tab) -> index = tabs.indexOf tab tabs.splice index, 1 return return .directive 'tabset', -> restrict: 'EA' transclude: true replace: true scope: type: '@' controller: 'tabsetController' template: '<ul class="nav nav-{{type || \'tabs\'}}" ng-class="{\'nav-stacked\': vertical}" ng-transclude></ul>' link: (scope, element, attrs) -> scope.vertical = if angular.isDefined(attrs.vertical) then scope.$parent.$eval(attrs.vertical) else false return .directive 'tab', ($parse) -> require: '^tabset' restrict: 'EA' transclude: true replace: true scope: active: '=?' controller: -> template: '<li ng-class="{active: active(), disabled: disabled}"><a ng-transclude></a></li>' compile: (elm, attrs) -> (scope, elm, attrs, ctrl) -> ctrl.addTab scope scope.$on '$destroy', -> ctrl.removeTab scope scope.active = -> attrs.uiSref is ctrl.state.current.name
[ { "context": "e\", subtitle: \"\" },\n 1: { id: 2, title: \"Robinson Crusoe\" }\n })\n $httpBackend.flush()\n\n c", "end": 1166, "score": 0.9998701214790344, "start": 1151, "tag": "NAME", "value": "Robinson Crusoe" }, { "context": "ual(2)\n expect(colle...
test/transform-response-spec.coffee
panta/angular-rest-orm
21
describe "response transform:", -> $rootScope = undefined $httpBackend = undefined $q = undefined Resource = undefined Book = undefined beforeEach module("restOrm") beforeEach inject(($injector) -> $rootScope = $injector.get("$rootScope") $httpBackend = $injector.get("$httpBackend") $q = $injector.get("$q") Resource = $injector.get("Resource") ) describe "transformResponse", -> beforeEach -> class Book extends Resource @urlEndpoint: '/api/v1/books/' @defaults: title: "" subtitle: "" @transformResponse: (res) -> if res.what == 'All' newData = [] for k, v of res.data newData.push v res.data = newData else if res.what == 'Get' res.data = res.data[0] else if res.what == '$save' res.data = res.data[0] return res it "should work for .All()", -> collection = Book.All() $httpBackend.when('GET', '/api/v1/books/').respond(200, { 0: { id: 1, title: "The Jungle", subtitle: "" }, 1: { id: 2, title: "Robinson Crusoe" } }) $httpBackend.flush() collection.$promise.then jasmine.createSpy('success') $rootScope.$digest() expect(collection.length).toEqual(2) expect(collection[0] instanceof Book).toBeTruthy() expect(collection[0].$id).toEqual(1) expect(collection[0].title).toEqual("The Jungle") expect(collection[1] instanceof Book).toBeTruthy() expect(collection[1].$id).toEqual(2) expect(collection[1].title).toEqual("Robinson Crusoe") return it "should work for .Get()", -> book = Book.Get(1) $httpBackend.when('GET', '/api/v1/books/1').respond(200, { 0: { id: 1, title: "The Jungle", subtitle: "" } }) $httpBackend.flush() book.$promise.then jasmine.createSpy('success') $rootScope.$digest() expect(book.$id).toEqual(1) expect(book.title).toEqual("The Jungle") return it "should work for .$ave() for fresh instance", -> book = new Book({ title: "The Jungle" }) book.$save() $httpBackend.when('POST', '/api/v1/books/').respond(200, { 0: { id: 1, title: "The Jungle" } }) $httpBackend.flush() book.$promise.then jasmine.createSpy('success') $rootScope.$digest() expect(book.$id).toEqual(1) expect(book.title).toEqual("The Jungle") return it "should work for .$ave() for existing instance", -> book = Book.Get(1) $httpBackend.when('GET', '/api/v1/books/1').respond(200, { 0: { id: 1, title: "The Jungle" } }) $httpBackend.flush() book.$promise.then jasmine.createSpy('success') $rootScope.$digest() book.title = "The Jungle 2.0" book.$save() $httpBackend.when('PUT', '/api/v1/books/1').respond(200, { 0: { id: 1, title: "The Jungle 2.0" } }) $httpBackend.flush() expect(book.$id).toEqual(1) expect(book.title).toEqual("The Jungle 2.0") return return return
130649
describe "response transform:", -> $rootScope = undefined $httpBackend = undefined $q = undefined Resource = undefined Book = undefined beforeEach module("restOrm") beforeEach inject(($injector) -> $rootScope = $injector.get("$rootScope") $httpBackend = $injector.get("$httpBackend") $q = $injector.get("$q") Resource = $injector.get("Resource") ) describe "transformResponse", -> beforeEach -> class Book extends Resource @urlEndpoint: '/api/v1/books/' @defaults: title: "" subtitle: "" @transformResponse: (res) -> if res.what == 'All' newData = [] for k, v of res.data newData.push v res.data = newData else if res.what == 'Get' res.data = res.data[0] else if res.what == '$save' res.data = res.data[0] return res it "should work for .All()", -> collection = Book.All() $httpBackend.when('GET', '/api/v1/books/').respond(200, { 0: { id: 1, title: "The Jungle", subtitle: "" }, 1: { id: 2, title: "<NAME>" } }) $httpBackend.flush() collection.$promise.then jasmine.createSpy('success') $rootScope.$digest() expect(collection.length).toEqual(2) expect(collection[0] instanceof Book).toBeTruthy() expect(collection[0].$id).toEqual(1) expect(collection[0].title).toEqual("The Jungle") expect(collection[1] instanceof Book).toBeTruthy() expect(collection[1].$id).toEqual(2) expect(collection[1].title).toEqual("<NAME>") return it "should work for .Get()", -> book = Book.Get(1) $httpBackend.when('GET', '/api/v1/books/1').respond(200, { 0: { id: 1, title: "The Jungle", subtitle: "" } }) $httpBackend.flush() book.$promise.then jasmine.createSpy('success') $rootScope.$digest() expect(book.$id).toEqual(1) expect(book.title).toEqual("The Jungle") return it "should work for .$ave() for fresh instance", -> book = new Book({ title: "The Jungle" }) book.$save() $httpBackend.when('POST', '/api/v1/books/').respond(200, { 0: { id: 1, title: "The Jungle" } }) $httpBackend.flush() book.$promise.then jasmine.createSpy('success') $rootScope.$digest() expect(book.$id).toEqual(1) expect(book.title).toEqual("The Jungle") return it "should work for .$ave() for existing instance", -> book = Book.Get(1) $httpBackend.when('GET', '/api/v1/books/1').respond(200, { 0: { id: 1, title: "The Jungle" } }) $httpBackend.flush() book.$promise.then jasmine.createSpy('success') $rootScope.$digest() book.title = "The Jungle 2.0" book.$save() $httpBackend.when('PUT', '/api/v1/books/1').respond(200, { 0: { id: 1, title: "The Jungle 2.0" } }) $httpBackend.flush() expect(book.$id).toEqual(1) expect(book.title).toEqual("The Jungle 2.0") return return return
true
describe "response transform:", -> $rootScope = undefined $httpBackend = undefined $q = undefined Resource = undefined Book = undefined beforeEach module("restOrm") beforeEach inject(($injector) -> $rootScope = $injector.get("$rootScope") $httpBackend = $injector.get("$httpBackend") $q = $injector.get("$q") Resource = $injector.get("Resource") ) describe "transformResponse", -> beforeEach -> class Book extends Resource @urlEndpoint: '/api/v1/books/' @defaults: title: "" subtitle: "" @transformResponse: (res) -> if res.what == 'All' newData = [] for k, v of res.data newData.push v res.data = newData else if res.what == 'Get' res.data = res.data[0] else if res.what == '$save' res.data = res.data[0] return res it "should work for .All()", -> collection = Book.All() $httpBackend.when('GET', '/api/v1/books/').respond(200, { 0: { id: 1, title: "The Jungle", subtitle: "" }, 1: { id: 2, title: "PI:NAME:<NAME>END_PI" } }) $httpBackend.flush() collection.$promise.then jasmine.createSpy('success') $rootScope.$digest() expect(collection.length).toEqual(2) expect(collection[0] instanceof Book).toBeTruthy() expect(collection[0].$id).toEqual(1) expect(collection[0].title).toEqual("The Jungle") expect(collection[1] instanceof Book).toBeTruthy() expect(collection[1].$id).toEqual(2) expect(collection[1].title).toEqual("PI:NAME:<NAME>END_PI") return it "should work for .Get()", -> book = Book.Get(1) $httpBackend.when('GET', '/api/v1/books/1').respond(200, { 0: { id: 1, title: "The Jungle", subtitle: "" } }) $httpBackend.flush() book.$promise.then jasmine.createSpy('success') $rootScope.$digest() expect(book.$id).toEqual(1) expect(book.title).toEqual("The Jungle") return it "should work for .$ave() for fresh instance", -> book = new Book({ title: "The Jungle" }) book.$save() $httpBackend.when('POST', '/api/v1/books/').respond(200, { 0: { id: 1, title: "The Jungle" } }) $httpBackend.flush() book.$promise.then jasmine.createSpy('success') $rootScope.$digest() expect(book.$id).toEqual(1) expect(book.title).toEqual("The Jungle") return it "should work for .$ave() for existing instance", -> book = Book.Get(1) $httpBackend.when('GET', '/api/v1/books/1').respond(200, { 0: { id: 1, title: "The Jungle" } }) $httpBackend.flush() book.$promise.then jasmine.createSpy('success') $rootScope.$digest() book.title = "The Jungle 2.0" book.$save() $httpBackend.when('PUT', '/api/v1/books/1').respond(200, { 0: { id: 1, title: "The Jungle 2.0" } }) $httpBackend.flush() expect(book.$id).toEqual(1) expect(book.title).toEqual("The Jungle 2.0") return return return
[ { "context": ": 'localhost'\n #port: 8777\n #username: 'admin' # optional\n #password: 'secret' # option", "end": 672, "score": 0.9984956979751587, "start": 667, "tag": "USERNAME", "value": "admin" }, { "context": "#username: 'admin' # optional\n #password: '...
otto.db.coffee
ferguson/otto
16
_ = require 'underscore' fs = require 'fs' net = require 'net' mongodb = require 'mongodb' child_process = require 'child_process' otto = global.otto module.exports = global.otto.db = do -> # note the 'do' causes the function to be called db = {} mongo = null c = {} #collections_inuse = ['objects', 'connections', 'images', 'accesslog', 'listeners', 'queues', 'events'] collections_inuse = ['objects', 'connections', 'images', 'events'] filenamecache = null db.assemble_dbconf = -> db.dbconf = db: 'otto' host: otto.OTTO_VAR + '/mongod.sock' domainSocket: true #host: 'localhost' #port: 8777 #username: 'admin' # optional #password: 'secret' # optional collection: 'sessions' # only for connect-mongo, optional, default: sessions file: "#{otto.OTTO_VAR}/mongodb.conf" db_directory: "#{otto.OTTO_VAR_MONGODB}" #log_file: "#{otto.OTTO_VAR}/mongod.log" pid_file: "#{otto.OTTO_VAR}/mongod.pid" socket_file: "#{otto.OTTO_VAR}/mongod.sock" # must end in .sock for pymongo to work #bind_ip: "localhost" port: 8777 # not really used when using a unix domain socket (but still required?) mongod_executable: "#{otto.MONGOD_EXECUTABLE}" db.dbconf.text = """ # auto generated (and regenerated) by otto, don't edit dbpath = #{db.dbconf.db_directory} pidfilepath = #{db.dbconf.pid_file} bind_ip = #{db.dbconf.socket_file} #bind_ip = #{db.dbconf.bind_ip} port = #{db.dbconf.port} # not really used, socket file on previous line is used instead nounixsocket = true # suppresses creation of a second socket in /tmp nohttpinterface = true journal = on noprealloc = true noauth = true #verbose = true quiet = true profile = 0 # don't report slow queries slowms = 2000 # it still prints them to stdout though, this'll cut that down """ # blank line at the end is so conf file has a closing CR (but not a blank line) return db.dbconf db.spawn = (callback) -> # see if there is an existing mongod by testing a connection to the socket testsocket = net.connect db.dbconf.socket_file, -> # mongod process already exists, don't spawn another one console.log "using existing mongod on #{db.dbconf.socket_file}" testsocket.destroy() callback() testsocket.on 'error', (err) -> #console.log 'error', err testsocket.destroy() console.log "no existing mongod found, spawning a new one on #{db.dbconf.socket_file}" console.log "...using executable #{db.dbconf.mongod_executable}" # we wait until now to write the conf file so we don't step on existing conf files for an existing mongod fs.writeFile db.dbconf.file, db.dbconf.text, (err) -> if err then throw err opts = #stdio: [ 'ignore', 'ignore', 'ignore' ] detached: true #env : # DYLD_FALLBACK_LIBRARY_PATH: otto.OTTO_LIB # LD_LIBRARY_PATH: otto.OTTO_LIB if otto.OTTO_SPAWN_AS_UID opts.uid = otto.OTTO_SPAWN_AS_UID child = child_process.spawn db.dbconf.mongod_executable, ['-f', db.dbconf.file], opts child.unref() mongod_says = (data) -> process.stdout.write 'mongod: ' + data # i could also color this differently, fun! child.stdout.on 'data', mongod_says child.stderr.on 'data', mongod_says child.on 'exit', (code, signal) -> return if otto.exiting console.log "mongod exited with code #{code}" if signal then console.log "...and signal #{signal}" throw new Error 'mongod went away!' # i guess we could wait and try reconnecting? FIXME otto.misc.wait_for_socket db.dbconf.socket_file, 1500, (err) -> # needed to be > 500 for linux if err then throw new Error err callback() db.kill_mongodSync = -> # needs to be Sync so we finish before event loop exits otto.misc.kill_from_pid_fileSync otto.OTTO_VAR + '/mongod.pid' db.init = (callback) -> db.assemble_dbconf() db.spawn -> db.connect db.dbconf.db, db.dbconf.host, db.dbconf.port, (err) -> if err "mongodb does not appear to be running" throw err #process.nextTick -> # not sure this is really necessary callback() db.connect = (database='otto', hostname='localhost', port=27017, callback=no) -> mongo = new mongodb.Db(database, new mongodb.Server(hostname, port, {}), {safe:true, strict:false}) mongo.open (err, p_client) -> if err if callback then callback "error trying to open database #{database} on #{hostname}:#{port}: #{err}" return attach_collections collections_inuse, -> c.objects.count (err, count) -> if err then throw new Error "database error trying to count 'objects' collection: #{err}" console.log "connected to database #{database} on #{hostname}:#{port}" s = if count != 1 then 's' else '' console.log "#{count} object#{s}" if count < 5 console.log 'we have an empty database!' db.emptydatabase = true else db.emptydatabase = false if count > 200000 console.log 'we have a large database!' db.largedatabase = true else db.largedatabase = false #if not c.events.isCapped() # console.log 'events collection is not capped' #else # console.log 'events collection is capped' # couldn't get this to work. perhaps runCommand is missing from my mongodb driver? #if not c.events.isCapped # console.log 'capping events collection' # p_client.runCommand {"convertToCapped": "events", size: 100000} #console.dir p_client #p_client.createCollection 'events', {'capped':true, 'size':100000}, -> #p_client.createCollection 'events', -> # if not c.events.isCapped # console.log 'events collection is not capped' # else # console.log 'events collection is capped' if callback callback() # lookup a list of connections by name and assign them to c.<collection_name> attach_collections = (collection_names, callback) -> lookupcount = collection_names.length if lookupcount for name in collection_names do (name) -> mongo.collection name, (err, collection) -> if err then throw new Error "database error trying to attach to collection '#{name}': #{err}" c[name] = collection if --lookupcount is 0 callback() else callback() db.save_event = (e, callback) -> _id = c.events.save e, (err, eSaved) -> callback eSaved._id db.save_object = (o, callback) -> if not o.otype? and o.otype throw new Error 'object need an otype to be saved' oid = c.objects.save o, (err, oSaved) -> callback oSaved._id db.load_object = (ids=null, load_parents=no, callback) -> # otypes: # 1 owner # 5 dir # 10 song # 20 album # 30 artist # 40 fileunder # 50 list if not ids console.log "load_object: no id(s) given" ids = [] if ids instanceof Array returnarray = true else returnarray = false ids = [ids] bids = ids.map (id) -> new mongodb.ObjectID(String(id)) # get_random_songs needed this for some odd reason! q = { '_id': { '$in': bids } } c.objects.find(q).toArray (err, objects) -> if err then throw new Error "database error trying to load objects #{ids}: #{err}" if not objects callback null return for object in objects object.oid = object['_id'] # for backwards compatability if load_parents lookupcount = objects.length for object in objects db.load_subobjects object, load_parents, yes, [5,6], -> lookupcount-- if lookupcount is 0 if returnarray callback objects else callback objects[0] else if returnarray callback objects else callback objects[0] # alias because i keep mistyping it db.load_objects = db.load_object db.load_subobjects = (objectlist, subotype, parents=no, filteroutctypes=[5,6], callback) -> if not objectlist then throw new Error "load_object: you must supply the object(s)" objects = [].concat objectlist # make array of array or single object lookupcount = objects.length # we should optimize this to be a single query instead of this loop FIXME if not objects.length callback objectlist else for o in objects do (o) -> # makes a closure so we can preserve each version of 'o' across the async calls below if parents q = { child: o._id } else q = { parent: o._id } # sort on _id, rank here? or do we need to sort after since they are not joined? TODO c.connections.find(q).toArray (err, results) -> if err then throw new Error "database error fetching list of subobjects for #{o._id}: #{err}" subids = results.map (i) -> if parents then i.parent else i.child q = { '_id': { '$in': subids } } if subotype q.otype = Number(subotype) c.objects.find(q).toArray (err, subobjects) -> if err then throw new Error "database error loading subobjects for #{o._id}: #{err}" for subobject in subobjects subobject.oid = subobject['_id'] # for backward compability switch Number(subotype) when 40 then o.fileunder = subobjects when 30 then o.artists = subobjects when 20 then o.albums = subobjects when 10 then o.songs = subobjects when 5 then o.dirs = subobjects when 1 then o.owners = subobjects lookupcount-- if lookupcount is 0 callback objectlist db.load_image = (id, size, callback) -> bid = new mongodb.ObjectID(id) if not size then size = 'orig' fields = {} fields["sizes.#{size}"] = 1 c.images.findOne { _id: bid }, fields, (err, image) -> if err callback null return if image and image.sizes and image.sizes[size] callback image.sizes[size].buffer return if size == 'orig' callback null return console.log "image size #{size} not found, trying orig" c.images.findOne { _id: bid }, { 'sizes.orig': 1 }, (err, image) -> if err callback null return if image and image.sizes and image.sizes.orig callback image.sizes.orig.buffer return callback null db.add_to_connections = (parent, child, ctype, rank, callback) -> # ctypes: # 1 dirs, songs, albums, artists to owner # 2 songs to albums # 3 songs to artists # 4 artists to albums # 5 primary albums to artists and/or 'various' # 6 secondary albums to artists and/or 'various' # 7 primary albums to fileunder # 8 secondary albums to fileunder # 10 dirs to dirs # 11 files (songs) to directory # 12 lists # FIXME need to extend this to handle rank and duplicates # upsert pattern yanked from https://github.com/mongodb/node-mongodb-native/issues/29 #id = mongodb.bson_serializer.ObjectID(null) id = mongodb.ObjectID(null) doc = '_id': id 'ctype': ctype 'parent': parent 'child': child 'rank': rank c.connections.update {'_id': id}, doc, upsert: true, (err, connection) -> if err callback null else console.log 'connection._id', connection._id # this isn't the way to get the new _id callback connection db.remove_from_connections = (id, callback) -> c.connections.remove {'_id': id}, (err, num) -> if err then throw new Error err callback num # load album (or artist, or fileunder) details db.album_details = (oid, callback) -> result = null lookupcount = 1 # lookup the id, see if it's an album or an artist or a fileunder db.load_object oid, false, (object) -> result = object if not result callback result return if result.otype in [30, 40] # artist or fileunder db.load_subobjects result, 20, no, [5,6], phasetwo else if result.otype == 20 phasetwo [result] else phasetwo result phasetwo = (subobjects) -> if result.otype in [30, 40] further = result.albums else further = [result] lookupcount = 3*further.length if not further.length callback result else for o in further db.load_subobjects o, 10, no, [5,6], phasethree db.load_subobjects o, 30, yes, [5,6], phasethree db.load_subobjects o, 1, yes, [5,6], phasethree phasethree = (subobjects) -> lookupcount-- if lookupcount is 0 callback result db.starts_with = (value, attribute, otype, nochildren, callback) -> elapsed = new otto.misc.Elapsed() filter = {} params = [] filteroutctypes = [4,6] order = {} order[attribute] = 1 if value.length == 1 and value.toLowerCase() in 'abcdefghijklmnopqrstuvwxyz0123456789' filter[attribute] = ///^#{value}///i else switch value when 'num' filter[attribute] = ///^[0-9]/// when 'other' filter[attribute] = {'$in': [ ///^[^0-9a-z]///i, 'unknown' ]} when 'st' filter[attribute] = ///\bsoundtrack\b///i filteroutctypes = False when 'va' filter[attribute] = { '$in': [ ///\bvarious\b///i, ///\bartists\b///i, ///\bvarious artists\b///i ] } # why yes, i *do* know the third regexp is redundant filteroutctypes = False when 'all' filter = {} order = {year: 1, album: 1} filter['otype'] = otype # i don't think this does anything when used on the objects collection (only connections have ctypes) if filteroutctypes filter['ctype'] = { '$nin': filteroutctypes } objects = [] object_lookup = {} # maybe someday we can figure out how to 'stream' these results (or maybe page 'em) # ...actually, the bottleneck seems to be in rendering large result sets on the client # side, not in getting the results from mongo or transmitting them to the client c.objects.find(filter).sort(order).each (err, object) -> if err then throw new Error "error searching for objects with #{attribute} #{value}: #{err}" if object object.oid = object['_id'] objects.push(object) object_lookup[object._id] = object else console.log "#{elapsed.seconds()} objects loaded" subotype = no if otype == 40 subotype = 20 else if otype > 10 subotype = otype - 10 else subotype = null if !subotype or nochildren callback objects return oids = objects.map (o) -> o._id parents = no # huh? perhaps overriding the value from above? if parents q = { 'child': {'$in': oids} } else q = { 'parent': {'$in': oids} } if filteroutctypes then q.ctype = {'$nin': filteroutctypes} c.connections.find(q).toArray (err, connections) -> if err then throw new Error "database error fetching list of subobjects for starts_with #{attribute} #{value} #{err}" console.log "#{elapsed.seconds()} connections loaded" subattribute = db.attach_point subotype suboids = connections.map (i) -> if parents then i.parent else i.child subobjects = [] subobject_lookup = {} #missing sorting on rank here? FIXME c.objects.find({ '_id': { '$in': suboids }, 'otype': subotype }).each (err, subobject) -> if err then throw new Error "database error loading subobjects for starts_with #{attribute} #{value}: #{err}" if subobject subobject.oid = subobject['_id'] subobjects.push(subobject) subobject_lookup[subobject._id] = subobject else for connection in connections if parents obj = object_lookup[connection.child] sub = subobject_lookup[connection.parent] else obj = object_lookup[connection.parent] sub = subobject_lookup[connection.child] if not sub continue if obj[subattribute] obj[subattribute].push(sub) else obj[subattribute] = [sub] console.log "#{elapsed.seconds()} subobjects loaded" console.log subobjects && subobjects.length callback objects db.attach_point = (otype) -> switch Number(otype) when 40 then return 'fileunder' when 30 then return 'artists' when 20 then return 'albums' when 10 then return 'songs' when 5 then return 'dirs' when 1 then return 'owners' return '' db.attach_parents = (objects, options, callback) -> ids = objects.map (o) -> o._id # match connections against child to find parents find = { 'child': {'$in': ids}, 'ctype': {'$nin':[4,6]} } c.connections.find(find).toArray (err, connections) -> if err then throw new Error "error fetching parent connections: #{err}" console.log connections.length, 'connections' parentids = connections.map (i) -> i.parent otypes = [].concat (options.otype || 40) find = { '_id': { '$in': parentids }, 'otype': {'$in':otypes} } sort = { 'child': 1, 'rank':1 } c.objects.find(find).sort(sort).toArray (err, parents) -> if err then throw new Error "error loading parent objects: #{err}" #console.log parents.length, 'parents' object_lookup = {} for object in objects object_lookup[object._id] = object parent_lookup = {} for parent in parents parent_lookup[parent._id] = parent # attach 'em for connection in connections object = object_lookup[connection.child] parent = parent_lookup[connection.parent] if not parent continue attribute = db.attach_point parent.otype if attribute if not object[attribute] object[attribute] = [] object[attribute].push parent callback objects db.attach_children = (objects, options, callback) -> ids = objects.map (o) -> o._id # match connections against parent to find children find = { 'parent': {'$in': ids}, 'ctype': {'$nin':[4,6]} } c.connections.find(find).toArray (err, connections) -> if err then throw new Error "error fetching child connections: #{err}" #console.log connections.length, 'connections' childids = connections.map (i) -> i.child otypes = [].concat (options.otype || 1) find = { '_id': { '$in': childids }, 'otype': {'$in':otypes} } sort = { 'child': 1, 'rank':1 } c.objects.find(find).sort(sort).toArray (err, children) -> if err then throw new Error "error loading child objects: #{err}" #console.log children.length, 'children' object_lookup = {} for object in objects object_lookup[object._id] = object child_lookup = {} for child in children child_lookup[child._id] = child # attach 'em for connection in connections object = object_lookup[connection.parent] child = child_lookup[connection.child] if not child continue attribute = db.attach_point child.otype if attribute if not object[attribute] object[attribute] = [] object[attribute].push child callback objects db.all_albums = (callback) -> c.objects.find( { otype: 20 } ).toArray (err, results) -> throw err if err callback results db.all_albums_by_year = (callback) -> filter = {} filter['otype'] = 20 order = {year: 1, album: 1} #order = {album: 1} #order = {genre: 1, album: 1} c.objects.find(filter).sort(order).toArray (err, objects) -> if err then throw new Error "error loading all_albums: #{err}" db.attach_parents objects, { otype: [40,1] }, -> console.log objects.length, 'objects' console.log 'swapping yearless albums to the end' for o, i in objects break if o.year? if i < objects.length objects = [].concat objects[i..], objects[...i] callback objects db.all_albums_by_fileunder = (callback) -> filter = {} filter['otype'] = 20 c.objects.find(filter).toArray (err, objects) -> if err then throw new Error "error loading all_albums: #{err}" db.attach_parents objects, { otype: [40,1] }, -> console.log objects.length, 'objects' console.log 'sorting by fileunder' objects.sort (a, b) -> if not a.fileunder or not a.fileunder[0] or not a.fileunder[0].key return 1 if not b.fileunder or not b.fileunder[0] or not b.fileunder[0].key return -1 if a.fileunder[0].key is b.fileunder[0].key return 0 else if a.fileunder[0].key > b.fileunder[0].key return 1 else return -1 console.log 'done' callback objects db.get_filename = (id, callback) -> bid = new mongodb.ObjectID(id) if filenamecache callback filenamecache[bid] # [parseInt(id)] <- not anymore! else console.log 'loading filename cache...' # if anyone else calls this while it is loading the cache the first time, it # will have a race condition and return undefined FIXME filenamecache = {} tempcache = {} c.objects.find({ filename: {'$exists':1} }, {_id:1, filename:1}).each (err, items) -> if item tempcache[item._id] = item.filename #if bid == _id # console.log "<<<<<<<<< #{item.filename}" else filenamecache = tempcache console.log 'finished loading filename cache' callback filenamecache[bid] db.load_songs_by_filenames = (filenames, callback) -> # this doesn't return the results in order which fuxxors the queue display FIXME filter = { 'otype': 10, 'filename': {'$in': filenames} } c.objects.find(filter).toArray (err, objects) -> if err then throw new Error "database error trying to load_songs_by_filenames #{filenames}: #{err}" for object in objects object.oid = object['_id'] if objects and objects.length # was crashing when queue was empty otype = object.otype lookupcount = 0 if otype is 10 then lookupcount += objects.length if otype < 20 then lookupcount += objects.length if otype < 30 then lookupcount += objects.length debug_limit = 20; finisher = -> lookupcount-- if lookupcount is 0 # now we need to put the results back in the order they were asked for ordered = [] for filename in filenames found = false for object,i in objects if object.filename is filename found = true ordered.push object objects.splice i, 1 break if not found #console.log 'warning: mpd queue item not found in database:', filename console.log 'warning: mpd queue item not found in database' # should be make a fake object to return so the queue prints something? object = filename: filename song: filename _id: 0 ordered.push object # objects really should be empty now for object in objects console.log 'could not match result object with requested filename!' #console.log object.filename #console.log filenames callback ordered for object in objects if otype is 10 then db.load_subobjects object, 1, yes, [5,6], finisher # owner if otype < 20 then db.load_subobjects object, 20, yes, [5,6], finisher # album if otype < 30 then db.load_subobjects object, 30, yes, [5,6], finisher # artist else callback objects # empty class Sequence constructor: (@items, @each_callback) -> @n = 0 next: -> if @n<@items.length @each_callback @items[@n++] else @done_callback @items go: (@done_callback) -> @next() db.count_otypes = (ids, otype, callback) -> c.objects.find( {_id: {'$in': ids}, otype: otype} ).count (err, howmany) -> throw err if err callback howmany db.load_ownerX = (username, callback) -> if username c.objects.findOne { otype: 1, owner: username }, {}, (err, owner) -> if err then throw err callback owner else # none specified, load 'em all c.objects.find( { otype: 1 } ).sort( { owner: 1 } ).toArray (err, owners) -> if err then throw err seq = new Sequence owners, (owner) -> c.connections.find({ parent: owner._id, ctype: 1 }).toArray (err, connections) => ids = for connection in connections then connection.child # don't use 'c'! ### # use map/reduce here FIXME tally = {} db.count_otypes ids, 5, (count) => tally.dirs = count db.count_otypes ids, 10, (count) => tally.songs = count db.count_otypes ids, 20, (count) => tally.albums = count db.count_otypes ids, 30, (count) => tally.artists = count db.count_otypes ids, 40, (count) => tally.fileunders = count db.count_otypes ids, 50, (count) => tally.lists = count _.extend owner, tally ### mapFunc = -> emit this.otype, 1 reduceFunc = (key, values) -> count = 0 count += values[i] for i of values return count c.objects.mapReduce mapFunc, reduceFunc, { query: {_id: {'$in': ids}}, out: { inline: 1 }}, (err, results) => for result in results name = false switch String(result._id) when '5' then name = 'dirs' when '10' then name = 'songs' when '20' then name = 'albums' when '30' then name = 'artists' if name owner[name] = result.value c.connections.find( { parent: owner._id, ctype: 12 } ).count (err, howmany) => throw err if err owner.stars = howmany @next() seq.go -> callback owners db.load_owner_list = (callback) -> c.objects.find( { otype: 1 } ).sort( { owner: 1 } ).toArray (err, owners) -> throw err if err callback owners # still slow, let's try again db.load_owner = (username, callback) -> if username q = { otype: 1, owner: username } else q = { otype: 1} #c.objects.findOne q, {}, (err, owner) -> #oops c.objects.find(q, {}).toArray (err, owner) -> if err then throw err callback owner db.load_users = (callback) -> # load list of owners elapsed = new otto.misc.Elapsed() db.load_owner_list (owners) -> console.log "#{elapsed.seconds()} owners loaded" console.log 'owners.length', owners.length c.connections.find { ctype: 1 }, (err, cursor) => throw err if err console.log "#{elapsed.seconds()} connections loaded" #console.log 'connections.length', connections.length owner_lookup = {} owner_stats = {} cursor.each (err, connection) -> throw err if err if connection owner_lookup[connection.child] = connection.parent else console.log "#{elapsed.seconds()} owner_lookup built" c.objects.find {}, {_id: 1, otype: 1, length: 1}, (err, cursor) -> #c.objects.find({}, {_id: 1, otype: 1, length: 1}).toArray (err, objects) -> throw err if err console.log "#{elapsed.seconds()} objects loaded" #console.log 'objects.length', objects.length cursor.each (err, object) -> if object owner_id = owner_lookup[object._id] if owner_id if not owner_stats[owner_id] owner_stats[owner_id] = {} name = false switch object.otype when 5 then name = 'dirs' when 10 then name = 'songs' when 20 then name = 'albums' when 30 then name = 'artists' if name owner_stats[owner_id][name] = 0 if not owner_stats[owner_id][name] owner_stats[owner_id][name] += 1 if object.otype is 10 and object['length'] owner_stats[owner_id].seconds = 0 if not owner_stats[owner_id].seconds owner_stats[owner_id].seconds += object['length'] else for owner in owners if owner_stats[owner._id] _.extend owner, owner_stats[owner._id] console.log "#{elapsed.seconds()} stats totaled" seq = new Sequence owners, (owner) -> c.connections.find( { parent: owner._id, ctype: 12, rank: {'$gt': 0} } ).count (err, howmany) => throw err if err owner.stars = howmany @next() seq.go -> console.log "#{elapsed.seconds()} stars totaled. done." callback owners db.find_or_create_owner = (username, callback) -> db.load_owner username, (owner) -> if owner[0] callback owner[0] else c.objects.save { otype: 1, owner: username }, (err, newowner) -> if err then throw err callback newowner db.load_list = (listname, callback) -> if listname c.objects.findOne { otype: 50, listname: listname }, {}, (err, list) -> if err then throw err callback list else # non specified, load 'em all c.objects.find( { otype: 1 } ).sort( { owner: 1 } ).toArray (err, lists) -> if err then throw err callback lists db.find_or_create_list = (listname, callback) -> db.load_list listname, (list) -> if list callback list else c.objects.save { otype: 50, listname: listname }, (error, newlist) -> if err then throw err callback newlist db.load_all_lists = (loadobjectstoo, callback) -> _build_results = (alllistitems, objects) -> lists = {} for item in alllistitems if not lists[item._id]? lists[item._id] = [] if objects for object in objects if item.child is object._id lists[item._id].push object break else lists[item._id].push item.child return lists c.connections.find( { ctype: 12 } ).sort( { parent: 1, rank: 1 } ).toArray (err, alllistitems) -> if err then throw err if loadobjectstoo loadids = [] for item in alllistitems loadids.push item.child load_object loadids, no, (objects) -> callback _build_results(alllistitems, objects) else callback _build_results(alllistitems) db.load_stars = (username, loadobjectstoo, callback) -> console.log 'load_stars', username db.load_owner username, (owners) -> if not owners return callback({}) ownerids = [] if owners not instanceof Array owners = [owners] for owner in owners ownerids.push owner._id #console.log 'ownerids', ownerids q = ctype: 12, parent: { $in: ownerids } c.connections.find( q ).sort( { ownerids: 1, rank: -1 } ).toArray (err, allstarreditems) -> #console.log 'allstarreditems', allstarreditems if err then throw err if loadobjectstoo loadids = [] for item in allstarreditems loadids.push item.child db.load_object loadids, no, (objects) -> callback db._load_stars_build_results(owners, allstarreditems, objects) else callback db._load_stars_build_results(owners, allstarreditems) db._load_stars_build_results = (owners, allstarreditems, objects) -> #console.log 'owners', owners #console.log 'allstarreditems', allstarreditems #console.log 'objects', objects stars = {} for owner in owners stars[owner.owner] = [] for item in allstarreditems if owner._id.equals(item.parent) if objects for object in objects if object._id.equals(item.child) _.extend item, object break stars[owner.owner].push item return stars db.add_to_user_list = (username, _id, rank, callback) -> db.find_or_create_owner username, (owner) -> db.load_object _id, no, (object) -> if object c.connections.findOne { ctype: 12, parent: owner._id, child: object._id }, (err, connection) -> if err then throw err if connection connection.rank = rank c.connections.update {'_id': connection._id}, connection, (err) -> if err then throw err callback(true) else db.add_to_connections owner._id, object._id, 12, rank, -> callback(true) else callback(false) db.remove_from_user_list = (username, oid, callback) -> db.load_owner username, (owner) -> if owner db.remove_from_connections owner[0]._id, oid, 12, -> callback true else callback false # too slow (mainly because of toArray it seems) (<- really?) db.Xget_all_song_ids = (callback) -> c.objects.find( { otype: 10 }, { '_id': 1 } ).toArray (err, results) -> ids = [] for row in results ids.push row._id callback ids # too slow, see above db.Xget_random_songs = (howmany=1, callback) -> console.log 'get_random_songs', howmany db.get_all_song_ids (ids) -> console.log 'got all song ids' picked_ids = [] while howmany-- console.log 'pick', howmany picked = Math.floor Math.random() * ids.length picked_ids.push ids[picked] console.log 'loading song objects', picked_ids db.load_object oids=picked_ids, no, (picked_songs) -> console.log 'loaded.' # we now shuffle the order of the returned songs since mongodb will # not return them in the order we asked (which was random), but in # 'natural' order. thus there will be a bias in the order of the random # picks being in the order in which they were loaded into the database shuffle = [] console.log 'shuffling picks' while picked_songs.length console.log 'shuffle', picked_songs.length n = Math.floor Math.random() * picked_songs.length shuffle.push picked_songs[n] picked_songs.splice(n, 1) console.log 'done picking random songs' callback shuffle db.count_all_song_ids = (callback) -> c.objects.find({ otype: 10 }, { '_id': 1 }).count (err, count) -> callback count db.get_song_id_n = (n, callback) -> c.objects.find({ otype: 10 }, { '_id': 1 }).skip(n).limit(1).toArray (err, song) -> callback song[0]._id db.Xget_random_songs = (howmany=1, callback) -> console.log 'get_random_songs', howmany elapsed = new otto.misc.Elapsed() song_ids = [] c.objects.find({ otype: 10 }, {_id: 1}).each (err, song) -> if song song_ids.push song._id else console.log "#{elapsed} all song_ids" count = song_ids.length console.log 'song ids count', count return [] if not count picked_ids = [] howmany = if howmany < count then howmany else count while howmany picked = Math.floor Math.random() * count if song_ids[picked] not in picked_ids picked_ids.push(song_ids[picked]) howmany-- console.log "#{elapsed} picked 'em" db.load_object oids=picked_ids, no, (picked_songs) -> console.log "#{elapsed} song objects loaded" db.attach_parents picked_songs, { otype: 1 }, -> console.log "#{elapsed} parents attached" # we now shuffle the order of the returned songs since mongodb will # not return them in the order we asked (which was random), but in # 'natural' order. thus there will be a bias in the order of the random # picks being in the order in which they were loaded into the database shuffle = [] console.log 'shuffling picks' while picked_songs.length n = Math.floor Math.random() * picked_songs.length shuffle.push picked_songs[n] picked_songs.splice(n, 1) console.log "#{elapsed} shuffeled results. done." callback shuffle db.get_random_songs = (howmany=1, callback) -> console.log 'get_random_songs', howmany elapsed = new otto.misc.Elapsed() song_ids = [] # pick a slate of random songs, skipping anything over 15mins long c.objects.find({ otype: 10, length: {$lt: 900} }, { _id: 1 }).count (err, count) -> console.log "#{elapsed} count songs: #{count}" randomWhere = "(Math.random() > #{(count-howmany)/count})" c.objects.find( {otype: 10, length: {$lt: 900}, $where: randomWhere} ).toArray (err, picked_songs) -> throw err if err console.log "#{elapsed} randomWhere done, #{picked_songs.length} picked_songs" db.attach_parents picked_songs, { otype: 1 }, -> console.log "#{elapsed} parents attached" # shuffle the order of the returned songs since mongodb will # return them in 'natural' order. thus there will be a bias in the order of the random # picks being in the order in which they were loaded into the database shuffle = [] while picked_songs.length n = Math.floor Math.random() * picked_songs.length shuffle.push picked_songs[n] picked_songs.splice(n, 1) callback shuffle db.get_random_starred_songs = (howmany=1, username, callback) -> #console.log 'get_random_starred_songs', howmany, 'for', username db.load_stars username, true, (stars) -> objects = stars[username] if not objects return callback [] #console.log objects.length, 'objects' songs = [] for object in objects if not object.rank > 0 then continue if object.otype is 10 songs.push object # expand albums into songs (still need to handle artists also) async_count = 0; for object in objects if not object.rank > 0 then continue if object.otype is 20 async_count += 1 db.load_subobjects object, 10, no, [5,6], (object) -> async_count -= 1 if object.songs? for song in object.songs songs.push song if async_count is 0 callback db.pick_random_songs_from_array howmany, songs if object.otype is 40 # not actually working yet async_count += 1 db.load_subobjects object, 10, no, [5,6], (objects) -> console.log '^^^^^^^^^^^^^^ otype 40 objects', objects async_count -= 1 if object.songs? for song in object.songs songs.push song if async_count is 0 callback db.pick_random_songs_from_array howmany, songs if async_count is 0 callback db.pick_random_songs_from_array howmany, songs db.pick_random_songs_from_array = (howmany, songs) -> #console.log 'picking random', howmany, 'songs from', songs.length, 'total songs' if howmany > songs.length then howmany = songs.length picked = [] attempts = 0 while picked.length < howmany and attempts < songs.length attempts++ #console.log 'picking' candidate = songs[Math.floor Math.random() * songs.length] alreadypicked = false for pick in picked if candidate.id is pick.id alreadypicked = true break if alreadypicked #console.log 'already' continue #console.log 'picked' picked.push candidate #console.log 'done. got', picked.length return picked db.get_newest_albums = (callback) -> c.objects.find( {otype : 20} ).sort( {_id:-1} ).limit(1000).toArray (err, albums) -> throw err if err for album in albums album.timestamp = Number(album._id.getTimestamp()) db.attach_parents albums, { otype: [1, 30] }, -> callback albums db.get_album = (albumname, callback) -> #console.log 'get_album for', albumname c.objects.findOne {otype: 20, album: albumname}, (err, album)-> if err then throw new Error "error: db.get_album - #{err}" if album db.load_subobjects album, 10, no, [5,6], -> callback album else callback album db.search = (value, callback) -> # (fileunders, albums, songs) = db.search2([[40, value, ['key', 'name', 'artist'], None], # [20, value, 'album', None], # [10, value, 'song', None]]) # #other = db.search(10, value, None, # # ['name', 'artist', 'album', 'song', 'filename', 'title', '.nam', '.ART', '.alb']) # #results = {'fileunders': fileunders, 'albums': albums, 'songs': songs, 'other': other} # results = {'fileunders': fileunders, 'albums': albums, 'songs': songs} # self.finish(json.dumps(results)) regexp = RegExp("\\b#{value}", 'i') c.objects.find({otype: 40, name: regexp}).sort({name: 1}).toArray (err, fileunders)-> if err then throw new Error "error: db.search - #{err}" db.load_subobjects fileunders, 20, no, [5,6], -> c.objects.find({otype: 20, album: regexp}).sort({album: 1}).toArray (err, albums)-> if err then throw new Error "error: db.search - #{err}" # err! this doesn't take a list of objects (yet) db.load_subobjects albums, 30, yes, [5,6], -> c.objects.find({otype: 10, song: regexp}).sort({song: 1}).toArray (err, songs)-> if err then throw new Error "error: db.search - #{err}" for song in songs song.oid = song._id # for backwards compatability c.objects.find({otype: 10, "tags.©wrt": regexp}).sort({"tags.©wrt": 1}).toArray (err, songcomposers)-> if err then throw new Error "error: db.search - #{err}" c.objects.find({otype: 10, "tags.TCOM": regexp}).sort({"tags.TCOM": 1}).toArray (err, songcomposers2)-> if err then throw new Error "error: db.search - #{err}" songcomposers = songcomposers.concat songcomposers2 for song in songcomposers song.oid = song._id # for backwards compatability callback null, fileunders: fileunders, albums: albums, songs: songs, songcomposers: songcomposers db.load_fileunder = (artistid, callback) -> #console.log 'load_fileunder', artistid db.load_object artistid, load_parents=40, (artist) -> callback artist.fileunder return db
20464
_ = require 'underscore' fs = require 'fs' net = require 'net' mongodb = require 'mongodb' child_process = require 'child_process' otto = global.otto module.exports = global.otto.db = do -> # note the 'do' causes the function to be called db = {} mongo = null c = {} #collections_inuse = ['objects', 'connections', 'images', 'accesslog', 'listeners', 'queues', 'events'] collections_inuse = ['objects', 'connections', 'images', 'events'] filenamecache = null db.assemble_dbconf = -> db.dbconf = db: 'otto' host: otto.OTTO_VAR + '/mongod.sock' domainSocket: true #host: 'localhost' #port: 8777 #username: 'admin' # optional #password: '<PASSWORD>' # optional collection: 'sessions' # only for connect-mongo, optional, default: sessions file: "#{otto.OTTO_VAR}/mongodb.conf" db_directory: "#{otto.OTTO_VAR_MONGODB}" #log_file: "#{otto.OTTO_VAR}/mongod.log" pid_file: "#{otto.OTTO_VAR}/mongod.pid" socket_file: "#{otto.OTTO_VAR}/mongod.sock" # must end in .sock for pymongo to work #bind_ip: "localhost" port: 8777 # not really used when using a unix domain socket (but still required?) mongod_executable: "#{otto.MONGOD_EXECUTABLE}" db.dbconf.text = """ # auto generated (and regenerated) by otto, don't edit dbpath = #{db.dbconf.db_directory} pidfilepath = #{db.dbconf.pid_file} bind_ip = #{db.dbconf.socket_file} #bind_ip = #{db.dbconf.bind_ip} port = #{db.dbconf.port} # not really used, socket file on previous line is used instead nounixsocket = true # suppresses creation of a second socket in /tmp nohttpinterface = true journal = on noprealloc = true noauth = true #verbose = true quiet = true profile = 0 # don't report slow queries slowms = 2000 # it still prints them to stdout though, this'll cut that down """ # blank line at the end is so conf file has a closing CR (but not a blank line) return db.dbconf db.spawn = (callback) -> # see if there is an existing mongod by testing a connection to the socket testsocket = net.connect db.dbconf.socket_file, -> # mongod process already exists, don't spawn another one console.log "using existing mongod on #{db.dbconf.socket_file}" testsocket.destroy() callback() testsocket.on 'error', (err) -> #console.log 'error', err testsocket.destroy() console.log "no existing mongod found, spawning a new one on #{db.dbconf.socket_file}" console.log "...using executable #{db.dbconf.mongod_executable}" # we wait until now to write the conf file so we don't step on existing conf files for an existing mongod fs.writeFile db.dbconf.file, db.dbconf.text, (err) -> if err then throw err opts = #stdio: [ 'ignore', 'ignore', 'ignore' ] detached: true #env : # DYLD_FALLBACK_LIBRARY_PATH: otto.OTTO_LIB # LD_LIBRARY_PATH: otto.OTTO_LIB if otto.OTTO_SPAWN_AS_UID opts.uid = otto.OTTO_SPAWN_AS_UID child = child_process.spawn db.dbconf.mongod_executable, ['-f', db.dbconf.file], opts child.unref() mongod_says = (data) -> process.stdout.write 'mongod: ' + data # i could also color this differently, fun! child.stdout.on 'data', mongod_says child.stderr.on 'data', mongod_says child.on 'exit', (code, signal) -> return if otto.exiting console.log "mongod exited with code #{code}" if signal then console.log "...and signal #{signal}" throw new Error 'mongod went away!' # i guess we could wait and try reconnecting? FIXME otto.misc.wait_for_socket db.dbconf.socket_file, 1500, (err) -> # needed to be > 500 for linux if err then throw new Error err callback() db.kill_mongodSync = -> # needs to be Sync so we finish before event loop exits otto.misc.kill_from_pid_fileSync otto.OTTO_VAR + '/mongod.pid' db.init = (callback) -> db.assemble_dbconf() db.spawn -> db.connect db.dbconf.db, db.dbconf.host, db.dbconf.port, (err) -> if err "mongodb does not appear to be running" throw err #process.nextTick -> # not sure this is really necessary callback() db.connect = (database='otto', hostname='localhost', port=27017, callback=no) -> mongo = new mongodb.Db(database, new mongodb.Server(hostname, port, {}), {safe:true, strict:false}) mongo.open (err, p_client) -> if err if callback then callback "error trying to open database #{database} on #{hostname}:#{port}: #{err}" return attach_collections collections_inuse, -> c.objects.count (err, count) -> if err then throw new Error "database error trying to count 'objects' collection: #{err}" console.log "connected to database #{database} on #{hostname}:#{port}" s = if count != 1 then 's' else '' console.log "#{count} object#{s}" if count < 5 console.log 'we have an empty database!' db.emptydatabase = true else db.emptydatabase = false if count > 200000 console.log 'we have a large database!' db.largedatabase = true else db.largedatabase = false #if not c.events.isCapped() # console.log 'events collection is not capped' #else # console.log 'events collection is capped' # couldn't get this to work. perhaps runCommand is missing from my mongodb driver? #if not c.events.isCapped # console.log 'capping events collection' # p_client.runCommand {"convertToCapped": "events", size: 100000} #console.dir p_client #p_client.createCollection 'events', {'capped':true, 'size':100000}, -> #p_client.createCollection 'events', -> # if not c.events.isCapped # console.log 'events collection is not capped' # else # console.log 'events collection is capped' if callback callback() # lookup a list of connections by name and assign them to c.<collection_name> attach_collections = (collection_names, callback) -> lookupcount = collection_names.length if lookupcount for name in collection_names do (name) -> mongo.collection name, (err, collection) -> if err then throw new Error "database error trying to attach to collection '#{name}': #{err}" c[name] = collection if --lookupcount is 0 callback() else callback() db.save_event = (e, callback) -> _id = c.events.save e, (err, eSaved) -> callback eSaved._id db.save_object = (o, callback) -> if not o.otype? and o.otype throw new Error 'object need an otype to be saved' oid = c.objects.save o, (err, oSaved) -> callback oSaved._id db.load_object = (ids=null, load_parents=no, callback) -> # otypes: # 1 owner # 5 dir # 10 song # 20 album # 30 artist # 40 fileunder # 50 list if not ids console.log "load_object: no id(s) given" ids = [] if ids instanceof Array returnarray = true else returnarray = false ids = [ids] bids = ids.map (id) -> new mongodb.ObjectID(String(id)) # get_random_songs needed this for some odd reason! q = { '_id': { '$in': bids } } c.objects.find(q).toArray (err, objects) -> if err then throw new Error "database error trying to load objects #{ids}: #{err}" if not objects callback null return for object in objects object.oid = object['_id'] # for backwards compatability if load_parents lookupcount = objects.length for object in objects db.load_subobjects object, load_parents, yes, [5,6], -> lookupcount-- if lookupcount is 0 if returnarray callback objects else callback objects[0] else if returnarray callback objects else callback objects[0] # alias because i keep mistyping it db.load_objects = db.load_object db.load_subobjects = (objectlist, subotype, parents=no, filteroutctypes=[5,6], callback) -> if not objectlist then throw new Error "load_object: you must supply the object(s)" objects = [].concat objectlist # make array of array or single object lookupcount = objects.length # we should optimize this to be a single query instead of this loop FIXME if not objects.length callback objectlist else for o in objects do (o) -> # makes a closure so we can preserve each version of 'o' across the async calls below if parents q = { child: o._id } else q = { parent: o._id } # sort on _id, rank here? or do we need to sort after since they are not joined? TODO c.connections.find(q).toArray (err, results) -> if err then throw new Error "database error fetching list of subobjects for #{o._id}: #{err}" subids = results.map (i) -> if parents then i.parent else i.child q = { '_id': { '$in': subids } } if subotype q.otype = Number(subotype) c.objects.find(q).toArray (err, subobjects) -> if err then throw new Error "database error loading subobjects for #{o._id}: #{err}" for subobject in subobjects subobject.oid = subobject['_id'] # for backward compability switch Number(subotype) when 40 then o.fileunder = subobjects when 30 then o.artists = subobjects when 20 then o.albums = subobjects when 10 then o.songs = subobjects when 5 then o.dirs = subobjects when 1 then o.owners = subobjects lookupcount-- if lookupcount is 0 callback objectlist db.load_image = (id, size, callback) -> bid = new mongodb.ObjectID(id) if not size then size = 'orig' fields = {} fields["sizes.#{size}"] = 1 c.images.findOne { _id: bid }, fields, (err, image) -> if err callback null return if image and image.sizes and image.sizes[size] callback image.sizes[size].buffer return if size == 'orig' callback null return console.log "image size #{size} not found, trying orig" c.images.findOne { _id: bid }, { 'sizes.orig': 1 }, (err, image) -> if err callback null return if image and image.sizes and image.sizes.orig callback image.sizes.orig.buffer return callback null db.add_to_connections = (parent, child, ctype, rank, callback) -> # ctypes: # 1 dirs, songs, albums, artists to owner # 2 songs to albums # 3 songs to artists # 4 artists to albums # 5 primary albums to artists and/or 'various' # 6 secondary albums to artists and/or 'various' # 7 primary albums to fileunder # 8 secondary albums to fileunder # 10 dirs to dirs # 11 files (songs) to directory # 12 lists # FIXME need to extend this to handle rank and duplicates # upsert pattern yanked from https://github.com/mongodb/node-mongodb-native/issues/29 #id = mongodb.bson_serializer.ObjectID(null) id = mongodb.ObjectID(null) doc = '_id': id 'ctype': ctype 'parent': parent 'child': child 'rank': rank c.connections.update {'_id': id}, doc, upsert: true, (err, connection) -> if err callback null else console.log 'connection._id', connection._id # this isn't the way to get the new _id callback connection db.remove_from_connections = (id, callback) -> c.connections.remove {'_id': id}, (err, num) -> if err then throw new Error err callback num # load album (or artist, or fileunder) details db.album_details = (oid, callback) -> result = null lookupcount = 1 # lookup the id, see if it's an album or an artist or a fileunder db.load_object oid, false, (object) -> result = object if not result callback result return if result.otype in [30, 40] # artist or fileunder db.load_subobjects result, 20, no, [5,6], phasetwo else if result.otype == 20 phasetwo [result] else phasetwo result phasetwo = (subobjects) -> if result.otype in [30, 40] further = result.albums else further = [result] lookupcount = 3*further.length if not further.length callback result else for o in further db.load_subobjects o, 10, no, [5,6], phasethree db.load_subobjects o, 30, yes, [5,6], phasethree db.load_subobjects o, 1, yes, [5,6], phasethree phasethree = (subobjects) -> lookupcount-- if lookupcount is 0 callback result db.starts_with = (value, attribute, otype, nochildren, callback) -> elapsed = new otto.misc.Elapsed() filter = {} params = [] filteroutctypes = [4,6] order = {} order[attribute] = 1 if value.length == 1 and value.toLowerCase() in 'abcdefghijklmnopqrstuvwxyz0123456789' filter[attribute] = ///^#{value}///i else switch value when 'num' filter[attribute] = ///^[0-9]/// when 'other' filter[attribute] = {'$in': [ ///^[^0-9a-z]///i, 'unknown' ]} when 'st' filter[attribute] = ///\bsoundtrack\b///i filteroutctypes = False when 'va' filter[attribute] = { '$in': [ ///\bvarious\b///i, ///\bartists\b///i, ///\bvarious artists\b///i ] } # why yes, i *do* know the third regexp is redundant filteroutctypes = False when 'all' filter = {} order = {year: 1, album: 1} filter['otype'] = otype # i don't think this does anything when used on the objects collection (only connections have ctypes) if filteroutctypes filter['ctype'] = { '$nin': filteroutctypes } objects = [] object_lookup = {} # maybe someday we can figure out how to 'stream' these results (or maybe page 'em) # ...actually, the bottleneck seems to be in rendering large result sets on the client # side, not in getting the results from mongo or transmitting them to the client c.objects.find(filter).sort(order).each (err, object) -> if err then throw new Error "error searching for objects with #{attribute} #{value}: #{err}" if object object.oid = object['_id'] objects.push(object) object_lookup[object._id] = object else console.log "#{elapsed.seconds()} objects loaded" subotype = no if otype == 40 subotype = 20 else if otype > 10 subotype = otype - 10 else subotype = null if !subotype or nochildren callback objects return oids = objects.map (o) -> o._id parents = no # huh? perhaps overriding the value from above? if parents q = { 'child': {'$in': oids} } else q = { 'parent': {'$in': oids} } if filteroutctypes then q.ctype = {'$nin': filteroutctypes} c.connections.find(q).toArray (err, connections) -> if err then throw new Error "database error fetching list of subobjects for starts_with #{attribute} #{value} #{err}" console.log "#{elapsed.seconds()} connections loaded" subattribute = db.attach_point subotype suboids = connections.map (i) -> if parents then i.parent else i.child subobjects = [] subobject_lookup = {} #missing sorting on rank here? FIXME c.objects.find({ '_id': { '$in': suboids }, 'otype': subotype }).each (err, subobject) -> if err then throw new Error "database error loading subobjects for starts_with #{attribute} #{value}: #{err}" if subobject subobject.oid = subobject['_id'] subobjects.push(subobject) subobject_lookup[subobject._id] = subobject else for connection in connections if parents obj = object_lookup[connection.child] sub = subobject_lookup[connection.parent] else obj = object_lookup[connection.parent] sub = subobject_lookup[connection.child] if not sub continue if obj[subattribute] obj[subattribute].push(sub) else obj[subattribute] = [sub] console.log "#{elapsed.seconds()} subobjects loaded" console.log subobjects && subobjects.length callback objects db.attach_point = (otype) -> switch Number(otype) when 40 then return 'fileunder' when 30 then return 'artists' when 20 then return 'albums' when 10 then return 'songs' when 5 then return 'dirs' when 1 then return 'owners' return '' db.attach_parents = (objects, options, callback) -> ids = objects.map (o) -> o._id # match connections against child to find parents find = { 'child': {'$in': ids}, 'ctype': {'$nin':[4,6]} } c.connections.find(find).toArray (err, connections) -> if err then throw new Error "error fetching parent connections: #{err}" console.log connections.length, 'connections' parentids = connections.map (i) -> i.parent otypes = [].concat (options.otype || 40) find = { '_id': { '$in': parentids }, 'otype': {'$in':otypes} } sort = { 'child': 1, 'rank':1 } c.objects.find(find).sort(sort).toArray (err, parents) -> if err then throw new Error "error loading parent objects: #{err}" #console.log parents.length, 'parents' object_lookup = {} for object in objects object_lookup[object._id] = object parent_lookup = {} for parent in parents parent_lookup[parent._id] = parent # attach 'em for connection in connections object = object_lookup[connection.child] parent = parent_lookup[connection.parent] if not parent continue attribute = db.attach_point parent.otype if attribute if not object[attribute] object[attribute] = [] object[attribute].push parent callback objects db.attach_children = (objects, options, callback) -> ids = objects.map (o) -> o._id # match connections against parent to find children find = { 'parent': {'$in': ids}, 'ctype': {'$nin':[4,6]} } c.connections.find(find).toArray (err, connections) -> if err then throw new Error "error fetching child connections: #{err}" #console.log connections.length, 'connections' childids = connections.map (i) -> i.child otypes = [].concat (options.otype || 1) find = { '_id': { '$in': childids }, 'otype': {'$in':otypes} } sort = { 'child': 1, 'rank':1 } c.objects.find(find).sort(sort).toArray (err, children) -> if err then throw new Error "error loading child objects: #{err}" #console.log children.length, 'children' object_lookup = {} for object in objects object_lookup[object._id] = object child_lookup = {} for child in children child_lookup[child._id] = child # attach 'em for connection in connections object = object_lookup[connection.parent] child = child_lookup[connection.child] if not child continue attribute = db.attach_point child.otype if attribute if not object[attribute] object[attribute] = [] object[attribute].push child callback objects db.all_albums = (callback) -> c.objects.find( { otype: 20 } ).toArray (err, results) -> throw err if err callback results db.all_albums_by_year = (callback) -> filter = {} filter['otype'] = 20 order = {year: 1, album: 1} #order = {album: 1} #order = {genre: 1, album: 1} c.objects.find(filter).sort(order).toArray (err, objects) -> if err then throw new Error "error loading all_albums: #{err}" db.attach_parents objects, { otype: [40,1] }, -> console.log objects.length, 'objects' console.log 'swapping yearless albums to the end' for o, i in objects break if o.year? if i < objects.length objects = [].concat objects[i..], objects[...i] callback objects db.all_albums_by_fileunder = (callback) -> filter = {} filter['otype'] = 20 c.objects.find(filter).toArray (err, objects) -> if err then throw new Error "error loading all_albums: #{err}" db.attach_parents objects, { otype: [40,1] }, -> console.log objects.length, 'objects' console.log 'sorting by fileunder' objects.sort (a, b) -> if not a.fileunder or not a.fileunder[0] or not a.fileunder[0].key return 1 if not b.fileunder or not b.fileunder[0] or not b.fileunder[0].key return -1 if a.fileunder[0].key is b.fileunder[0].key return 0 else if a.fileunder[0].key > b.fileunder[0].key return 1 else return -1 console.log 'done' callback objects db.get_filename = (id, callback) -> bid = new mongodb.ObjectID(id) if filenamecache callback filenamecache[bid] # [parseInt(id)] <- not anymore! else console.log 'loading filename cache...' # if anyone else calls this while it is loading the cache the first time, it # will have a race condition and return undefined FIXME filenamecache = {} tempcache = {} c.objects.find({ filename: {'$exists':1} }, {_id:1, filename:1}).each (err, items) -> if item tempcache[item._id] = item.filename #if bid == _id # console.log "<<<<<<<<< #{item.filename}" else filenamecache = tempcache console.log 'finished loading filename cache' callback filenamecache[bid] db.load_songs_by_filenames = (filenames, callback) -> # this doesn't return the results in order which fuxxors the queue display FIXME filter = { 'otype': 10, 'filename': {'$in': filenames} } c.objects.find(filter).toArray (err, objects) -> if err then throw new Error "database error trying to load_songs_by_filenames #{filenames}: #{err}" for object in objects object.oid = object['_id'] if objects and objects.length # was crashing when queue was empty otype = object.otype lookupcount = 0 if otype is 10 then lookupcount += objects.length if otype < 20 then lookupcount += objects.length if otype < 30 then lookupcount += objects.length debug_limit = 20; finisher = -> lookupcount-- if lookupcount is 0 # now we need to put the results back in the order they were asked for ordered = [] for filename in filenames found = false for object,i in objects if object.filename is filename found = true ordered.push object objects.splice i, 1 break if not found #console.log 'warning: mpd queue item not found in database:', filename console.log 'warning: mpd queue item not found in database' # should be make a fake object to return so the queue prints something? object = filename: filename song: filename _id: 0 ordered.push object # objects really should be empty now for object in objects console.log 'could not match result object with requested filename!' #console.log object.filename #console.log filenames callback ordered for object in objects if otype is 10 then db.load_subobjects object, 1, yes, [5,6], finisher # owner if otype < 20 then db.load_subobjects object, 20, yes, [5,6], finisher # album if otype < 30 then db.load_subobjects object, 30, yes, [5,6], finisher # artist else callback objects # empty class Sequence constructor: (@items, @each_callback) -> @n = 0 next: -> if @n<@items.length @each_callback @items[@n++] else @done_callback @items go: (@done_callback) -> @next() db.count_otypes = (ids, otype, callback) -> c.objects.find( {_id: {'$in': ids}, otype: otype} ).count (err, howmany) -> throw err if err callback howmany db.load_ownerX = (username, callback) -> if username c.objects.findOne { otype: 1, owner: username }, {}, (err, owner) -> if err then throw err callback owner else # none specified, load 'em all c.objects.find( { otype: 1 } ).sort( { owner: 1 } ).toArray (err, owners) -> if err then throw err seq = new Sequence owners, (owner) -> c.connections.find({ parent: owner._id, ctype: 1 }).toArray (err, connections) => ids = for connection in connections then connection.child # don't use 'c'! ### # use map/reduce here FIXME tally = {} db.count_otypes ids, 5, (count) => tally.dirs = count db.count_otypes ids, 10, (count) => tally.songs = count db.count_otypes ids, 20, (count) => tally.albums = count db.count_otypes ids, 30, (count) => tally.artists = count db.count_otypes ids, 40, (count) => tally.fileunders = count db.count_otypes ids, 50, (count) => tally.lists = count _.extend owner, tally ### mapFunc = -> emit this.otype, 1 reduceFunc = (key, values) -> count = 0 count += values[i] for i of values return count c.objects.mapReduce mapFunc, reduceFunc, { query: {_id: {'$in': ids}}, out: { inline: 1 }}, (err, results) => for result in results name = false switch String(result._id) when '5' then name = 'dirs' when '10' then name = 'songs' when '20' then name = 'albums' when '30' then name = 'artists' if name owner[name] = result.value c.connections.find( { parent: owner._id, ctype: 12 } ).count (err, howmany) => throw err if err owner.stars = howmany @next() seq.go -> callback owners db.load_owner_list = (callback) -> c.objects.find( { otype: 1 } ).sort( { owner: 1 } ).toArray (err, owners) -> throw err if err callback owners # still slow, let's try again db.load_owner = (username, callback) -> if username q = { otype: 1, owner: username } else q = { otype: 1} #c.objects.findOne q, {}, (err, owner) -> #oops c.objects.find(q, {}).toArray (err, owner) -> if err then throw err callback owner db.load_users = (callback) -> # load list of owners elapsed = new otto.misc.Elapsed() db.load_owner_list (owners) -> console.log "#{elapsed.seconds()} owners loaded" console.log 'owners.length', owners.length c.connections.find { ctype: 1 }, (err, cursor) => throw err if err console.log "#{elapsed.seconds()} connections loaded" #console.log 'connections.length', connections.length owner_lookup = {} owner_stats = {} cursor.each (err, connection) -> throw err if err if connection owner_lookup[connection.child] = connection.parent else console.log "#{elapsed.seconds()} owner_lookup built" c.objects.find {}, {_id: 1, otype: 1, length: 1}, (err, cursor) -> #c.objects.find({}, {_id: 1, otype: 1, length: 1}).toArray (err, objects) -> throw err if err console.log "#{elapsed.seconds()} objects loaded" #console.log 'objects.length', objects.length cursor.each (err, object) -> if object owner_id = owner_lookup[object._id] if owner_id if not owner_stats[owner_id] owner_stats[owner_id] = {} name = false switch object.otype when 5 then name = 'dirs' when 10 then name = 'songs' when 20 then name = 'albums' when 30 then name = 'artists' if name owner_stats[owner_id][name] = 0 if not owner_stats[owner_id][name] owner_stats[owner_id][name] += 1 if object.otype is 10 and object['length'] owner_stats[owner_id].seconds = 0 if not owner_stats[owner_id].seconds owner_stats[owner_id].seconds += object['length'] else for owner in owners if owner_stats[owner._id] _.extend owner, owner_stats[owner._id] console.log "#{elapsed.seconds()} stats totaled" seq = new Sequence owners, (owner) -> c.connections.find( { parent: owner._id, ctype: 12, rank: {'$gt': 0} } ).count (err, howmany) => throw err if err owner.stars = howmany @next() seq.go -> console.log "#{elapsed.seconds()} stars totaled. done." callback owners db.find_or_create_owner = (username, callback) -> db.load_owner username, (owner) -> if owner[0] callback owner[0] else c.objects.save { otype: 1, owner: username }, (err, newowner) -> if err then throw err callback newowner db.load_list = (listname, callback) -> if listname c.objects.findOne { otype: 50, listname: listname }, {}, (err, list) -> if err then throw err callback list else # non specified, load 'em all c.objects.find( { otype: 1 } ).sort( { owner: 1 } ).toArray (err, lists) -> if err then throw err callback lists db.find_or_create_list = (listname, callback) -> db.load_list listname, (list) -> if list callback list else c.objects.save { otype: 50, listname: listname }, (error, newlist) -> if err then throw err callback newlist db.load_all_lists = (loadobjectstoo, callback) -> _build_results = (alllistitems, objects) -> lists = {} for item in alllistitems if not lists[item._id]? lists[item._id] = [] if objects for object in objects if item.child is object._id lists[item._id].push object break else lists[item._id].push item.child return lists c.connections.find( { ctype: 12 } ).sort( { parent: 1, rank: 1 } ).toArray (err, alllistitems) -> if err then throw err if loadobjectstoo loadids = [] for item in alllistitems loadids.push item.child load_object loadids, no, (objects) -> callback _build_results(alllistitems, objects) else callback _build_results(alllistitems) db.load_stars = (username, loadobjectstoo, callback) -> console.log 'load_stars', username db.load_owner username, (owners) -> if not owners return callback({}) ownerids = [] if owners not instanceof Array owners = [owners] for owner in owners ownerids.push owner._id #console.log 'ownerids', ownerids q = ctype: 12, parent: { $in: ownerids } c.connections.find( q ).sort( { ownerids: 1, rank: -1 } ).toArray (err, allstarreditems) -> #console.log 'allstarreditems', allstarreditems if err then throw err if loadobjectstoo loadids = [] for item in allstarreditems loadids.push item.child db.load_object loadids, no, (objects) -> callback db._load_stars_build_results(owners, allstarreditems, objects) else callback db._load_stars_build_results(owners, allstarreditems) db._load_stars_build_results = (owners, allstarreditems, objects) -> #console.log 'owners', owners #console.log 'allstarreditems', allstarreditems #console.log 'objects', objects stars = {} for owner in owners stars[owner.owner] = [] for item in allstarreditems if owner._id.equals(item.parent) if objects for object in objects if object._id.equals(item.child) _.extend item, object break stars[owner.owner].push item return stars db.add_to_user_list = (username, _id, rank, callback) -> db.find_or_create_owner username, (owner) -> db.load_object _id, no, (object) -> if object c.connections.findOne { ctype: 12, parent: owner._id, child: object._id }, (err, connection) -> if err then throw err if connection connection.rank = rank c.connections.update {'_id': connection._id}, connection, (err) -> if err then throw err callback(true) else db.add_to_connections owner._id, object._id, 12, rank, -> callback(true) else callback(false) db.remove_from_user_list = (username, oid, callback) -> db.load_owner username, (owner) -> if owner db.remove_from_connections owner[0]._id, oid, 12, -> callback true else callback false # too slow (mainly because of toArray it seems) (<- really?) db.Xget_all_song_ids = (callback) -> c.objects.find( { otype: 10 }, { '_id': 1 } ).toArray (err, results) -> ids = [] for row in results ids.push row._id callback ids # too slow, see above db.Xget_random_songs = (howmany=1, callback) -> console.log 'get_random_songs', howmany db.get_all_song_ids (ids) -> console.log 'got all song ids' picked_ids = [] while howmany-- console.log 'pick', howmany picked = Math.floor Math.random() * ids.length picked_ids.push ids[picked] console.log 'loading song objects', picked_ids db.load_object oids=picked_ids, no, (picked_songs) -> console.log 'loaded.' # we now shuffle the order of the returned songs since mongodb will # not return them in the order we asked (which was random), but in # 'natural' order. thus there will be a bias in the order of the random # picks being in the order in which they were loaded into the database shuffle = [] console.log 'shuffling picks' while picked_songs.length console.log 'shuffle', picked_songs.length n = Math.floor Math.random() * picked_songs.length shuffle.push picked_songs[n] picked_songs.splice(n, 1) console.log 'done picking random songs' callback shuffle db.count_all_song_ids = (callback) -> c.objects.find({ otype: 10 }, { '_id': 1 }).count (err, count) -> callback count db.get_song_id_n = (n, callback) -> c.objects.find({ otype: 10 }, { '_id': 1 }).skip(n).limit(1).toArray (err, song) -> callback song[0]._id db.Xget_random_songs = (howmany=1, callback) -> console.log 'get_random_songs', howmany elapsed = new otto.misc.Elapsed() song_ids = [] c.objects.find({ otype: 10 }, {_id: 1}).each (err, song) -> if song song_ids.push song._id else console.log "#{elapsed} all song_ids" count = song_ids.length console.log 'song ids count', count return [] if not count picked_ids = [] howmany = if howmany < count then howmany else count while howmany picked = Math.floor Math.random() * count if song_ids[picked] not in picked_ids picked_ids.push(song_ids[picked]) howmany-- console.log "#{elapsed} picked 'em" db.load_object oids=picked_ids, no, (picked_songs) -> console.log "#{elapsed} song objects loaded" db.attach_parents picked_songs, { otype: 1 }, -> console.log "#{elapsed} parents attached" # we now shuffle the order of the returned songs since mongodb will # not return them in the order we asked (which was random), but in # 'natural' order. thus there will be a bias in the order of the random # picks being in the order in which they were loaded into the database shuffle = [] console.log 'shuffling picks' while picked_songs.length n = Math.floor Math.random() * picked_songs.length shuffle.push picked_songs[n] picked_songs.splice(n, 1) console.log "#{elapsed} shuffeled results. done." callback shuffle db.get_random_songs = (howmany=1, callback) -> console.log 'get_random_songs', howmany elapsed = new otto.misc.Elapsed() song_ids = [] # pick a slate of random songs, skipping anything over 15mins long c.objects.find({ otype: 10, length: {$lt: 900} }, { _id: 1 }).count (err, count) -> console.log "#{elapsed} count songs: #{count}" randomWhere = "(Math.random() > #{(count-howmany)/count})" c.objects.find( {otype: 10, length: {$lt: 900}, $where: randomWhere} ).toArray (err, picked_songs) -> throw err if err console.log "#{elapsed} randomWhere done, #{picked_songs.length} picked_songs" db.attach_parents picked_songs, { otype: 1 }, -> console.log "#{elapsed} parents attached" # shuffle the order of the returned songs since mongodb will # return them in 'natural' order. thus there will be a bias in the order of the random # picks being in the order in which they were loaded into the database shuffle = [] while picked_songs.length n = Math.floor Math.random() * picked_songs.length shuffle.push picked_songs[n] picked_songs.splice(n, 1) callback shuffle db.get_random_starred_songs = (howmany=1, username, callback) -> #console.log 'get_random_starred_songs', howmany, 'for', username db.load_stars username, true, (stars) -> objects = stars[username] if not objects return callback [] #console.log objects.length, 'objects' songs = [] for object in objects if not object.rank > 0 then continue if object.otype is 10 songs.push object # expand albums into songs (still need to handle artists also) async_count = 0; for object in objects if not object.rank > 0 then continue if object.otype is 20 async_count += 1 db.load_subobjects object, 10, no, [5,6], (object) -> async_count -= 1 if object.songs? for song in object.songs songs.push song if async_count is 0 callback db.pick_random_songs_from_array howmany, songs if object.otype is 40 # not actually working yet async_count += 1 db.load_subobjects object, 10, no, [5,6], (objects) -> console.log '^^^^^^^^^^^^^^ otype 40 objects', objects async_count -= 1 if object.songs? for song in object.songs songs.push song if async_count is 0 callback db.pick_random_songs_from_array howmany, songs if async_count is 0 callback db.pick_random_songs_from_array howmany, songs db.pick_random_songs_from_array = (howmany, songs) -> #console.log 'picking random', howmany, 'songs from', songs.length, 'total songs' if howmany > songs.length then howmany = songs.length picked = [] attempts = 0 while picked.length < howmany and attempts < songs.length attempts++ #console.log 'picking' candidate = songs[Math.floor Math.random() * songs.length] alreadypicked = false for pick in picked if candidate.id is pick.id alreadypicked = true break if alreadypicked #console.log 'already' continue #console.log 'picked' picked.push candidate #console.log 'done. got', picked.length return picked db.get_newest_albums = (callback) -> c.objects.find( {otype : 20} ).sort( {_id:-1} ).limit(1000).toArray (err, albums) -> throw err if err for album in albums album.timestamp = Number(album._id.getTimestamp()) db.attach_parents albums, { otype: [1, 30] }, -> callback albums db.get_album = (albumname, callback) -> #console.log 'get_album for', albumname c.objects.findOne {otype: 20, album: albumname}, (err, album)-> if err then throw new Error "error: db.get_album - #{err}" if album db.load_subobjects album, 10, no, [5,6], -> callback album else callback album db.search = (value, callback) -> # (fileunders, albums, songs) = db.search2([[40, value, ['key', 'name', 'artist'], None], # [20, value, 'album', None], # [10, value, 'song', None]]) # #other = db.search(10, value, None, # # ['name', 'artist', 'album', 'song', 'filename', 'title', '.nam', '.ART', '.alb']) # #results = {'fileunders': fileunders, 'albums': albums, 'songs': songs, 'other': other} # results = {'fileunders': fileunders, 'albums': albums, 'songs': songs} # self.finish(json.dumps(results)) regexp = RegExp("\\b#{value}", 'i') c.objects.find({otype: 40, name: regexp}).sort({name: 1}).toArray (err, fileunders)-> if err then throw new Error "error: db.search - #{err}" db.load_subobjects fileunders, 20, no, [5,6], -> c.objects.find({otype: 20, album: regexp}).sort({album: 1}).toArray (err, albums)-> if err then throw new Error "error: db.search - #{err}" # err! this doesn't take a list of objects (yet) db.load_subobjects albums, 30, yes, [5,6], -> c.objects.find({otype: 10, song: regexp}).sort({song: 1}).toArray (err, songs)-> if err then throw new Error "error: db.search - #{err}" for song in songs song.oid = song._id # for backwards compatability c.objects.find({otype: 10, "tags.©wrt": regexp}).sort({"tags.©wrt": 1}).toArray (err, songcomposers)-> if err then throw new Error "error: db.search - #{err}" c.objects.find({otype: 10, "tags.TCOM": regexp}).sort({"tags.TCOM": 1}).toArray (err, songcomposers2)-> if err then throw new Error "error: db.search - #{err}" songcomposers = songcomposers.concat songcomposers2 for song in songcomposers song.oid = song._id # for backwards compatability callback null, fileunders: fileunders, albums: albums, songs: songs, songcomposers: songcomposers db.load_fileunder = (artistid, callback) -> #console.log 'load_fileunder', artistid db.load_object artistid, load_parents=40, (artist) -> callback artist.fileunder return db
true
_ = require 'underscore' fs = require 'fs' net = require 'net' mongodb = require 'mongodb' child_process = require 'child_process' otto = global.otto module.exports = global.otto.db = do -> # note the 'do' causes the function to be called db = {} mongo = null c = {} #collections_inuse = ['objects', 'connections', 'images', 'accesslog', 'listeners', 'queues', 'events'] collections_inuse = ['objects', 'connections', 'images', 'events'] filenamecache = null db.assemble_dbconf = -> db.dbconf = db: 'otto' host: otto.OTTO_VAR + '/mongod.sock' domainSocket: true #host: 'localhost' #port: 8777 #username: 'admin' # optional #password: 'PI:PASSWORD:<PASSWORD>END_PI' # optional collection: 'sessions' # only for connect-mongo, optional, default: sessions file: "#{otto.OTTO_VAR}/mongodb.conf" db_directory: "#{otto.OTTO_VAR_MONGODB}" #log_file: "#{otto.OTTO_VAR}/mongod.log" pid_file: "#{otto.OTTO_VAR}/mongod.pid" socket_file: "#{otto.OTTO_VAR}/mongod.sock" # must end in .sock for pymongo to work #bind_ip: "localhost" port: 8777 # not really used when using a unix domain socket (but still required?) mongod_executable: "#{otto.MONGOD_EXECUTABLE}" db.dbconf.text = """ # auto generated (and regenerated) by otto, don't edit dbpath = #{db.dbconf.db_directory} pidfilepath = #{db.dbconf.pid_file} bind_ip = #{db.dbconf.socket_file} #bind_ip = #{db.dbconf.bind_ip} port = #{db.dbconf.port} # not really used, socket file on previous line is used instead nounixsocket = true # suppresses creation of a second socket in /tmp nohttpinterface = true journal = on noprealloc = true noauth = true #verbose = true quiet = true profile = 0 # don't report slow queries slowms = 2000 # it still prints them to stdout though, this'll cut that down """ # blank line at the end is so conf file has a closing CR (but not a blank line) return db.dbconf db.spawn = (callback) -> # see if there is an existing mongod by testing a connection to the socket testsocket = net.connect db.dbconf.socket_file, -> # mongod process already exists, don't spawn another one console.log "using existing mongod on #{db.dbconf.socket_file}" testsocket.destroy() callback() testsocket.on 'error', (err) -> #console.log 'error', err testsocket.destroy() console.log "no existing mongod found, spawning a new one on #{db.dbconf.socket_file}" console.log "...using executable #{db.dbconf.mongod_executable}" # we wait until now to write the conf file so we don't step on existing conf files for an existing mongod fs.writeFile db.dbconf.file, db.dbconf.text, (err) -> if err then throw err opts = #stdio: [ 'ignore', 'ignore', 'ignore' ] detached: true #env : # DYLD_FALLBACK_LIBRARY_PATH: otto.OTTO_LIB # LD_LIBRARY_PATH: otto.OTTO_LIB if otto.OTTO_SPAWN_AS_UID opts.uid = otto.OTTO_SPAWN_AS_UID child = child_process.spawn db.dbconf.mongod_executable, ['-f', db.dbconf.file], opts child.unref() mongod_says = (data) -> process.stdout.write 'mongod: ' + data # i could also color this differently, fun! child.stdout.on 'data', mongod_says child.stderr.on 'data', mongod_says child.on 'exit', (code, signal) -> return if otto.exiting console.log "mongod exited with code #{code}" if signal then console.log "...and signal #{signal}" throw new Error 'mongod went away!' # i guess we could wait and try reconnecting? FIXME otto.misc.wait_for_socket db.dbconf.socket_file, 1500, (err) -> # needed to be > 500 for linux if err then throw new Error err callback() db.kill_mongodSync = -> # needs to be Sync so we finish before event loop exits otto.misc.kill_from_pid_fileSync otto.OTTO_VAR + '/mongod.pid' db.init = (callback) -> db.assemble_dbconf() db.spawn -> db.connect db.dbconf.db, db.dbconf.host, db.dbconf.port, (err) -> if err "mongodb does not appear to be running" throw err #process.nextTick -> # not sure this is really necessary callback() db.connect = (database='otto', hostname='localhost', port=27017, callback=no) -> mongo = new mongodb.Db(database, new mongodb.Server(hostname, port, {}), {safe:true, strict:false}) mongo.open (err, p_client) -> if err if callback then callback "error trying to open database #{database} on #{hostname}:#{port}: #{err}" return attach_collections collections_inuse, -> c.objects.count (err, count) -> if err then throw new Error "database error trying to count 'objects' collection: #{err}" console.log "connected to database #{database} on #{hostname}:#{port}" s = if count != 1 then 's' else '' console.log "#{count} object#{s}" if count < 5 console.log 'we have an empty database!' db.emptydatabase = true else db.emptydatabase = false if count > 200000 console.log 'we have a large database!' db.largedatabase = true else db.largedatabase = false #if not c.events.isCapped() # console.log 'events collection is not capped' #else # console.log 'events collection is capped' # couldn't get this to work. perhaps runCommand is missing from my mongodb driver? #if not c.events.isCapped # console.log 'capping events collection' # p_client.runCommand {"convertToCapped": "events", size: 100000} #console.dir p_client #p_client.createCollection 'events', {'capped':true, 'size':100000}, -> #p_client.createCollection 'events', -> # if not c.events.isCapped # console.log 'events collection is not capped' # else # console.log 'events collection is capped' if callback callback() # lookup a list of connections by name and assign them to c.<collection_name> attach_collections = (collection_names, callback) -> lookupcount = collection_names.length if lookupcount for name in collection_names do (name) -> mongo.collection name, (err, collection) -> if err then throw new Error "database error trying to attach to collection '#{name}': #{err}" c[name] = collection if --lookupcount is 0 callback() else callback() db.save_event = (e, callback) -> _id = c.events.save e, (err, eSaved) -> callback eSaved._id db.save_object = (o, callback) -> if not o.otype? and o.otype throw new Error 'object need an otype to be saved' oid = c.objects.save o, (err, oSaved) -> callback oSaved._id db.load_object = (ids=null, load_parents=no, callback) -> # otypes: # 1 owner # 5 dir # 10 song # 20 album # 30 artist # 40 fileunder # 50 list if not ids console.log "load_object: no id(s) given" ids = [] if ids instanceof Array returnarray = true else returnarray = false ids = [ids] bids = ids.map (id) -> new mongodb.ObjectID(String(id)) # get_random_songs needed this for some odd reason! q = { '_id': { '$in': bids } } c.objects.find(q).toArray (err, objects) -> if err then throw new Error "database error trying to load objects #{ids}: #{err}" if not objects callback null return for object in objects object.oid = object['_id'] # for backwards compatability if load_parents lookupcount = objects.length for object in objects db.load_subobjects object, load_parents, yes, [5,6], -> lookupcount-- if lookupcount is 0 if returnarray callback objects else callback objects[0] else if returnarray callback objects else callback objects[0] # alias because i keep mistyping it db.load_objects = db.load_object db.load_subobjects = (objectlist, subotype, parents=no, filteroutctypes=[5,6], callback) -> if not objectlist then throw new Error "load_object: you must supply the object(s)" objects = [].concat objectlist # make array of array or single object lookupcount = objects.length # we should optimize this to be a single query instead of this loop FIXME if not objects.length callback objectlist else for o in objects do (o) -> # makes a closure so we can preserve each version of 'o' across the async calls below if parents q = { child: o._id } else q = { parent: o._id } # sort on _id, rank here? or do we need to sort after since they are not joined? TODO c.connections.find(q).toArray (err, results) -> if err then throw new Error "database error fetching list of subobjects for #{o._id}: #{err}" subids = results.map (i) -> if parents then i.parent else i.child q = { '_id': { '$in': subids } } if subotype q.otype = Number(subotype) c.objects.find(q).toArray (err, subobjects) -> if err then throw new Error "database error loading subobjects for #{o._id}: #{err}" for subobject in subobjects subobject.oid = subobject['_id'] # for backward compability switch Number(subotype) when 40 then o.fileunder = subobjects when 30 then o.artists = subobjects when 20 then o.albums = subobjects when 10 then o.songs = subobjects when 5 then o.dirs = subobjects when 1 then o.owners = subobjects lookupcount-- if lookupcount is 0 callback objectlist db.load_image = (id, size, callback) -> bid = new mongodb.ObjectID(id) if not size then size = 'orig' fields = {} fields["sizes.#{size}"] = 1 c.images.findOne { _id: bid }, fields, (err, image) -> if err callback null return if image and image.sizes and image.sizes[size] callback image.sizes[size].buffer return if size == 'orig' callback null return console.log "image size #{size} not found, trying orig" c.images.findOne { _id: bid }, { 'sizes.orig': 1 }, (err, image) -> if err callback null return if image and image.sizes and image.sizes.orig callback image.sizes.orig.buffer return callback null db.add_to_connections = (parent, child, ctype, rank, callback) -> # ctypes: # 1 dirs, songs, albums, artists to owner # 2 songs to albums # 3 songs to artists # 4 artists to albums # 5 primary albums to artists and/or 'various' # 6 secondary albums to artists and/or 'various' # 7 primary albums to fileunder # 8 secondary albums to fileunder # 10 dirs to dirs # 11 files (songs) to directory # 12 lists # FIXME need to extend this to handle rank and duplicates # upsert pattern yanked from https://github.com/mongodb/node-mongodb-native/issues/29 #id = mongodb.bson_serializer.ObjectID(null) id = mongodb.ObjectID(null) doc = '_id': id 'ctype': ctype 'parent': parent 'child': child 'rank': rank c.connections.update {'_id': id}, doc, upsert: true, (err, connection) -> if err callback null else console.log 'connection._id', connection._id # this isn't the way to get the new _id callback connection db.remove_from_connections = (id, callback) -> c.connections.remove {'_id': id}, (err, num) -> if err then throw new Error err callback num # load album (or artist, or fileunder) details db.album_details = (oid, callback) -> result = null lookupcount = 1 # lookup the id, see if it's an album or an artist or a fileunder db.load_object oid, false, (object) -> result = object if not result callback result return if result.otype in [30, 40] # artist or fileunder db.load_subobjects result, 20, no, [5,6], phasetwo else if result.otype == 20 phasetwo [result] else phasetwo result phasetwo = (subobjects) -> if result.otype in [30, 40] further = result.albums else further = [result] lookupcount = 3*further.length if not further.length callback result else for o in further db.load_subobjects o, 10, no, [5,6], phasethree db.load_subobjects o, 30, yes, [5,6], phasethree db.load_subobjects o, 1, yes, [5,6], phasethree phasethree = (subobjects) -> lookupcount-- if lookupcount is 0 callback result db.starts_with = (value, attribute, otype, nochildren, callback) -> elapsed = new otto.misc.Elapsed() filter = {} params = [] filteroutctypes = [4,6] order = {} order[attribute] = 1 if value.length == 1 and value.toLowerCase() in 'abcdefghijklmnopqrstuvwxyz0123456789' filter[attribute] = ///^#{value}///i else switch value when 'num' filter[attribute] = ///^[0-9]/// when 'other' filter[attribute] = {'$in': [ ///^[^0-9a-z]///i, 'unknown' ]} when 'st' filter[attribute] = ///\bsoundtrack\b///i filteroutctypes = False when 'va' filter[attribute] = { '$in': [ ///\bvarious\b///i, ///\bartists\b///i, ///\bvarious artists\b///i ] } # why yes, i *do* know the third regexp is redundant filteroutctypes = False when 'all' filter = {} order = {year: 1, album: 1} filter['otype'] = otype # i don't think this does anything when used on the objects collection (only connections have ctypes) if filteroutctypes filter['ctype'] = { '$nin': filteroutctypes } objects = [] object_lookup = {} # maybe someday we can figure out how to 'stream' these results (or maybe page 'em) # ...actually, the bottleneck seems to be in rendering large result sets on the client # side, not in getting the results from mongo or transmitting them to the client c.objects.find(filter).sort(order).each (err, object) -> if err then throw new Error "error searching for objects with #{attribute} #{value}: #{err}" if object object.oid = object['_id'] objects.push(object) object_lookup[object._id] = object else console.log "#{elapsed.seconds()} objects loaded" subotype = no if otype == 40 subotype = 20 else if otype > 10 subotype = otype - 10 else subotype = null if !subotype or nochildren callback objects return oids = objects.map (o) -> o._id parents = no # huh? perhaps overriding the value from above? if parents q = { 'child': {'$in': oids} } else q = { 'parent': {'$in': oids} } if filteroutctypes then q.ctype = {'$nin': filteroutctypes} c.connections.find(q).toArray (err, connections) -> if err then throw new Error "database error fetching list of subobjects for starts_with #{attribute} #{value} #{err}" console.log "#{elapsed.seconds()} connections loaded" subattribute = db.attach_point subotype suboids = connections.map (i) -> if parents then i.parent else i.child subobjects = [] subobject_lookup = {} #missing sorting on rank here? FIXME c.objects.find({ '_id': { '$in': suboids }, 'otype': subotype }).each (err, subobject) -> if err then throw new Error "database error loading subobjects for starts_with #{attribute} #{value}: #{err}" if subobject subobject.oid = subobject['_id'] subobjects.push(subobject) subobject_lookup[subobject._id] = subobject else for connection in connections if parents obj = object_lookup[connection.child] sub = subobject_lookup[connection.parent] else obj = object_lookup[connection.parent] sub = subobject_lookup[connection.child] if not sub continue if obj[subattribute] obj[subattribute].push(sub) else obj[subattribute] = [sub] console.log "#{elapsed.seconds()} subobjects loaded" console.log subobjects && subobjects.length callback objects db.attach_point = (otype) -> switch Number(otype) when 40 then return 'fileunder' when 30 then return 'artists' when 20 then return 'albums' when 10 then return 'songs' when 5 then return 'dirs' when 1 then return 'owners' return '' db.attach_parents = (objects, options, callback) -> ids = objects.map (o) -> o._id # match connections against child to find parents find = { 'child': {'$in': ids}, 'ctype': {'$nin':[4,6]} } c.connections.find(find).toArray (err, connections) -> if err then throw new Error "error fetching parent connections: #{err}" console.log connections.length, 'connections' parentids = connections.map (i) -> i.parent otypes = [].concat (options.otype || 40) find = { '_id': { '$in': parentids }, 'otype': {'$in':otypes} } sort = { 'child': 1, 'rank':1 } c.objects.find(find).sort(sort).toArray (err, parents) -> if err then throw new Error "error loading parent objects: #{err}" #console.log parents.length, 'parents' object_lookup = {} for object in objects object_lookup[object._id] = object parent_lookup = {} for parent in parents parent_lookup[parent._id] = parent # attach 'em for connection in connections object = object_lookup[connection.child] parent = parent_lookup[connection.parent] if not parent continue attribute = db.attach_point parent.otype if attribute if not object[attribute] object[attribute] = [] object[attribute].push parent callback objects db.attach_children = (objects, options, callback) -> ids = objects.map (o) -> o._id # match connections against parent to find children find = { 'parent': {'$in': ids}, 'ctype': {'$nin':[4,6]} } c.connections.find(find).toArray (err, connections) -> if err then throw new Error "error fetching child connections: #{err}" #console.log connections.length, 'connections' childids = connections.map (i) -> i.child otypes = [].concat (options.otype || 1) find = { '_id': { '$in': childids }, 'otype': {'$in':otypes} } sort = { 'child': 1, 'rank':1 } c.objects.find(find).sort(sort).toArray (err, children) -> if err then throw new Error "error loading child objects: #{err}" #console.log children.length, 'children' object_lookup = {} for object in objects object_lookup[object._id] = object child_lookup = {} for child in children child_lookup[child._id] = child # attach 'em for connection in connections object = object_lookup[connection.parent] child = child_lookup[connection.child] if not child continue attribute = db.attach_point child.otype if attribute if not object[attribute] object[attribute] = [] object[attribute].push child callback objects db.all_albums = (callback) -> c.objects.find( { otype: 20 } ).toArray (err, results) -> throw err if err callback results db.all_albums_by_year = (callback) -> filter = {} filter['otype'] = 20 order = {year: 1, album: 1} #order = {album: 1} #order = {genre: 1, album: 1} c.objects.find(filter).sort(order).toArray (err, objects) -> if err then throw new Error "error loading all_albums: #{err}" db.attach_parents objects, { otype: [40,1] }, -> console.log objects.length, 'objects' console.log 'swapping yearless albums to the end' for o, i in objects break if o.year? if i < objects.length objects = [].concat objects[i..], objects[...i] callback objects db.all_albums_by_fileunder = (callback) -> filter = {} filter['otype'] = 20 c.objects.find(filter).toArray (err, objects) -> if err then throw new Error "error loading all_albums: #{err}" db.attach_parents objects, { otype: [40,1] }, -> console.log objects.length, 'objects' console.log 'sorting by fileunder' objects.sort (a, b) -> if not a.fileunder or not a.fileunder[0] or not a.fileunder[0].key return 1 if not b.fileunder or not b.fileunder[0] or not b.fileunder[0].key return -1 if a.fileunder[0].key is b.fileunder[0].key return 0 else if a.fileunder[0].key > b.fileunder[0].key return 1 else return -1 console.log 'done' callback objects db.get_filename = (id, callback) -> bid = new mongodb.ObjectID(id) if filenamecache callback filenamecache[bid] # [parseInt(id)] <- not anymore! else console.log 'loading filename cache...' # if anyone else calls this while it is loading the cache the first time, it # will have a race condition and return undefined FIXME filenamecache = {} tempcache = {} c.objects.find({ filename: {'$exists':1} }, {_id:1, filename:1}).each (err, items) -> if item tempcache[item._id] = item.filename #if bid == _id # console.log "<<<<<<<<< #{item.filename}" else filenamecache = tempcache console.log 'finished loading filename cache' callback filenamecache[bid] db.load_songs_by_filenames = (filenames, callback) -> # this doesn't return the results in order which fuxxors the queue display FIXME filter = { 'otype': 10, 'filename': {'$in': filenames} } c.objects.find(filter).toArray (err, objects) -> if err then throw new Error "database error trying to load_songs_by_filenames #{filenames}: #{err}" for object in objects object.oid = object['_id'] if objects and objects.length # was crashing when queue was empty otype = object.otype lookupcount = 0 if otype is 10 then lookupcount += objects.length if otype < 20 then lookupcount += objects.length if otype < 30 then lookupcount += objects.length debug_limit = 20; finisher = -> lookupcount-- if lookupcount is 0 # now we need to put the results back in the order they were asked for ordered = [] for filename in filenames found = false for object,i in objects if object.filename is filename found = true ordered.push object objects.splice i, 1 break if not found #console.log 'warning: mpd queue item not found in database:', filename console.log 'warning: mpd queue item not found in database' # should be make a fake object to return so the queue prints something? object = filename: filename song: filename _id: 0 ordered.push object # objects really should be empty now for object in objects console.log 'could not match result object with requested filename!' #console.log object.filename #console.log filenames callback ordered for object in objects if otype is 10 then db.load_subobjects object, 1, yes, [5,6], finisher # owner if otype < 20 then db.load_subobjects object, 20, yes, [5,6], finisher # album if otype < 30 then db.load_subobjects object, 30, yes, [5,6], finisher # artist else callback objects # empty class Sequence constructor: (@items, @each_callback) -> @n = 0 next: -> if @n<@items.length @each_callback @items[@n++] else @done_callback @items go: (@done_callback) -> @next() db.count_otypes = (ids, otype, callback) -> c.objects.find( {_id: {'$in': ids}, otype: otype} ).count (err, howmany) -> throw err if err callback howmany db.load_ownerX = (username, callback) -> if username c.objects.findOne { otype: 1, owner: username }, {}, (err, owner) -> if err then throw err callback owner else # none specified, load 'em all c.objects.find( { otype: 1 } ).sort( { owner: 1 } ).toArray (err, owners) -> if err then throw err seq = new Sequence owners, (owner) -> c.connections.find({ parent: owner._id, ctype: 1 }).toArray (err, connections) => ids = for connection in connections then connection.child # don't use 'c'! ### # use map/reduce here FIXME tally = {} db.count_otypes ids, 5, (count) => tally.dirs = count db.count_otypes ids, 10, (count) => tally.songs = count db.count_otypes ids, 20, (count) => tally.albums = count db.count_otypes ids, 30, (count) => tally.artists = count db.count_otypes ids, 40, (count) => tally.fileunders = count db.count_otypes ids, 50, (count) => tally.lists = count _.extend owner, tally ### mapFunc = -> emit this.otype, 1 reduceFunc = (key, values) -> count = 0 count += values[i] for i of values return count c.objects.mapReduce mapFunc, reduceFunc, { query: {_id: {'$in': ids}}, out: { inline: 1 }}, (err, results) => for result in results name = false switch String(result._id) when '5' then name = 'dirs' when '10' then name = 'songs' when '20' then name = 'albums' when '30' then name = 'artists' if name owner[name] = result.value c.connections.find( { parent: owner._id, ctype: 12 } ).count (err, howmany) => throw err if err owner.stars = howmany @next() seq.go -> callback owners db.load_owner_list = (callback) -> c.objects.find( { otype: 1 } ).sort( { owner: 1 } ).toArray (err, owners) -> throw err if err callback owners # still slow, let's try again db.load_owner = (username, callback) -> if username q = { otype: 1, owner: username } else q = { otype: 1} #c.objects.findOne q, {}, (err, owner) -> #oops c.objects.find(q, {}).toArray (err, owner) -> if err then throw err callback owner db.load_users = (callback) -> # load list of owners elapsed = new otto.misc.Elapsed() db.load_owner_list (owners) -> console.log "#{elapsed.seconds()} owners loaded" console.log 'owners.length', owners.length c.connections.find { ctype: 1 }, (err, cursor) => throw err if err console.log "#{elapsed.seconds()} connections loaded" #console.log 'connections.length', connections.length owner_lookup = {} owner_stats = {} cursor.each (err, connection) -> throw err if err if connection owner_lookup[connection.child] = connection.parent else console.log "#{elapsed.seconds()} owner_lookup built" c.objects.find {}, {_id: 1, otype: 1, length: 1}, (err, cursor) -> #c.objects.find({}, {_id: 1, otype: 1, length: 1}).toArray (err, objects) -> throw err if err console.log "#{elapsed.seconds()} objects loaded" #console.log 'objects.length', objects.length cursor.each (err, object) -> if object owner_id = owner_lookup[object._id] if owner_id if not owner_stats[owner_id] owner_stats[owner_id] = {} name = false switch object.otype when 5 then name = 'dirs' when 10 then name = 'songs' when 20 then name = 'albums' when 30 then name = 'artists' if name owner_stats[owner_id][name] = 0 if not owner_stats[owner_id][name] owner_stats[owner_id][name] += 1 if object.otype is 10 and object['length'] owner_stats[owner_id].seconds = 0 if not owner_stats[owner_id].seconds owner_stats[owner_id].seconds += object['length'] else for owner in owners if owner_stats[owner._id] _.extend owner, owner_stats[owner._id] console.log "#{elapsed.seconds()} stats totaled" seq = new Sequence owners, (owner) -> c.connections.find( { parent: owner._id, ctype: 12, rank: {'$gt': 0} } ).count (err, howmany) => throw err if err owner.stars = howmany @next() seq.go -> console.log "#{elapsed.seconds()} stars totaled. done." callback owners db.find_or_create_owner = (username, callback) -> db.load_owner username, (owner) -> if owner[0] callback owner[0] else c.objects.save { otype: 1, owner: username }, (err, newowner) -> if err then throw err callback newowner db.load_list = (listname, callback) -> if listname c.objects.findOne { otype: 50, listname: listname }, {}, (err, list) -> if err then throw err callback list else # non specified, load 'em all c.objects.find( { otype: 1 } ).sort( { owner: 1 } ).toArray (err, lists) -> if err then throw err callback lists db.find_or_create_list = (listname, callback) -> db.load_list listname, (list) -> if list callback list else c.objects.save { otype: 50, listname: listname }, (error, newlist) -> if err then throw err callback newlist db.load_all_lists = (loadobjectstoo, callback) -> _build_results = (alllistitems, objects) -> lists = {} for item in alllistitems if not lists[item._id]? lists[item._id] = [] if objects for object in objects if item.child is object._id lists[item._id].push object break else lists[item._id].push item.child return lists c.connections.find( { ctype: 12 } ).sort( { parent: 1, rank: 1 } ).toArray (err, alllistitems) -> if err then throw err if loadobjectstoo loadids = [] for item in alllistitems loadids.push item.child load_object loadids, no, (objects) -> callback _build_results(alllistitems, objects) else callback _build_results(alllistitems) db.load_stars = (username, loadobjectstoo, callback) -> console.log 'load_stars', username db.load_owner username, (owners) -> if not owners return callback({}) ownerids = [] if owners not instanceof Array owners = [owners] for owner in owners ownerids.push owner._id #console.log 'ownerids', ownerids q = ctype: 12, parent: { $in: ownerids } c.connections.find( q ).sort( { ownerids: 1, rank: -1 } ).toArray (err, allstarreditems) -> #console.log 'allstarreditems', allstarreditems if err then throw err if loadobjectstoo loadids = [] for item in allstarreditems loadids.push item.child db.load_object loadids, no, (objects) -> callback db._load_stars_build_results(owners, allstarreditems, objects) else callback db._load_stars_build_results(owners, allstarreditems) db._load_stars_build_results = (owners, allstarreditems, objects) -> #console.log 'owners', owners #console.log 'allstarreditems', allstarreditems #console.log 'objects', objects stars = {} for owner in owners stars[owner.owner] = [] for item in allstarreditems if owner._id.equals(item.parent) if objects for object in objects if object._id.equals(item.child) _.extend item, object break stars[owner.owner].push item return stars db.add_to_user_list = (username, _id, rank, callback) -> db.find_or_create_owner username, (owner) -> db.load_object _id, no, (object) -> if object c.connections.findOne { ctype: 12, parent: owner._id, child: object._id }, (err, connection) -> if err then throw err if connection connection.rank = rank c.connections.update {'_id': connection._id}, connection, (err) -> if err then throw err callback(true) else db.add_to_connections owner._id, object._id, 12, rank, -> callback(true) else callback(false) db.remove_from_user_list = (username, oid, callback) -> db.load_owner username, (owner) -> if owner db.remove_from_connections owner[0]._id, oid, 12, -> callback true else callback false # too slow (mainly because of toArray it seems) (<- really?) db.Xget_all_song_ids = (callback) -> c.objects.find( { otype: 10 }, { '_id': 1 } ).toArray (err, results) -> ids = [] for row in results ids.push row._id callback ids # too slow, see above db.Xget_random_songs = (howmany=1, callback) -> console.log 'get_random_songs', howmany db.get_all_song_ids (ids) -> console.log 'got all song ids' picked_ids = [] while howmany-- console.log 'pick', howmany picked = Math.floor Math.random() * ids.length picked_ids.push ids[picked] console.log 'loading song objects', picked_ids db.load_object oids=picked_ids, no, (picked_songs) -> console.log 'loaded.' # we now shuffle the order of the returned songs since mongodb will # not return them in the order we asked (which was random), but in # 'natural' order. thus there will be a bias in the order of the random # picks being in the order in which they were loaded into the database shuffle = [] console.log 'shuffling picks' while picked_songs.length console.log 'shuffle', picked_songs.length n = Math.floor Math.random() * picked_songs.length shuffle.push picked_songs[n] picked_songs.splice(n, 1) console.log 'done picking random songs' callback shuffle db.count_all_song_ids = (callback) -> c.objects.find({ otype: 10 }, { '_id': 1 }).count (err, count) -> callback count db.get_song_id_n = (n, callback) -> c.objects.find({ otype: 10 }, { '_id': 1 }).skip(n).limit(1).toArray (err, song) -> callback song[0]._id db.Xget_random_songs = (howmany=1, callback) -> console.log 'get_random_songs', howmany elapsed = new otto.misc.Elapsed() song_ids = [] c.objects.find({ otype: 10 }, {_id: 1}).each (err, song) -> if song song_ids.push song._id else console.log "#{elapsed} all song_ids" count = song_ids.length console.log 'song ids count', count return [] if not count picked_ids = [] howmany = if howmany < count then howmany else count while howmany picked = Math.floor Math.random() * count if song_ids[picked] not in picked_ids picked_ids.push(song_ids[picked]) howmany-- console.log "#{elapsed} picked 'em" db.load_object oids=picked_ids, no, (picked_songs) -> console.log "#{elapsed} song objects loaded" db.attach_parents picked_songs, { otype: 1 }, -> console.log "#{elapsed} parents attached" # we now shuffle the order of the returned songs since mongodb will # not return them in the order we asked (which was random), but in # 'natural' order. thus there will be a bias in the order of the random # picks being in the order in which they were loaded into the database shuffle = [] console.log 'shuffling picks' while picked_songs.length n = Math.floor Math.random() * picked_songs.length shuffle.push picked_songs[n] picked_songs.splice(n, 1) console.log "#{elapsed} shuffeled results. done." callback shuffle db.get_random_songs = (howmany=1, callback) -> console.log 'get_random_songs', howmany elapsed = new otto.misc.Elapsed() song_ids = [] # pick a slate of random songs, skipping anything over 15mins long c.objects.find({ otype: 10, length: {$lt: 900} }, { _id: 1 }).count (err, count) -> console.log "#{elapsed} count songs: #{count}" randomWhere = "(Math.random() > #{(count-howmany)/count})" c.objects.find( {otype: 10, length: {$lt: 900}, $where: randomWhere} ).toArray (err, picked_songs) -> throw err if err console.log "#{elapsed} randomWhere done, #{picked_songs.length} picked_songs" db.attach_parents picked_songs, { otype: 1 }, -> console.log "#{elapsed} parents attached" # shuffle the order of the returned songs since mongodb will # return them in 'natural' order. thus there will be a bias in the order of the random # picks being in the order in which they were loaded into the database shuffle = [] while picked_songs.length n = Math.floor Math.random() * picked_songs.length shuffle.push picked_songs[n] picked_songs.splice(n, 1) callback shuffle db.get_random_starred_songs = (howmany=1, username, callback) -> #console.log 'get_random_starred_songs', howmany, 'for', username db.load_stars username, true, (stars) -> objects = stars[username] if not objects return callback [] #console.log objects.length, 'objects' songs = [] for object in objects if not object.rank > 0 then continue if object.otype is 10 songs.push object # expand albums into songs (still need to handle artists also) async_count = 0; for object in objects if not object.rank > 0 then continue if object.otype is 20 async_count += 1 db.load_subobjects object, 10, no, [5,6], (object) -> async_count -= 1 if object.songs? for song in object.songs songs.push song if async_count is 0 callback db.pick_random_songs_from_array howmany, songs if object.otype is 40 # not actually working yet async_count += 1 db.load_subobjects object, 10, no, [5,6], (objects) -> console.log '^^^^^^^^^^^^^^ otype 40 objects', objects async_count -= 1 if object.songs? for song in object.songs songs.push song if async_count is 0 callback db.pick_random_songs_from_array howmany, songs if async_count is 0 callback db.pick_random_songs_from_array howmany, songs db.pick_random_songs_from_array = (howmany, songs) -> #console.log 'picking random', howmany, 'songs from', songs.length, 'total songs' if howmany > songs.length then howmany = songs.length picked = [] attempts = 0 while picked.length < howmany and attempts < songs.length attempts++ #console.log 'picking' candidate = songs[Math.floor Math.random() * songs.length] alreadypicked = false for pick in picked if candidate.id is pick.id alreadypicked = true break if alreadypicked #console.log 'already' continue #console.log 'picked' picked.push candidate #console.log 'done. got', picked.length return picked db.get_newest_albums = (callback) -> c.objects.find( {otype : 20} ).sort( {_id:-1} ).limit(1000).toArray (err, albums) -> throw err if err for album in albums album.timestamp = Number(album._id.getTimestamp()) db.attach_parents albums, { otype: [1, 30] }, -> callback albums db.get_album = (albumname, callback) -> #console.log 'get_album for', albumname c.objects.findOne {otype: 20, album: albumname}, (err, album)-> if err then throw new Error "error: db.get_album - #{err}" if album db.load_subobjects album, 10, no, [5,6], -> callback album else callback album db.search = (value, callback) -> # (fileunders, albums, songs) = db.search2([[40, value, ['key', 'name', 'artist'], None], # [20, value, 'album', None], # [10, value, 'song', None]]) # #other = db.search(10, value, None, # # ['name', 'artist', 'album', 'song', 'filename', 'title', '.nam', '.ART', '.alb']) # #results = {'fileunders': fileunders, 'albums': albums, 'songs': songs, 'other': other} # results = {'fileunders': fileunders, 'albums': albums, 'songs': songs} # self.finish(json.dumps(results)) regexp = RegExp("\\b#{value}", 'i') c.objects.find({otype: 40, name: regexp}).sort({name: 1}).toArray (err, fileunders)-> if err then throw new Error "error: db.search - #{err}" db.load_subobjects fileunders, 20, no, [5,6], -> c.objects.find({otype: 20, album: regexp}).sort({album: 1}).toArray (err, albums)-> if err then throw new Error "error: db.search - #{err}" # err! this doesn't take a list of objects (yet) db.load_subobjects albums, 30, yes, [5,6], -> c.objects.find({otype: 10, song: regexp}).sort({song: 1}).toArray (err, songs)-> if err then throw new Error "error: db.search - #{err}" for song in songs song.oid = song._id # for backwards compatability c.objects.find({otype: 10, "tags.©wrt": regexp}).sort({"tags.©wrt": 1}).toArray (err, songcomposers)-> if err then throw new Error "error: db.search - #{err}" c.objects.find({otype: 10, "tags.TCOM": regexp}).sort({"tags.TCOM": 1}).toArray (err, songcomposers2)-> if err then throw new Error "error: db.search - #{err}" songcomposers = songcomposers.concat songcomposers2 for song in songcomposers song.oid = song._id # for backwards compatability callback null, fileunders: fileunders, albums: albums, songs: songs, songcomposers: songcomposers db.load_fileunder = (artistid, callback) -> #console.log 'load_fileunder', artistid db.load_object artistid, load_parents=40, (artist) -> callback artist.fileunder return db
[ { "context": "est for Meaning -> qfm\n [S]tories\n [T]odd Barranca\n [S]ong Lyrics\n [S]poopin Right N", "end": 2035, "score": 0.9685910940170288, "start": 2023, "tag": "NAME", "value": "odd Barranca" } ]
issues/2017-10.coffee
STRd6/zine
12
Model = require "model" AchievementStatus = require "../apps/achievement-status" MyBriefcase = require "../apps/my-briefcase" StoryReader = require "../apps/story-reader" Social = require "../social/social" fetchContent = (targetFile, sourcePath=targetFile) -> targetPath = "/issue-10/#{targetFile}" system.readFile targetPath .then (file) -> throw new Error "File not found" unless file .catch -> system.ajax url: "https://danielx.whimsy.space/whimsy.space/V1E10/#{sourcePath}" responseType: "blob" .then (blob) -> system.writeFile targetPath, blob module.exports = -> {ContextMenu, MenuBar, Modal, Progress, Util:{parseMenu}, Window} = system.UI {Achievement, ajax} = system system.Achievement.unlock "Issue 10" fetchContent "Todd Barranca.md" fetchContent "haunted.png" fetchContent "pumpkin.png" fetchContent "Spoopin' Right Now.md" fetchContent "Well I Want to Get a Ride Today.md" launch = (App) -> system.attachApplication App() handlers = Model().include(Social).extend area: -> "2017-10" toddBarranca: -> system.Achievement.unlock "Hard Rain" system.openPath "/issue-10/Todd Barranca.md" achievementStatus: -> launch AchievementStatus myBriefcase: -> launch MyBriefcase pixiePaint: -> system.launchAppByName("Pixie Paint") codeEditor: -> system.launchAppByName("Code Editor") qfm: -> system.launchAppByName("Quest for Meaning") spoopinRightNow: -> system.Achievement.unlock("3spoopy5me") system.openPath("/issue-10/Spoopin' Right Now.md") ride: -> system.Achievement.unlock("Not a real JT song") system.openPath("/issue-10/Well I Want to Get a Ride Today.md") haunted: -> system.openPath("/issue-10/haunted.png") menuBar = MenuBar items: parseMenu """ [A]pps My [B]riefcase [P]ixie Paint [C]ode Editor [G]ames [Q]uest for Meaning -> qfm [S]tories [T]odd Barranca [S]ong Lyrics [S]poopin Right Now [W]ell I Want to Get a Ride Today -> ride [H]aunted #{Social.menuText} [H]elp [A]chievement Status """ handlers: handlers iframe = document.createElement "iframe" iframe.src = "https://www.youtube.com/embed/WcCeyLf2IeE?autoplay=1&controls=0&showinfo=0&iv_load_policy=3" iframe.style = "width: 100%; height: 100%" windowView = Window title: "Whimsy.Space Volume 1 | Episode 10?? | Spoopin Right Now | October 2017" content: iframe iconEmoji: "🎃" menuBar: menuBar.element width: 536 + 8 height: 357 + 46 x: 64 y: 64 windowView.element.querySelector('viewport').style.overflow = "initial" document.body.appendChild windowView.element
99591
Model = require "model" AchievementStatus = require "../apps/achievement-status" MyBriefcase = require "../apps/my-briefcase" StoryReader = require "../apps/story-reader" Social = require "../social/social" fetchContent = (targetFile, sourcePath=targetFile) -> targetPath = "/issue-10/#{targetFile}" system.readFile targetPath .then (file) -> throw new Error "File not found" unless file .catch -> system.ajax url: "https://danielx.whimsy.space/whimsy.space/V1E10/#{sourcePath}" responseType: "blob" .then (blob) -> system.writeFile targetPath, blob module.exports = -> {ContextMenu, MenuBar, Modal, Progress, Util:{parseMenu}, Window} = system.UI {Achievement, ajax} = system system.Achievement.unlock "Issue 10" fetchContent "Todd Barranca.md" fetchContent "haunted.png" fetchContent "pumpkin.png" fetchContent "Spoopin' Right Now.md" fetchContent "Well I Want to Get a Ride Today.md" launch = (App) -> system.attachApplication App() handlers = Model().include(Social).extend area: -> "2017-10" toddBarranca: -> system.Achievement.unlock "Hard Rain" system.openPath "/issue-10/Todd Barranca.md" achievementStatus: -> launch AchievementStatus myBriefcase: -> launch MyBriefcase pixiePaint: -> system.launchAppByName("Pixie Paint") codeEditor: -> system.launchAppByName("Code Editor") qfm: -> system.launchAppByName("Quest for Meaning") spoopinRightNow: -> system.Achievement.unlock("3spoopy5me") system.openPath("/issue-10/Spoopin' Right Now.md") ride: -> system.Achievement.unlock("Not a real JT song") system.openPath("/issue-10/Well I Want to Get a Ride Today.md") haunted: -> system.openPath("/issue-10/haunted.png") menuBar = MenuBar items: parseMenu """ [A]pps My [B]riefcase [P]ixie Paint [C]ode Editor [G]ames [Q]uest for Meaning -> qfm [S]tories [T]<NAME> [S]ong Lyrics [S]poopin Right Now [W]ell I Want to Get a Ride Today -> ride [H]aunted #{Social.menuText} [H]elp [A]chievement Status """ handlers: handlers iframe = document.createElement "iframe" iframe.src = "https://www.youtube.com/embed/WcCeyLf2IeE?autoplay=1&controls=0&showinfo=0&iv_load_policy=3" iframe.style = "width: 100%; height: 100%" windowView = Window title: "Whimsy.Space Volume 1 | Episode 10?? | Spoopin Right Now | October 2017" content: iframe iconEmoji: "🎃" menuBar: menuBar.element width: 536 + 8 height: 357 + 46 x: 64 y: 64 windowView.element.querySelector('viewport').style.overflow = "initial" document.body.appendChild windowView.element
true
Model = require "model" AchievementStatus = require "../apps/achievement-status" MyBriefcase = require "../apps/my-briefcase" StoryReader = require "../apps/story-reader" Social = require "../social/social" fetchContent = (targetFile, sourcePath=targetFile) -> targetPath = "/issue-10/#{targetFile}" system.readFile targetPath .then (file) -> throw new Error "File not found" unless file .catch -> system.ajax url: "https://danielx.whimsy.space/whimsy.space/V1E10/#{sourcePath}" responseType: "blob" .then (blob) -> system.writeFile targetPath, blob module.exports = -> {ContextMenu, MenuBar, Modal, Progress, Util:{parseMenu}, Window} = system.UI {Achievement, ajax} = system system.Achievement.unlock "Issue 10" fetchContent "Todd Barranca.md" fetchContent "haunted.png" fetchContent "pumpkin.png" fetchContent "Spoopin' Right Now.md" fetchContent "Well I Want to Get a Ride Today.md" launch = (App) -> system.attachApplication App() handlers = Model().include(Social).extend area: -> "2017-10" toddBarranca: -> system.Achievement.unlock "Hard Rain" system.openPath "/issue-10/Todd Barranca.md" achievementStatus: -> launch AchievementStatus myBriefcase: -> launch MyBriefcase pixiePaint: -> system.launchAppByName("Pixie Paint") codeEditor: -> system.launchAppByName("Code Editor") qfm: -> system.launchAppByName("Quest for Meaning") spoopinRightNow: -> system.Achievement.unlock("3spoopy5me") system.openPath("/issue-10/Spoopin' Right Now.md") ride: -> system.Achievement.unlock("Not a real JT song") system.openPath("/issue-10/Well I Want to Get a Ride Today.md") haunted: -> system.openPath("/issue-10/haunted.png") menuBar = MenuBar items: parseMenu """ [A]pps My [B]riefcase [P]ixie Paint [C]ode Editor [G]ames [Q]uest for Meaning -> qfm [S]tories [T]PI:NAME:<NAME>END_PI [S]ong Lyrics [S]poopin Right Now [W]ell I Want to Get a Ride Today -> ride [H]aunted #{Social.menuText} [H]elp [A]chievement Status """ handlers: handlers iframe = document.createElement "iframe" iframe.src = "https://www.youtube.com/embed/WcCeyLf2IeE?autoplay=1&controls=0&showinfo=0&iv_load_policy=3" iframe.style = "width: 100%; height: 100%" windowView = Window title: "Whimsy.Space Volume 1 | Episode 10?? | Spoopin Right Now | October 2017" content: iframe iconEmoji: "🎃" menuBar: menuBar.element width: 536 + 8 height: 357 + 46 x: 64 y: 64 windowView.element.querySelector('viewport').style.overflow = "initial" document.body.appendChild windowView.element
[ { "context": "dBeUUID = Uuid.v4()\n\tpers = new Person \n\t\tgiven: \"Slog\"\n\t\t_id: shouldBeUUID\n\t# console.log pers.uri()\n\tp", "end": 4466, "score": 0.9971185922622681, "start": 4462, "tag": "NAME", "value": "Slog" }, { "context": " = schemo.models\n\tauthor = new Person\n\t\...
test/test.coffee
kba/mongoose-jsonld
0
Fs = require 'fs' Async = require 'async' test = require 'tape' Mongoose = require 'mongoose' Schemo = require '../src' Uuid = require 'node-uuid' Utils = require '../src/utils' {inspect} = require 'util' ignore = -> schemo = null _connect = -> schemo = new Schemo( mongoose: Mongoose.createConnection('mongodb://localhost:27018/test') baseURI: 'http://www-test.bib-uni-mannheim.de/infolis' apiPrefix: '/data' schemaPrefix: '/schema' expandContexts: ['basic', { rdfs: 'http://www.w3.org/2000/01/rdf-schema#' infolis: 'http://www-test.bib-uni-mannheim.de/infolis/schema/' infolis_data: 'http://www-test.bib-uni-mannheim.de/infolis/data/' }] schemo: require '../data/simple-schema.coffee' ) _disconnect = -> schemo.mongoose.close() test 'sanity mongoose instance check', (t) -> # _connect() # t.equals new schemo.mongoose.base.constructor, Mongoose # _disconnect() t.end() # Publication = factory.createModel(Mongoose, 'Publication', schemaDefinitions.Publication) # Person = factory.createModel(Mongoose, 'Person', schemaDefinitions.Person) testABoxProfile = (t, profile, cb) -> pub1 = new schemo.models.Publication(title: "The Art of Foo", type: 'article') pub1.jsonldABox {profile:profile}, (err, data) -> t.notOk err, "no error for #{profile}" # if profile is 'compact' # console.log data # Fs.writeFileSync 'abox.jsonld', JSON.stringify(data, null, 2) t.ok data, "result for #{profile}" cb() testTBoxProfile = (t, profile, cb) -> schemo.models.Publication.jsonldTBox {profile: profile}, (err, data) -> t.notOk err, "no error for #{profile}" t.ok data, "result for #{profile}" # console.log data # Fs.writeFileSync 'tbox.jsonld', JSON.stringify(data, null, 2) cb() test 'all profiles yield a result (TBox)', (t) -> _connect() Async.map ['flatten', 'compact', 'expand'], (profile, cb) -> testABoxProfile(t, profile, cb) , (err, result) -> _disconnect() t.end() test 'all profiles yield a result (TBox)', (t) -> _connect() Async.map ['flatten', 'compact', 'expand'], (profile, cb) -> testTBoxProfile(t, profile, cb) , (err, result) -> _disconnect() t.end() # Async.map ['compact'], testTBoxProfile, (err, result) -> t.end() test 'with and without callbacl', (t) -> _connect() pub1 = new schemo.models.Publication(title: "The Art of Foo", type: 'article') pub1.jsonldABox {profile: 'expand'}, (err, dataFromCB) -> schemo.jsonldRapper.convert pub1.jsonldABox(), 'jsonld', 'jsonld', {profile: 'expand'}, (err, dataFromJ2R) -> t.deepEquals dataFromJ2R, dataFromCB, "Callback and return give the same result" _disconnect() t.end() test 'shorten expand with objects', (t) -> _connect() schemo.addClass 'FooBarQuux', { '@context': 'dc:foo': '@id': 'dc:bar' 'dc:quux': '@id': 'dc:froop' blork: '@context': 'dc:frobozz': '@id': 'dc:fnep' type: 'String' } # console.log FooBarQuux.jsonldTBox() schemo.models.FooBarQuux.jsonldTBox {to:'turtle'}, (err, data) -> t.notOk err, "No error" t.ok (data.indexOf('dc:frobozz dc:fnep ;') > -1), "Contains correct Turtle" _disconnect() t.end() test 'Save flat', (t) -> _connect() pub1 = new schemo.models.Publication(title: "The Art of Foo", type: 'article') pub1.save (err, saved) -> t.notOk err, "No error saving" t.ok saved._id, "has an id" _disconnect() t.end() test 'Validate', (t) -> pub2 = new schemo.models.Publication( title: 'bar' type: '!!invalid on purpose!!' ) pub2.validate (err) -> # console.log err t.ok err, 'Should have error' t.ok err.errors.type, 'should be on "type"' t.equals err.errors.type.kind, 'enum', "because value isn't from the enum" t.end() # test.only 'filter_predicate', (t) -> # _connect() # {Publication} = schemo.models # pub = new Publication(title:'foo', type:'book') # pub.save (err) -> # Async.series [ # (cb) -> pub.jsonldABox {filter_predicate:['title']}, (err, data) -> # t.notOk data.type, 'type should be filtered out' # cb() # (cb) -> pub.jsonldABox {filter_predicate:['http://foo/title']}, (err, data) -> # t.notOk data.type, 'here as well' # cb() # ], () -> # _disconnect() # t.end() ignore '_createDocumentFromObject', (t) -> _connect() {Person, Publication} = schemo.models shouldBeUUID = Uuid.v4() pers = new Person given: "Slog" _id: shouldBeUUID # console.log pers.uri() pub = Publication.fromJSON _id: Uuid.v1() title: 'Bar!' author: pers.uri() reader: [pers.uri(), shouldBeUUID, Uuid.v4()] t.equals pub.author, shouldBeUUID, "Publication author should be uuid of author" pers.save (err, persSaved) -> t.notOk err, "No error" t.equals persSaved._id, shouldBeUUID, "Person saved ID as expected" pub.save (err, saved) -> t.notOk err, "No error" # console.log saved # console.log saved.author Publication.findOneAndPopulate {_id: pub._id}, (err, found) -> t.notOk err, "No error" t.ok found.author, "Populated author field" t.equals found.author._id, shouldBeUUID, "Author uuid as expected" t.ok found.reader, "Populated reader field" if found.reader t.equals found.reader.length, 2 # console.log found.author # console.log found _disconnect() t.end() ignore '_findOneAndPopulate', (t) -> _connect() {Person, Publication} = schemo.models author = new Person surname: 'Doe' given: 'John' pub = new Publication title: 'Foo!' author.save (err) -> pub.author = author._id for i in [0...3] pub.reader.push author._id pub.save (err) -> Publication.findOneAndPopulate pub, (err, found) -> found.jsonldABox {to:'turtle'}, (err, rdf) -> t.equals rdf.split(author.uri()).length, 6 _disconnect() t.end() # pub3 = new Publication(pub3_def) # console.log pub3.author # pub3.validate (err) -> # console.log err # console.log pub3 test 'convert to turtle', (t) -> _connect() pub1 = new schemo.models.Publication(title: "The Art of Foo", type: 'article') # console.log pub1.jsonldABox {profile: 'expand'} schemo.jsonldTBox {to:'turtle'}, (err, dat) -> t.ok dat # Utils.dumplog dat # console.log dat _disconnect() t.end() test 'properFields', (t) -> _connect() console.log schemo.models.Publication.properFields() t.end() _disconnect()
2296
Fs = require 'fs' Async = require 'async' test = require 'tape' Mongoose = require 'mongoose' Schemo = require '../src' Uuid = require 'node-uuid' Utils = require '../src/utils' {inspect} = require 'util' ignore = -> schemo = null _connect = -> schemo = new Schemo( mongoose: Mongoose.createConnection('mongodb://localhost:27018/test') baseURI: 'http://www-test.bib-uni-mannheim.de/infolis' apiPrefix: '/data' schemaPrefix: '/schema' expandContexts: ['basic', { rdfs: 'http://www.w3.org/2000/01/rdf-schema#' infolis: 'http://www-test.bib-uni-mannheim.de/infolis/schema/' infolis_data: 'http://www-test.bib-uni-mannheim.de/infolis/data/' }] schemo: require '../data/simple-schema.coffee' ) _disconnect = -> schemo.mongoose.close() test 'sanity mongoose instance check', (t) -> # _connect() # t.equals new schemo.mongoose.base.constructor, Mongoose # _disconnect() t.end() # Publication = factory.createModel(Mongoose, 'Publication', schemaDefinitions.Publication) # Person = factory.createModel(Mongoose, 'Person', schemaDefinitions.Person) testABoxProfile = (t, profile, cb) -> pub1 = new schemo.models.Publication(title: "The Art of Foo", type: 'article') pub1.jsonldABox {profile:profile}, (err, data) -> t.notOk err, "no error for #{profile}" # if profile is 'compact' # console.log data # Fs.writeFileSync 'abox.jsonld', JSON.stringify(data, null, 2) t.ok data, "result for #{profile}" cb() testTBoxProfile = (t, profile, cb) -> schemo.models.Publication.jsonldTBox {profile: profile}, (err, data) -> t.notOk err, "no error for #{profile}" t.ok data, "result for #{profile}" # console.log data # Fs.writeFileSync 'tbox.jsonld', JSON.stringify(data, null, 2) cb() test 'all profiles yield a result (TBox)', (t) -> _connect() Async.map ['flatten', 'compact', 'expand'], (profile, cb) -> testABoxProfile(t, profile, cb) , (err, result) -> _disconnect() t.end() test 'all profiles yield a result (TBox)', (t) -> _connect() Async.map ['flatten', 'compact', 'expand'], (profile, cb) -> testTBoxProfile(t, profile, cb) , (err, result) -> _disconnect() t.end() # Async.map ['compact'], testTBoxProfile, (err, result) -> t.end() test 'with and without callbacl', (t) -> _connect() pub1 = new schemo.models.Publication(title: "The Art of Foo", type: 'article') pub1.jsonldABox {profile: 'expand'}, (err, dataFromCB) -> schemo.jsonldRapper.convert pub1.jsonldABox(), 'jsonld', 'jsonld', {profile: 'expand'}, (err, dataFromJ2R) -> t.deepEquals dataFromJ2R, dataFromCB, "Callback and return give the same result" _disconnect() t.end() test 'shorten expand with objects', (t) -> _connect() schemo.addClass 'FooBarQuux', { '@context': 'dc:foo': '@id': 'dc:bar' 'dc:quux': '@id': 'dc:froop' blork: '@context': 'dc:frobozz': '@id': 'dc:fnep' type: 'String' } # console.log FooBarQuux.jsonldTBox() schemo.models.FooBarQuux.jsonldTBox {to:'turtle'}, (err, data) -> t.notOk err, "No error" t.ok (data.indexOf('dc:frobozz dc:fnep ;') > -1), "Contains correct Turtle" _disconnect() t.end() test 'Save flat', (t) -> _connect() pub1 = new schemo.models.Publication(title: "The Art of Foo", type: 'article') pub1.save (err, saved) -> t.notOk err, "No error saving" t.ok saved._id, "has an id" _disconnect() t.end() test 'Validate', (t) -> pub2 = new schemo.models.Publication( title: 'bar' type: '!!invalid on purpose!!' ) pub2.validate (err) -> # console.log err t.ok err, 'Should have error' t.ok err.errors.type, 'should be on "type"' t.equals err.errors.type.kind, 'enum', "because value isn't from the enum" t.end() # test.only 'filter_predicate', (t) -> # _connect() # {Publication} = schemo.models # pub = new Publication(title:'foo', type:'book') # pub.save (err) -> # Async.series [ # (cb) -> pub.jsonldABox {filter_predicate:['title']}, (err, data) -> # t.notOk data.type, 'type should be filtered out' # cb() # (cb) -> pub.jsonldABox {filter_predicate:['http://foo/title']}, (err, data) -> # t.notOk data.type, 'here as well' # cb() # ], () -> # _disconnect() # t.end() ignore '_createDocumentFromObject', (t) -> _connect() {Person, Publication} = schemo.models shouldBeUUID = Uuid.v4() pers = new Person given: "<NAME>" _id: shouldBeUUID # console.log pers.uri() pub = Publication.fromJSON _id: Uuid.v1() title: 'Bar!' author: pers.uri() reader: [pers.uri(), shouldBeUUID, Uuid.v4()] t.equals pub.author, shouldBeUUID, "Publication author should be uuid of author" pers.save (err, persSaved) -> t.notOk err, "No error" t.equals persSaved._id, shouldBeUUID, "Person saved ID as expected" pub.save (err, saved) -> t.notOk err, "No error" # console.log saved # console.log saved.author Publication.findOneAndPopulate {_id: pub._id}, (err, found) -> t.notOk err, "No error" t.ok found.author, "Populated author field" t.equals found.author._id, shouldBeUUID, "Author uuid as expected" t.ok found.reader, "Populated reader field" if found.reader t.equals found.reader.length, 2 # console.log found.author # console.log found _disconnect() t.end() ignore '_findOneAndPopulate', (t) -> _connect() {Person, Publication} = schemo.models author = new Person surname: '<NAME>' given: '<NAME>' pub = new Publication title: 'Foo!' author.save (err) -> pub.author = author._id for i in [0...3] pub.reader.push author._id pub.save (err) -> Publication.findOneAndPopulate pub, (err, found) -> found.jsonldABox {to:'turtle'}, (err, rdf) -> t.equals rdf.split(author.uri()).length, 6 _disconnect() t.end() # pub3 = new Publication(pub3_def) # console.log pub3.author # pub3.validate (err) -> # console.log err # console.log pub3 test 'convert to turtle', (t) -> _connect() pub1 = new schemo.models.Publication(title: "The Art of Foo", type: 'article') # console.log pub1.jsonldABox {profile: 'expand'} schemo.jsonldTBox {to:'turtle'}, (err, dat) -> t.ok dat # Utils.dumplog dat # console.log dat _disconnect() t.end() test 'properFields', (t) -> _connect() console.log schemo.models.Publication.properFields() t.end() _disconnect()
true
Fs = require 'fs' Async = require 'async' test = require 'tape' Mongoose = require 'mongoose' Schemo = require '../src' Uuid = require 'node-uuid' Utils = require '../src/utils' {inspect} = require 'util' ignore = -> schemo = null _connect = -> schemo = new Schemo( mongoose: Mongoose.createConnection('mongodb://localhost:27018/test') baseURI: 'http://www-test.bib-uni-mannheim.de/infolis' apiPrefix: '/data' schemaPrefix: '/schema' expandContexts: ['basic', { rdfs: 'http://www.w3.org/2000/01/rdf-schema#' infolis: 'http://www-test.bib-uni-mannheim.de/infolis/schema/' infolis_data: 'http://www-test.bib-uni-mannheim.de/infolis/data/' }] schemo: require '../data/simple-schema.coffee' ) _disconnect = -> schemo.mongoose.close() test 'sanity mongoose instance check', (t) -> # _connect() # t.equals new schemo.mongoose.base.constructor, Mongoose # _disconnect() t.end() # Publication = factory.createModel(Mongoose, 'Publication', schemaDefinitions.Publication) # Person = factory.createModel(Mongoose, 'Person', schemaDefinitions.Person) testABoxProfile = (t, profile, cb) -> pub1 = new schemo.models.Publication(title: "The Art of Foo", type: 'article') pub1.jsonldABox {profile:profile}, (err, data) -> t.notOk err, "no error for #{profile}" # if profile is 'compact' # console.log data # Fs.writeFileSync 'abox.jsonld', JSON.stringify(data, null, 2) t.ok data, "result for #{profile}" cb() testTBoxProfile = (t, profile, cb) -> schemo.models.Publication.jsonldTBox {profile: profile}, (err, data) -> t.notOk err, "no error for #{profile}" t.ok data, "result for #{profile}" # console.log data # Fs.writeFileSync 'tbox.jsonld', JSON.stringify(data, null, 2) cb() test 'all profiles yield a result (TBox)', (t) -> _connect() Async.map ['flatten', 'compact', 'expand'], (profile, cb) -> testABoxProfile(t, profile, cb) , (err, result) -> _disconnect() t.end() test 'all profiles yield a result (TBox)', (t) -> _connect() Async.map ['flatten', 'compact', 'expand'], (profile, cb) -> testTBoxProfile(t, profile, cb) , (err, result) -> _disconnect() t.end() # Async.map ['compact'], testTBoxProfile, (err, result) -> t.end() test 'with and without callbacl', (t) -> _connect() pub1 = new schemo.models.Publication(title: "The Art of Foo", type: 'article') pub1.jsonldABox {profile: 'expand'}, (err, dataFromCB) -> schemo.jsonldRapper.convert pub1.jsonldABox(), 'jsonld', 'jsonld', {profile: 'expand'}, (err, dataFromJ2R) -> t.deepEquals dataFromJ2R, dataFromCB, "Callback and return give the same result" _disconnect() t.end() test 'shorten expand with objects', (t) -> _connect() schemo.addClass 'FooBarQuux', { '@context': 'dc:foo': '@id': 'dc:bar' 'dc:quux': '@id': 'dc:froop' blork: '@context': 'dc:frobozz': '@id': 'dc:fnep' type: 'String' } # console.log FooBarQuux.jsonldTBox() schemo.models.FooBarQuux.jsonldTBox {to:'turtle'}, (err, data) -> t.notOk err, "No error" t.ok (data.indexOf('dc:frobozz dc:fnep ;') > -1), "Contains correct Turtle" _disconnect() t.end() test 'Save flat', (t) -> _connect() pub1 = new schemo.models.Publication(title: "The Art of Foo", type: 'article') pub1.save (err, saved) -> t.notOk err, "No error saving" t.ok saved._id, "has an id" _disconnect() t.end() test 'Validate', (t) -> pub2 = new schemo.models.Publication( title: 'bar' type: '!!invalid on purpose!!' ) pub2.validate (err) -> # console.log err t.ok err, 'Should have error' t.ok err.errors.type, 'should be on "type"' t.equals err.errors.type.kind, 'enum', "because value isn't from the enum" t.end() # test.only 'filter_predicate', (t) -> # _connect() # {Publication} = schemo.models # pub = new Publication(title:'foo', type:'book') # pub.save (err) -> # Async.series [ # (cb) -> pub.jsonldABox {filter_predicate:['title']}, (err, data) -> # t.notOk data.type, 'type should be filtered out' # cb() # (cb) -> pub.jsonldABox {filter_predicate:['http://foo/title']}, (err, data) -> # t.notOk data.type, 'here as well' # cb() # ], () -> # _disconnect() # t.end() ignore '_createDocumentFromObject', (t) -> _connect() {Person, Publication} = schemo.models shouldBeUUID = Uuid.v4() pers = new Person given: "PI:NAME:<NAME>END_PI" _id: shouldBeUUID # console.log pers.uri() pub = Publication.fromJSON _id: Uuid.v1() title: 'Bar!' author: pers.uri() reader: [pers.uri(), shouldBeUUID, Uuid.v4()] t.equals pub.author, shouldBeUUID, "Publication author should be uuid of author" pers.save (err, persSaved) -> t.notOk err, "No error" t.equals persSaved._id, shouldBeUUID, "Person saved ID as expected" pub.save (err, saved) -> t.notOk err, "No error" # console.log saved # console.log saved.author Publication.findOneAndPopulate {_id: pub._id}, (err, found) -> t.notOk err, "No error" t.ok found.author, "Populated author field" t.equals found.author._id, shouldBeUUID, "Author uuid as expected" t.ok found.reader, "Populated reader field" if found.reader t.equals found.reader.length, 2 # console.log found.author # console.log found _disconnect() t.end() ignore '_findOneAndPopulate', (t) -> _connect() {Person, Publication} = schemo.models author = new Person surname: 'PI:NAME:<NAME>END_PI' given: 'PI:NAME:<NAME>END_PI' pub = new Publication title: 'Foo!' author.save (err) -> pub.author = author._id for i in [0...3] pub.reader.push author._id pub.save (err) -> Publication.findOneAndPopulate pub, (err, found) -> found.jsonldABox {to:'turtle'}, (err, rdf) -> t.equals rdf.split(author.uri()).length, 6 _disconnect() t.end() # pub3 = new Publication(pub3_def) # console.log pub3.author # pub3.validate (err) -> # console.log err # console.log pub3 test 'convert to turtle', (t) -> _connect() pub1 = new schemo.models.Publication(title: "The Art of Foo", type: 'article') # console.log pub1.jsonldABox {profile: 'expand'} schemo.jsonldTBox {to:'turtle'}, (err, dat) -> t.ok dat # Utils.dumplog dat # console.log dat _disconnect() t.end() test 'properFields', (t) -> _connect() console.log schemo.models.Publication.properFields() t.end() _disconnect()
[ { "context": "oGLib\n# Module | Stat methods\n# Author | Sherif Emabrak\n# Description | proportion for set of elements\n# ", "end": 163, "score": 0.9998790621757507, "start": 149, "tag": "NAME", "value": "Sherif Emabrak" } ]
src/lib/statistics/summary/proportion.coffee
Sherif-Embarak/gp-test
0
# ------------------------------------------------------------------------------ # Project | GoGLib # Module | Stat methods # Author | Sherif Emabrak # Description | proportion for set of elements # ------------------------------------------------------------------------------ proportion = () ->
183035
# ------------------------------------------------------------------------------ # Project | GoGLib # Module | Stat methods # Author | <NAME> # Description | proportion for set of elements # ------------------------------------------------------------------------------ proportion = () ->
true
# ------------------------------------------------------------------------------ # Project | GoGLib # Module | Stat methods # Author | PI:NAME:<NAME>END_PI # Description | proportion for set of elements # ------------------------------------------------------------------------------ proportion = () ->
[ { "context": "user'\nAssert = require 'assert'\n\nuser = new User \"Fake User\", {name: 'fake', type: \"groupchat\"}\nAssert.equal ", "end": 82, "score": 0.6883094310760498, "start": 73, "tag": "USERNAME", "value": "Fake User" }, { "context": "re 'assert'\n\nuser = new User \"Fake Us...
test/user_test.coffee
realmacsoftware/hubot
1
User = require '../src/user' Assert = require 'assert' user = new User "Fake User", {name: 'fake', type: "groupchat"} Assert.equal "Fake User", user.id Assert.equal "groupchat", user.type Assert.equal "fake", user.name user = new User "Fake User", {room: "chat@room.jabber", type: "groupchat"} Assert.equal "Fake User", user.id Assert.equal "chat@room.jabber", user.room Assert.equal "groupchat", user.type Assert.equal "Fake User", user.name # Make sure that if no name is given, we fallback to the ID
12872
User = require '../src/user' Assert = require 'assert' user = new User "Fake User", {name: 'fake', type: "groupchat"} Assert.equal "Fake User", user.id Assert.equal "groupchat", user.type Assert.equal "fake", user.name user = new User "Fake User", {room: "<EMAIL>", type: "groupchat"} Assert.equal "Fake User", user.id Assert.equal "<EMAIL>", user.room Assert.equal "groupchat", user.type Assert.equal "Fake User", user.name # Make sure that if no name is given, we fallback to the ID
true
User = require '../src/user' Assert = require 'assert' user = new User "Fake User", {name: 'fake', type: "groupchat"} Assert.equal "Fake User", user.id Assert.equal "groupchat", user.type Assert.equal "fake", user.name user = new User "Fake User", {room: "PI:EMAIL:<EMAIL>END_PI", type: "groupchat"} Assert.equal "Fake User", user.id Assert.equal "PI:EMAIL:<EMAIL>END_PI", user.room Assert.equal "groupchat", user.type Assert.equal "Fake User", user.name # Make sure that if no name is given, we fallback to the ID
[ { "context": "ain_text_email\n recipient:\n address: 'jane@codecombat.com'\n sender:\n address: config.mail.usern", "end": 479, "score": 0.9998922944068909, "start": 460, "tag": "EMAIL", "value": "jane@codecombat.com" }, { "context": "nt:\n address: req...
server/middleware/contact.coffee
Anagsom/codecombat
2
sendwithus = require '../sendwithus' utils = require '../lib/utils' errors = require '../commons/errors' wrap = require 'co-express' database = require '../commons/database' parse = require '../commons/parse' config = require '../../server_config' module.exports = sendAPCSPAccessRequest: wrap (req, res, next) -> { message, email, name } = req.body context = email_id: sendwithus.templates.plain_text_email recipient: address: 'jane@codecombat.com' sender: address: config.mail.username reply_to: email name: name email_data: subject: 'New APCSP Access Request - ' + email content: message contentHTML: message.replace /\n/g, '\n<br>' sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendParentSignupInstructions: wrap (req, res, next) -> context = email_id: sendwithus.templates.coppa_deny_parent_signup recipient: address: req.body.parentEmail if /@codecombat.com/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendTeacherSignupInstructions: wrap (req, res, next) -> context = email_id: sendwithus.templates.teacher_signup_instructions recipient: address: req.body.teacherEmail bcc: [{address: 'schools@codecombat.com'}] template_data: student_name: req.body.studentName if /@codecombat.com/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendTeacherGameDevProjectShare: wrap (req, res, next) -> context = email_id: sendwithus.templates.teacher_game_dev_project_share recipient: address: req.body.teacherEmail bcc: [{address: 'schools@codecombat.com'}] template_data: student_name: req.user.broadName() code_language: req.body.codeLanguage level_link: "https://codecombat.com/play/game-dev-level/#{req.body.sessionId}" level_name: req.body.levelName if /@codecombat.com/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send()
159183
sendwithus = require '../sendwithus' utils = require '../lib/utils' errors = require '../commons/errors' wrap = require 'co-express' database = require '../commons/database' parse = require '../commons/parse' config = require '../../server_config' module.exports = sendAPCSPAccessRequest: wrap (req, res, next) -> { message, email, name } = req.body context = email_id: sendwithus.templates.plain_text_email recipient: address: '<EMAIL>' sender: address: config.mail.username reply_to: email name: name email_data: subject: 'New APCSP Access Request - ' + email content: message contentHTML: message.replace /\n/g, '\n<br>' sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendParentSignupInstructions: wrap (req, res, next) -> context = email_id: sendwithus.templates.coppa_deny_parent_signup recipient: address: req.body.parentEmail if /<EMAIL>/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendTeacherSignupInstructions: wrap (req, res, next) -> context = email_id: sendwithus.templates.teacher_signup_instructions recipient: address: req.body.teacherEmail bcc: [{address: '<EMAIL>'}] template_data: student_name: req.body.studentName if<EMAIL> /<EMAIL>/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendTeacherGameDevProjectShare: wrap (req, res, next) -> context = email_id: sendwithus.templates.teacher_game_dev_project_share recipient: address: req.body.teacherEmail bcc: [{address: '<EMAIL>'}] template_data: student_name: req.user.broadName() code_language: req.body.codeLanguage level_link: "https://codecombat.com/play/game-dev-level/#{req.body.sessionId}" level_name: req.body.levelName if /<EMAIL>/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send()
true
sendwithus = require '../sendwithus' utils = require '../lib/utils' errors = require '../commons/errors' wrap = require 'co-express' database = require '../commons/database' parse = require '../commons/parse' config = require '../../server_config' module.exports = sendAPCSPAccessRequest: wrap (req, res, next) -> { message, email, name } = req.body context = email_id: sendwithus.templates.plain_text_email recipient: address: 'PI:EMAIL:<EMAIL>END_PI' sender: address: config.mail.username reply_to: email name: name email_data: subject: 'New APCSP Access Request - ' + email content: message contentHTML: message.replace /\n/g, '\n<br>' sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendParentSignupInstructions: wrap (req, res, next) -> context = email_id: sendwithus.templates.coppa_deny_parent_signup recipient: address: req.body.parentEmail if /PI:EMAIL:<EMAIL>END_PI/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendTeacherSignupInstructions: wrap (req, res, next) -> context = email_id: sendwithus.templates.teacher_signup_instructions recipient: address: req.body.teacherEmail bcc: [{address: 'PI:EMAIL:<EMAIL>END_PI'}] template_data: student_name: req.body.studentName ifPI:EMAIL:<EMAIL>END_PI /PI:EMAIL:<EMAIL>END_PI/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send() sendTeacherGameDevProjectShare: wrap (req, res, next) -> context = email_id: sendwithus.templates.teacher_game_dev_project_share recipient: address: req.body.teacherEmail bcc: [{address: 'PI:EMAIL:<EMAIL>END_PI'}] template_data: student_name: req.user.broadName() code_language: req.body.codeLanguage level_link: "https://codecombat.com/play/game-dev-level/#{req.body.sessionId}" level_name: req.body.levelName if /PI:EMAIL:<EMAIL>END_PI/.test(context.recipient.address) or not _.str.trim context.recipient.address console.error "Somehow sent an email with bogus recipient? #{context.recipient.address}" return next(new errors.InternalServerError("Error sending email. Need a valid recipient.")) sendwithus.api.send context, (err, result) -> if err return next(new errors.InternalServerError("Error sending email. Check that it's valid and try again.")) else res.status(200).send()
[ { "context": "$scope.submit = ->\n username = $scope.form.username\n email = $scope.form.email\n passwor", "end": 5463, "score": 0.9381839036941528, "start": 5455, "tag": "USERNAME", "value": "username" }, { "context": " email = $scope.form.email\n pa...
results/front/app/coffee/controllers/main.coffee
gnufede/results
0
MainController = ($scope, $rootScope, resource, $timeout, $routeParams, $location) -> onUserSuccess = (result) -> $scope.user = result if $routeParams.year $scope.getGoalsAndWins() onUserError = (result)-> $location.url("/login") resource.getUser("me").then(onUserSuccess, onUserError) $rootScope.year = $routeParams.year or 0 $rootScope.month = $routeParams.month or 0 $rootScope.day = $routeParams.day or 0 $scope.$watch('dt', () -> if $scope.dt $rootScope.year = $scope.dt.getFullYear() $rootScope.month = $scope.dt.getMonth()+1 $rootScope.day = $scope.dt.getDate() $location.url("/"+$rootScope.year+'/'+$rootScope.month+'/'+$rootScope.day) return ) $scope.getGoalsAndWins = () -> resource.getGoals(weekly=true, year=$rootScope.year, month=$rootScope.month, day=$rootScope.day).then (result) -> $rootScope.weeklyGoalList = result resource.getWins(weekly=true, year=$rootScope.year, month=$rootScope.month, day=$rootScope.day).then (result) -> $rootScope.weeklyWinList = result resource.getGoals(weekly=false, year=$rootScope.year, month=$rootScope.month, day=$rootScope.day).then (result) -> $rootScope.goalList = result resource.getWins(weekly=false, year=$rootScope.year, month=$rootScope.month, day=$rootScope.day).then (result) -> $rootScope.winList = result return $scope.addWinButton = ()-> $scope.showWinDialog = true $scope.closeWinButton = ()-> $scope.showWinDialog = false $scope.addGoalButton = ()-> $scope.showGoalDialog = true $scope.closeGoalButton = ()-> $scope.showGoalDialog = false $scope.isFlashWarnVisible = false $scope.isFlashErrorVisible = false $scope.isFlashSuccessVisible = false $scope.$on("flash", (event, data)-> $scope.isFlashWarnVisible = true if data.type == "warn" $scope.isFlashErrorVisible = true if data.type == "error" $scope.isFlashSuccessVisible = true if data.type == "success" $scope.flashMessage = data.message hideFlash = ()-> $scope.isFlashWarnVisible = false $scope.isFlashErrorVisible = false $scope.isFlashSuccessVisible = false $timeout(hideFlash, 2000) ) $scope.today = () -> $scope.dt = new Date() return if $rootScope.year==0 $scope.today(); else $scope.dt = new Date($rootScope.year, $rootScope.month-1, $rootScope.day) $scope.startingDay = 1 $scope.showWeeks = false $scope.toggleWeeks = () -> $scope.showWeeks = ! $scope.showWeeks return $scope.clear = () -> $scope.dt = null return # $scope.disabled = (date, mode) -> # ( mode == 'day' && ( date.getDay() == 0 || date.getDay() == 6 ) ) $scope.open = ($event) -> $event.preventDefault() $event.stopPropagation() return $scope.opened = true $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'shortDate'] $scope.format = $scope.formats[1] return GoalController = ($scope, $rootScope, $location, $routeParams, $model, $modal, resource) -> $scope.goal = resource.getGoal($routeParams.goalId) $scope.showGoalDialog = true $scope.updateGoal = (goal) -> resource.updateGoal(goal).then -> $scope.showGoalDialog = false return $scope.open = () -> modalInstance = $modal.open( templateUrl: 'myModalContent.html' controller: 'GoalController' ) WinListController = ($scope, $rootScope, $location, $model, resource) -> $scope.addWin = (weekly=false)-> $scope.win.date = $rootScope.year+'-'+$rootScope.month+'-'+$rootScope.day cb = resource.postWin($scope.win, weekly) cb.then (response)-> new_win = $model.make_model("wins",response.data) if weekly $rootScope.weeklyWinList.push(new_win) else $rootScope.winList.push(new_win) $scope.win = {} return $scope.deleteWin = (win) -> win.remove().then -> $scope.getGoalsAndWins() $scope.weeklyWin = {} $scope.win = {} return GoalListController = ($scope, $rootScope, $location, $model, resource) -> $scope.addGoal = (weekly=false)-> $scope.goal.date = $rootScope.year+'-'+$rootScope.month+'-'+$rootScope.day cb = resource.postGoal($scope.goal, weekly) cb.then (response)-> new_goal = $model.make_model("goals",response.data) if weekly $rootScope.weeklyGoalList.push(new_goal) else $rootScope.goalList.push(new_goal) $scope.goal = {} return $scope.deleteGoal = (goal) -> goal.remove().then -> $scope.getGoalsAndWins() #$location.url("/") $scope.goal = {} $scope.weeklyGoal = {} return PublicRegisterController = ($scope, $rootScope, $location, resource, $gmAuth) -> $rootScope.pageTitle = 'Signup' $rootScope.pageSection = 'signup' $scope.form = {"type": "public"} $scope.$watch "site.data.public_register", (value) -> if value == false $location.url("/login") $scope.submit = -> username = $scope.form.username email = $scope.form.email password = $scope.form.password $scope.loading = true onSuccess = (user) -> $location.url("/login") onError = (data) -> $scope.error = true $scope.errorMessage = data.detail promise = resource.register(username, email, password) promise = promise.then(onSuccess, onError) return LoginController = ($scope, $rootScope, $location, $routeParams, resource, $gmAuth) -> $rootScope.pageTitle = 'Login' $rootScope.pageSection = 'login' $scope.form = {} $scope.submit = -> username = $scope.form.username password = $scope.form.password $scope.loading = true onSuccess = (user) -> $gmAuth.setUser(user) $rootScope.auth = user $location.url("/") onError = (data) -> $scope.error = true $scope.errorMessage = data.detail promise = resource.login(username, password) promise = promise.then(onSuccess, onError) promise.then -> $scope.loading = false return TooltipController = ($scope, $document)-> $scope.isTooltipVisible = false $scope.showTooltip = ()-> $scope.isTooltipVisible = !$scope.isTooltipVisible $scope.hideTooltip = ()-> $scope.isTooltipVisible = false module = angular.module("results.controllers.main", []) #module.controller("DateCtrl", ["$scope", "$rootScope", "$routeParams", "$location", "resource", DateCtrl]) module.controller("MainController", ["$scope", "$rootScope","resource", "$timeout", "$routeParams", "$location", MainController]) #module.controller("ContainerController", ["$scope", "$rootScope", "$routeParams", "resource", ContainerController]) module.controller("TooltipController", ["$scope", "$document", TooltipController]) module.controller("LoginController", ["$scope","$rootScope", "$location", "$routeParams", "resource", "$gmAuth", LoginController]) module.controller("GoalController", ["$scope","$rootScope","$location", "$routeParams", "$model", "$modal", "resource", GoalController]) module.controller("GoalListController", ["$scope","$rootScope", "$location", "$model", "resource", GoalListController]) module.controller("WinListController", ["$scope","$rootScope", "$location", "$model", "resource", WinListController]) module.controller("PublicRegisterController", ["$scope", "$rootScope", "$location", "resource", "$gmAuth", PublicRegisterController])
109856
MainController = ($scope, $rootScope, resource, $timeout, $routeParams, $location) -> onUserSuccess = (result) -> $scope.user = result if $routeParams.year $scope.getGoalsAndWins() onUserError = (result)-> $location.url("/login") resource.getUser("me").then(onUserSuccess, onUserError) $rootScope.year = $routeParams.year or 0 $rootScope.month = $routeParams.month or 0 $rootScope.day = $routeParams.day or 0 $scope.$watch('dt', () -> if $scope.dt $rootScope.year = $scope.dt.getFullYear() $rootScope.month = $scope.dt.getMonth()+1 $rootScope.day = $scope.dt.getDate() $location.url("/"+$rootScope.year+'/'+$rootScope.month+'/'+$rootScope.day) return ) $scope.getGoalsAndWins = () -> resource.getGoals(weekly=true, year=$rootScope.year, month=$rootScope.month, day=$rootScope.day).then (result) -> $rootScope.weeklyGoalList = result resource.getWins(weekly=true, year=$rootScope.year, month=$rootScope.month, day=$rootScope.day).then (result) -> $rootScope.weeklyWinList = result resource.getGoals(weekly=false, year=$rootScope.year, month=$rootScope.month, day=$rootScope.day).then (result) -> $rootScope.goalList = result resource.getWins(weekly=false, year=$rootScope.year, month=$rootScope.month, day=$rootScope.day).then (result) -> $rootScope.winList = result return $scope.addWinButton = ()-> $scope.showWinDialog = true $scope.closeWinButton = ()-> $scope.showWinDialog = false $scope.addGoalButton = ()-> $scope.showGoalDialog = true $scope.closeGoalButton = ()-> $scope.showGoalDialog = false $scope.isFlashWarnVisible = false $scope.isFlashErrorVisible = false $scope.isFlashSuccessVisible = false $scope.$on("flash", (event, data)-> $scope.isFlashWarnVisible = true if data.type == "warn" $scope.isFlashErrorVisible = true if data.type == "error" $scope.isFlashSuccessVisible = true if data.type == "success" $scope.flashMessage = data.message hideFlash = ()-> $scope.isFlashWarnVisible = false $scope.isFlashErrorVisible = false $scope.isFlashSuccessVisible = false $timeout(hideFlash, 2000) ) $scope.today = () -> $scope.dt = new Date() return if $rootScope.year==0 $scope.today(); else $scope.dt = new Date($rootScope.year, $rootScope.month-1, $rootScope.day) $scope.startingDay = 1 $scope.showWeeks = false $scope.toggleWeeks = () -> $scope.showWeeks = ! $scope.showWeeks return $scope.clear = () -> $scope.dt = null return # $scope.disabled = (date, mode) -> # ( mode == 'day' && ( date.getDay() == 0 || date.getDay() == 6 ) ) $scope.open = ($event) -> $event.preventDefault() $event.stopPropagation() return $scope.opened = true $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'shortDate'] $scope.format = $scope.formats[1] return GoalController = ($scope, $rootScope, $location, $routeParams, $model, $modal, resource) -> $scope.goal = resource.getGoal($routeParams.goalId) $scope.showGoalDialog = true $scope.updateGoal = (goal) -> resource.updateGoal(goal).then -> $scope.showGoalDialog = false return $scope.open = () -> modalInstance = $modal.open( templateUrl: 'myModalContent.html' controller: 'GoalController' ) WinListController = ($scope, $rootScope, $location, $model, resource) -> $scope.addWin = (weekly=false)-> $scope.win.date = $rootScope.year+'-'+$rootScope.month+'-'+$rootScope.day cb = resource.postWin($scope.win, weekly) cb.then (response)-> new_win = $model.make_model("wins",response.data) if weekly $rootScope.weeklyWinList.push(new_win) else $rootScope.winList.push(new_win) $scope.win = {} return $scope.deleteWin = (win) -> win.remove().then -> $scope.getGoalsAndWins() $scope.weeklyWin = {} $scope.win = {} return GoalListController = ($scope, $rootScope, $location, $model, resource) -> $scope.addGoal = (weekly=false)-> $scope.goal.date = $rootScope.year+'-'+$rootScope.month+'-'+$rootScope.day cb = resource.postGoal($scope.goal, weekly) cb.then (response)-> new_goal = $model.make_model("goals",response.data) if weekly $rootScope.weeklyGoalList.push(new_goal) else $rootScope.goalList.push(new_goal) $scope.goal = {} return $scope.deleteGoal = (goal) -> goal.remove().then -> $scope.getGoalsAndWins() #$location.url("/") $scope.goal = {} $scope.weeklyGoal = {} return PublicRegisterController = ($scope, $rootScope, $location, resource, $gmAuth) -> $rootScope.pageTitle = 'Signup' $rootScope.pageSection = 'signup' $scope.form = {"type": "public"} $scope.$watch "site.data.public_register", (value) -> if value == false $location.url("/login") $scope.submit = -> username = $scope.form.username email = $scope.form.email password = <PASSWORD> $scope.loading = true onSuccess = (user) -> $location.url("/login") onError = (data) -> $scope.error = true $scope.errorMessage = data.detail promise = resource.register(username, email, password) promise = promise.then(onSuccess, onError) return LoginController = ($scope, $rootScope, $location, $routeParams, resource, $gmAuth) -> $rootScope.pageTitle = 'Login' $rootScope.pageSection = 'login' $scope.form = {} $scope.submit = -> username = $scope.form.username password = $scope.<PASSWORD> $scope.loading = true onSuccess = (user) -> $gmAuth.setUser(user) $rootScope.auth = user $location.url("/") onError = (data) -> $scope.error = true $scope.errorMessage = data.detail promise = resource.login(username, password) promise = promise.then(onSuccess, onError) promise.then -> $scope.loading = false return TooltipController = ($scope, $document)-> $scope.isTooltipVisible = false $scope.showTooltip = ()-> $scope.isTooltipVisible = !$scope.isTooltipVisible $scope.hideTooltip = ()-> $scope.isTooltipVisible = false module = angular.module("results.controllers.main", []) #module.controller("DateCtrl", ["$scope", "$rootScope", "$routeParams", "$location", "resource", DateCtrl]) module.controller("MainController", ["$scope", "$rootScope","resource", "$timeout", "$routeParams", "$location", MainController]) #module.controller("ContainerController", ["$scope", "$rootScope", "$routeParams", "resource", ContainerController]) module.controller("TooltipController", ["$scope", "$document", TooltipController]) module.controller("LoginController", ["$scope","$rootScope", "$location", "$routeParams", "resource", "$gmAuth", LoginController]) module.controller("GoalController", ["$scope","$rootScope","$location", "$routeParams", "$model", "$modal", "resource", GoalController]) module.controller("GoalListController", ["$scope","$rootScope", "$location", "$model", "resource", GoalListController]) module.controller("WinListController", ["$scope","$rootScope", "$location", "$model", "resource", WinListController]) module.controller("PublicRegisterController", ["$scope", "$rootScope", "$location", "resource", "$gmAuth", PublicRegisterController])
true
MainController = ($scope, $rootScope, resource, $timeout, $routeParams, $location) -> onUserSuccess = (result) -> $scope.user = result if $routeParams.year $scope.getGoalsAndWins() onUserError = (result)-> $location.url("/login") resource.getUser("me").then(onUserSuccess, onUserError) $rootScope.year = $routeParams.year or 0 $rootScope.month = $routeParams.month or 0 $rootScope.day = $routeParams.day or 0 $scope.$watch('dt', () -> if $scope.dt $rootScope.year = $scope.dt.getFullYear() $rootScope.month = $scope.dt.getMonth()+1 $rootScope.day = $scope.dt.getDate() $location.url("/"+$rootScope.year+'/'+$rootScope.month+'/'+$rootScope.day) return ) $scope.getGoalsAndWins = () -> resource.getGoals(weekly=true, year=$rootScope.year, month=$rootScope.month, day=$rootScope.day).then (result) -> $rootScope.weeklyGoalList = result resource.getWins(weekly=true, year=$rootScope.year, month=$rootScope.month, day=$rootScope.day).then (result) -> $rootScope.weeklyWinList = result resource.getGoals(weekly=false, year=$rootScope.year, month=$rootScope.month, day=$rootScope.day).then (result) -> $rootScope.goalList = result resource.getWins(weekly=false, year=$rootScope.year, month=$rootScope.month, day=$rootScope.day).then (result) -> $rootScope.winList = result return $scope.addWinButton = ()-> $scope.showWinDialog = true $scope.closeWinButton = ()-> $scope.showWinDialog = false $scope.addGoalButton = ()-> $scope.showGoalDialog = true $scope.closeGoalButton = ()-> $scope.showGoalDialog = false $scope.isFlashWarnVisible = false $scope.isFlashErrorVisible = false $scope.isFlashSuccessVisible = false $scope.$on("flash", (event, data)-> $scope.isFlashWarnVisible = true if data.type == "warn" $scope.isFlashErrorVisible = true if data.type == "error" $scope.isFlashSuccessVisible = true if data.type == "success" $scope.flashMessage = data.message hideFlash = ()-> $scope.isFlashWarnVisible = false $scope.isFlashErrorVisible = false $scope.isFlashSuccessVisible = false $timeout(hideFlash, 2000) ) $scope.today = () -> $scope.dt = new Date() return if $rootScope.year==0 $scope.today(); else $scope.dt = new Date($rootScope.year, $rootScope.month-1, $rootScope.day) $scope.startingDay = 1 $scope.showWeeks = false $scope.toggleWeeks = () -> $scope.showWeeks = ! $scope.showWeeks return $scope.clear = () -> $scope.dt = null return # $scope.disabled = (date, mode) -> # ( mode == 'day' && ( date.getDay() == 0 || date.getDay() == 6 ) ) $scope.open = ($event) -> $event.preventDefault() $event.stopPropagation() return $scope.opened = true $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'shortDate'] $scope.format = $scope.formats[1] return GoalController = ($scope, $rootScope, $location, $routeParams, $model, $modal, resource) -> $scope.goal = resource.getGoal($routeParams.goalId) $scope.showGoalDialog = true $scope.updateGoal = (goal) -> resource.updateGoal(goal).then -> $scope.showGoalDialog = false return $scope.open = () -> modalInstance = $modal.open( templateUrl: 'myModalContent.html' controller: 'GoalController' ) WinListController = ($scope, $rootScope, $location, $model, resource) -> $scope.addWin = (weekly=false)-> $scope.win.date = $rootScope.year+'-'+$rootScope.month+'-'+$rootScope.day cb = resource.postWin($scope.win, weekly) cb.then (response)-> new_win = $model.make_model("wins",response.data) if weekly $rootScope.weeklyWinList.push(new_win) else $rootScope.winList.push(new_win) $scope.win = {} return $scope.deleteWin = (win) -> win.remove().then -> $scope.getGoalsAndWins() $scope.weeklyWin = {} $scope.win = {} return GoalListController = ($scope, $rootScope, $location, $model, resource) -> $scope.addGoal = (weekly=false)-> $scope.goal.date = $rootScope.year+'-'+$rootScope.month+'-'+$rootScope.day cb = resource.postGoal($scope.goal, weekly) cb.then (response)-> new_goal = $model.make_model("goals",response.data) if weekly $rootScope.weeklyGoalList.push(new_goal) else $rootScope.goalList.push(new_goal) $scope.goal = {} return $scope.deleteGoal = (goal) -> goal.remove().then -> $scope.getGoalsAndWins() #$location.url("/") $scope.goal = {} $scope.weeklyGoal = {} return PublicRegisterController = ($scope, $rootScope, $location, resource, $gmAuth) -> $rootScope.pageTitle = 'Signup' $rootScope.pageSection = 'signup' $scope.form = {"type": "public"} $scope.$watch "site.data.public_register", (value) -> if value == false $location.url("/login") $scope.submit = -> username = $scope.form.username email = $scope.form.email password = PI:PASSWORD:<PASSWORD>END_PI $scope.loading = true onSuccess = (user) -> $location.url("/login") onError = (data) -> $scope.error = true $scope.errorMessage = data.detail promise = resource.register(username, email, password) promise = promise.then(onSuccess, onError) return LoginController = ($scope, $rootScope, $location, $routeParams, resource, $gmAuth) -> $rootScope.pageTitle = 'Login' $rootScope.pageSection = 'login' $scope.form = {} $scope.submit = -> username = $scope.form.username password = $scope.PI:PASSWORD:<PASSWORD>END_PI $scope.loading = true onSuccess = (user) -> $gmAuth.setUser(user) $rootScope.auth = user $location.url("/") onError = (data) -> $scope.error = true $scope.errorMessage = data.detail promise = resource.login(username, password) promise = promise.then(onSuccess, onError) promise.then -> $scope.loading = false return TooltipController = ($scope, $document)-> $scope.isTooltipVisible = false $scope.showTooltip = ()-> $scope.isTooltipVisible = !$scope.isTooltipVisible $scope.hideTooltip = ()-> $scope.isTooltipVisible = false module = angular.module("results.controllers.main", []) #module.controller("DateCtrl", ["$scope", "$rootScope", "$routeParams", "$location", "resource", DateCtrl]) module.controller("MainController", ["$scope", "$rootScope","resource", "$timeout", "$routeParams", "$location", MainController]) #module.controller("ContainerController", ["$scope", "$rootScope", "$routeParams", "resource", ContainerController]) module.controller("TooltipController", ["$scope", "$document", TooltipController]) module.controller("LoginController", ["$scope","$rootScope", "$location", "$routeParams", "resource", "$gmAuth", LoginController]) module.controller("GoalController", ["$scope","$rootScope","$location", "$routeParams", "$model", "$modal", "resource", GoalController]) module.controller("GoalListController", ["$scope","$rootScope", "$location", "$model", "resource", GoalListController]) module.controller("WinListController", ["$scope","$rootScope", "$location", "$model", "resource", WinListController]) module.controller("PublicRegisterController", ["$scope", "$rootScope", "$location", "resource", "$gmAuth", PublicRegisterController])
[ { "context": "eathermap.org/data/2.5/weather'\n# key = '317b5b5a2c782dd1b7aab1c82867e90c'\n lat = position.coords.latitude\n ", "end": 2764, "score": 0.9997537732124329, "start": 2732, "tag": "KEY", "value": "317b5b5a2c782dd1b7aab1c82867e90c" } ]
api/app/assets/javascripts/diaries.coffee
kyokoshima/word_diary
0
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ ready = -> Barba.Pjax.start() Barba.Pjax.init() Barba.Prefetch.init() Barba.Dispatcher.on 'linkClicked', (el) -> console.log el Barba.Dispatcher.on 'transitionCompleted', (st) -> pageInit() Materialize.updateTextFields() if Materialize.updateTextFields getNewPageFile = -> return Barba.HistoryManager.currentStatus().url.split('/').pop(); pageInit = -> $('.button-collapse').sideNav({ menuWidth: 100, edge: 'right', draggable: true }) $('#diary_word').on 'keyup', -> $('#preview-word').text $(this).val() readURL = (input) -> if input.files && input.files[0] reader = new FileReader() reader.onload = (e) -> $('#preview').attr 'src', e.target.result # readColor $('#preview')[0] reader.readAsDataURL input.files[0] readColor = (img) -> RGBaster.colors(img, { success: (payload) -> console.log payload textColor = complementColor payload.palette[9] console.log textColor $('.preview-container').css('color', textColor) } ) $('#diary_image').change -> readURL(@) $('#diary_show_temp').change -> container = $('.temp-container') if $(@).prop('checked') then container.show() else container.hide() $('#diary_show_weather').change -> container = $('.weather-container') if $(@).prop('checked') then container.show() else container.hide() $('#diary_show_date').change -> container = $('.date-container') if $(@).prop('checked') then container.show() else container.hide() $('#diary_show_location').change -> container = $('.place-container') if $(@).prop('checked') then container.show() else container.hide() if getNewPageFile() == 'new' #d = new $.Deferred [lastLat, lastLon, lastTemp, lastIcon] = '' if navigator.geolocation and $('.preview-container') Materialize.toast 'Getting your location...', 2000 d = new $.Deferred watchId = navigator.geolocation.watchPosition (position) -> d.resolve(position) , (error) -> d.reject(error) console.log error Materialize.toast "Couldn't get your location", 3000 d.promise() .then (position) -> inner = '<div class="circle"></div>' Materialize.toast "Getting weather of your place...", 2000 # url = 'http://api.openweathermap.org/data/2.5/weather' # key = '317b5b5a2c782dd1b7aab1c82867e90c' lat = position.coords.latitude lon = position.coords.longitude [lastLat ,lastLon] = [lat, lon] # $.ajax url, # type: 'get', # data: { # appid: key, # lat: lat, # lon: lon, # units: 'metric' # } $.ajax 'weather', data: {lat: lat, lon: lon}, dataType: 'json' .then( (response, status, xhr) -> d = new $.Deferred place = response.place $('#preview-place').text place $('#diary_place').val place temp = response.temp $('#preview-temp').text temp $('#diary_temperature').val temp $('#diary_weather').val response.weather $('#diary_weather_icon').val response.icon $('#preview-weather i').addClass(response.icon_class) d.resolve().promise() , (xhr, status, error) -> console.log error new $.Deferred().reject().promise() ) post_date = moment().format("ddd, MMM D, YYYY") $('#preview-date').text(post_date) $('#diary_post_date').val(post_date) pageInit() MovePage = Barba.BaseTransition.extend start: -> Promise .all([@newContainerLoading, @scrollTop()]) .then(@movePages.bind(@)); , scrollTop: -> deferred = Barba.Utils.deferred(); obj = { y: window.pageYOffset }; TweenLite.to obj, 0.4, { y: 0, onUpdate: -> if obj.y == 0 deferred.resolve(); window.scroll(0, obj.y); , onComplete: -> deferred.resolve(); } return deferred.promise; , movePages: -> _this = @; goingForward = true; if getNewPageFile() == 'diaries' goingForward = false $('.side-nav, .fixed-action-btn').hide(); TweenLite.set(@newContainer, { visibility: 'visible', xPercent: if goingForward then 100 else -100, position: 'fixed', left: 0, top: 0, right: 0 }); TweenLite.to @oldContainer, 0.3, { xPercent: if goingForward then -100 else 100 } TweenLite.to @newContainer, 0.3, { xPercent: 0, onComplete: -> TweenLite.set _this.newContainer, { clearProps: 'all' } $('.side-nav, .fixed-action-btn').show() _this.done() } , Barba.Pjax.getTransition = -> return MovePage; complementColor = (color) -> [r, g, b] = color.match(/rgb\((.*)\)/)[1].split(',') [max, min] = [Math.max(r, Math.max(g, b)), Math.min(r, Math.min(g, b))] sum = max + min [newR, newG, newB] = [sum - r, sum-g, sum-b] "rgb(#{newR},#{newG},#{newB})" $(document).on 'turbolinks:load', ready Materialize.toast $('#notice').text(), 3000 if $('#notice').text() Materialize.toast $('#error').text(), 3000 if $('#error').text()
147115
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ ready = -> Barba.Pjax.start() Barba.Pjax.init() Barba.Prefetch.init() Barba.Dispatcher.on 'linkClicked', (el) -> console.log el Barba.Dispatcher.on 'transitionCompleted', (st) -> pageInit() Materialize.updateTextFields() if Materialize.updateTextFields getNewPageFile = -> return Barba.HistoryManager.currentStatus().url.split('/').pop(); pageInit = -> $('.button-collapse').sideNav({ menuWidth: 100, edge: 'right', draggable: true }) $('#diary_word').on 'keyup', -> $('#preview-word').text $(this).val() readURL = (input) -> if input.files && input.files[0] reader = new FileReader() reader.onload = (e) -> $('#preview').attr 'src', e.target.result # readColor $('#preview')[0] reader.readAsDataURL input.files[0] readColor = (img) -> RGBaster.colors(img, { success: (payload) -> console.log payload textColor = complementColor payload.palette[9] console.log textColor $('.preview-container').css('color', textColor) } ) $('#diary_image').change -> readURL(@) $('#diary_show_temp').change -> container = $('.temp-container') if $(@).prop('checked') then container.show() else container.hide() $('#diary_show_weather').change -> container = $('.weather-container') if $(@).prop('checked') then container.show() else container.hide() $('#diary_show_date').change -> container = $('.date-container') if $(@).prop('checked') then container.show() else container.hide() $('#diary_show_location').change -> container = $('.place-container') if $(@).prop('checked') then container.show() else container.hide() if getNewPageFile() == 'new' #d = new $.Deferred [lastLat, lastLon, lastTemp, lastIcon] = '' if navigator.geolocation and $('.preview-container') Materialize.toast 'Getting your location...', 2000 d = new $.Deferred watchId = navigator.geolocation.watchPosition (position) -> d.resolve(position) , (error) -> d.reject(error) console.log error Materialize.toast "Couldn't get your location", 3000 d.promise() .then (position) -> inner = '<div class="circle"></div>' Materialize.toast "Getting weather of your place...", 2000 # url = 'http://api.openweathermap.org/data/2.5/weather' # key = '<KEY>' lat = position.coords.latitude lon = position.coords.longitude [lastLat ,lastLon] = [lat, lon] # $.ajax url, # type: 'get', # data: { # appid: key, # lat: lat, # lon: lon, # units: 'metric' # } $.ajax 'weather', data: {lat: lat, lon: lon}, dataType: 'json' .then( (response, status, xhr) -> d = new $.Deferred place = response.place $('#preview-place').text place $('#diary_place').val place temp = response.temp $('#preview-temp').text temp $('#diary_temperature').val temp $('#diary_weather').val response.weather $('#diary_weather_icon').val response.icon $('#preview-weather i').addClass(response.icon_class) d.resolve().promise() , (xhr, status, error) -> console.log error new $.Deferred().reject().promise() ) post_date = moment().format("ddd, MMM D, YYYY") $('#preview-date').text(post_date) $('#diary_post_date').val(post_date) pageInit() MovePage = Barba.BaseTransition.extend start: -> Promise .all([@newContainerLoading, @scrollTop()]) .then(@movePages.bind(@)); , scrollTop: -> deferred = Barba.Utils.deferred(); obj = { y: window.pageYOffset }; TweenLite.to obj, 0.4, { y: 0, onUpdate: -> if obj.y == 0 deferred.resolve(); window.scroll(0, obj.y); , onComplete: -> deferred.resolve(); } return deferred.promise; , movePages: -> _this = @; goingForward = true; if getNewPageFile() == 'diaries' goingForward = false $('.side-nav, .fixed-action-btn').hide(); TweenLite.set(@newContainer, { visibility: 'visible', xPercent: if goingForward then 100 else -100, position: 'fixed', left: 0, top: 0, right: 0 }); TweenLite.to @oldContainer, 0.3, { xPercent: if goingForward then -100 else 100 } TweenLite.to @newContainer, 0.3, { xPercent: 0, onComplete: -> TweenLite.set _this.newContainer, { clearProps: 'all' } $('.side-nav, .fixed-action-btn').show() _this.done() } , Barba.Pjax.getTransition = -> return MovePage; complementColor = (color) -> [r, g, b] = color.match(/rgb\((.*)\)/)[1].split(',') [max, min] = [Math.max(r, Math.max(g, b)), Math.min(r, Math.min(g, b))] sum = max + min [newR, newG, newB] = [sum - r, sum-g, sum-b] "rgb(#{newR},#{newG},#{newB})" $(document).on 'turbolinks:load', ready Materialize.toast $('#notice').text(), 3000 if $('#notice').text() Materialize.toast $('#error').text(), 3000 if $('#error').text()
true
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ ready = -> Barba.Pjax.start() Barba.Pjax.init() Barba.Prefetch.init() Barba.Dispatcher.on 'linkClicked', (el) -> console.log el Barba.Dispatcher.on 'transitionCompleted', (st) -> pageInit() Materialize.updateTextFields() if Materialize.updateTextFields getNewPageFile = -> return Barba.HistoryManager.currentStatus().url.split('/').pop(); pageInit = -> $('.button-collapse').sideNav({ menuWidth: 100, edge: 'right', draggable: true }) $('#diary_word').on 'keyup', -> $('#preview-word').text $(this).val() readURL = (input) -> if input.files && input.files[0] reader = new FileReader() reader.onload = (e) -> $('#preview').attr 'src', e.target.result # readColor $('#preview')[0] reader.readAsDataURL input.files[0] readColor = (img) -> RGBaster.colors(img, { success: (payload) -> console.log payload textColor = complementColor payload.palette[9] console.log textColor $('.preview-container').css('color', textColor) } ) $('#diary_image').change -> readURL(@) $('#diary_show_temp').change -> container = $('.temp-container') if $(@).prop('checked') then container.show() else container.hide() $('#diary_show_weather').change -> container = $('.weather-container') if $(@).prop('checked') then container.show() else container.hide() $('#diary_show_date').change -> container = $('.date-container') if $(@).prop('checked') then container.show() else container.hide() $('#diary_show_location').change -> container = $('.place-container') if $(@).prop('checked') then container.show() else container.hide() if getNewPageFile() == 'new' #d = new $.Deferred [lastLat, lastLon, lastTemp, lastIcon] = '' if navigator.geolocation and $('.preview-container') Materialize.toast 'Getting your location...', 2000 d = new $.Deferred watchId = navigator.geolocation.watchPosition (position) -> d.resolve(position) , (error) -> d.reject(error) console.log error Materialize.toast "Couldn't get your location", 3000 d.promise() .then (position) -> inner = '<div class="circle"></div>' Materialize.toast "Getting weather of your place...", 2000 # url = 'http://api.openweathermap.org/data/2.5/weather' # key = 'PI:KEY:<KEY>END_PI' lat = position.coords.latitude lon = position.coords.longitude [lastLat ,lastLon] = [lat, lon] # $.ajax url, # type: 'get', # data: { # appid: key, # lat: lat, # lon: lon, # units: 'metric' # } $.ajax 'weather', data: {lat: lat, lon: lon}, dataType: 'json' .then( (response, status, xhr) -> d = new $.Deferred place = response.place $('#preview-place').text place $('#diary_place').val place temp = response.temp $('#preview-temp').text temp $('#diary_temperature').val temp $('#diary_weather').val response.weather $('#diary_weather_icon').val response.icon $('#preview-weather i').addClass(response.icon_class) d.resolve().promise() , (xhr, status, error) -> console.log error new $.Deferred().reject().promise() ) post_date = moment().format("ddd, MMM D, YYYY") $('#preview-date').text(post_date) $('#diary_post_date').val(post_date) pageInit() MovePage = Barba.BaseTransition.extend start: -> Promise .all([@newContainerLoading, @scrollTop()]) .then(@movePages.bind(@)); , scrollTop: -> deferred = Barba.Utils.deferred(); obj = { y: window.pageYOffset }; TweenLite.to obj, 0.4, { y: 0, onUpdate: -> if obj.y == 0 deferred.resolve(); window.scroll(0, obj.y); , onComplete: -> deferred.resolve(); } return deferred.promise; , movePages: -> _this = @; goingForward = true; if getNewPageFile() == 'diaries' goingForward = false $('.side-nav, .fixed-action-btn').hide(); TweenLite.set(@newContainer, { visibility: 'visible', xPercent: if goingForward then 100 else -100, position: 'fixed', left: 0, top: 0, right: 0 }); TweenLite.to @oldContainer, 0.3, { xPercent: if goingForward then -100 else 100 } TweenLite.to @newContainer, 0.3, { xPercent: 0, onComplete: -> TweenLite.set _this.newContainer, { clearProps: 'all' } $('.side-nav, .fixed-action-btn').show() _this.done() } , Barba.Pjax.getTransition = -> return MovePage; complementColor = (color) -> [r, g, b] = color.match(/rgb\((.*)\)/)[1].split(',') [max, min] = [Math.max(r, Math.max(g, b)), Math.min(r, Math.min(g, b))] sum = max + min [newR, newG, newB] = [sum - r, sum-g, sum-b] "rgb(#{newR},#{newG},#{newB})" $(document).on 'turbolinks:load', ready Materialize.toast $('#notice').text(), 3000 if $('#notice').text() Materialize.toast $('#error').text(), 3000 if $('#error').text()
[ { "context": "###\n * tablodbò\n * https://github.com/leny/tablodbo\n *\n * JS/COFFEE Document - /cli.js - cli", "end": 42, "score": 0.9995286464691162, "start": 38, "tag": "USERNAME", "value": "leny" }, { "context": "ommander setup and runner\n *\n * Copyright (c) 2014 Leny\n * Lice...
src/cli.coffee
leny/tablodbo
0
### * tablodbò * https://github.com/leny/tablodbo * * JS/COFFEE Document - /cli.js - cli entry point, commander setup and runner * * Copyright (c) 2014 Leny * Licensed under the MIT license. ### "use strict" pkg = require "../package.json" tablodbo = require "./tablodbo.js" exec = require( "child_process" ).exec Table = require "cli-table" chalk = require "chalk" error = ( oError ) -> console.log chalk.bold.red "✘ #{ oError }." process.exit 1 ( spinner = require "simple-spinner" ) .change_sequence [ "◓" "◑" "◒" "◐" ] ( program = require "commander" ) .version pkg.version .usage "[options] <npm-user>" .description "A CLI-dashboard for your npm packages" .parse process.argv fColorizeText = ( sText ) -> switch sText when "passing", "up to date" then chalk.green sText when "failing", "out of date" then chalk.red sText when "pending" then chalk.blue sText when "unknown" then chalk.gray sText else sText fProcess = ( sUser ) -> spinner.start 50 tablodbo sUser, ( oError, aInfos ) -> spinner.stop() error oError if oError error "User #{ sUser } has no packages on npm!" unless aInfos.length oTable = new Table head: [ chalk.cyan( "name" ) chalk.cyan( "version" ) chalk.cyan( "build status" ) chalk.cyan( "dependencies" ) chalk.cyan( "dev dependencies" ) chalk.cyan( "downloads" ) + "\n" + chalk.cyan( "(last month)" ) chalk.cyan( "stars" ) chalk.cyan( "dependents" ) ] for oPackage in aInfos oTable.push [ oPackage.name oPackage.version fColorizeText oPackage.build fColorizeText oPackage.dependencies fColorizeText oPackage.devDependencies fColorizeText oPackage.downloads fColorizeText oPackage.stars fColorizeText oPackage.dependents ] console.log "\n" console.log oTable.toString() process.exit 0 unless sNPMUser = program.args[ 0 ] exec "npm whoami", ( oError, sSTDOut ) -> error oError if oError sNPMUser = sSTDOut.trim() fProcess sNPMUser else fProcess sNPMUser
50352
### * tablodbò * https://github.com/leny/tablodbo * * JS/COFFEE Document - /cli.js - cli entry point, commander setup and runner * * Copyright (c) 2014 <NAME> * Licensed under the MIT license. ### "use strict" pkg = require "../package.json" tablodbo = require "./tablodbo.js" exec = require( "child_process" ).exec Table = require "cli-table" chalk = require "chalk" error = ( oError ) -> console.log chalk.bold.red "✘ #{ oError }." process.exit 1 ( spinner = require "simple-spinner" ) .change_sequence [ "◓" "◑" "◒" "◐" ] ( program = require "commander" ) .version pkg.version .usage "[options] <npm-user>" .description "A CLI-dashboard for your npm packages" .parse process.argv fColorizeText = ( sText ) -> switch sText when "passing", "up to date" then chalk.green sText when "failing", "out of date" then chalk.red sText when "pending" then chalk.blue sText when "unknown" then chalk.gray sText else sText fProcess = ( sUser ) -> spinner.start 50 tablodbo sUser, ( oError, aInfos ) -> spinner.stop() error oError if oError error "User #{ sUser } has no packages on npm!" unless aInfos.length oTable = new Table head: [ chalk.cyan( "name" ) chalk.cyan( "version" ) chalk.cyan( "build status" ) chalk.cyan( "dependencies" ) chalk.cyan( "dev dependencies" ) chalk.cyan( "downloads" ) + "\n" + chalk.cyan( "(last month)" ) chalk.cyan( "stars" ) chalk.cyan( "dependents" ) ] for oPackage in aInfos oTable.push [ oPackage.name oPackage.version fColorizeText oPackage.build fColorizeText oPackage.dependencies fColorizeText oPackage.devDependencies fColorizeText oPackage.downloads fColorizeText oPackage.stars fColorizeText oPackage.dependents ] console.log "\n" console.log oTable.toString() process.exit 0 unless sNPMUser = program.args[ 0 ] exec "npm whoami", ( oError, sSTDOut ) -> error oError if oError sNPMUser = sSTDOut.trim() fProcess sNPMUser else fProcess sNPMUser
true
### * tablodbò * https://github.com/leny/tablodbo * * JS/COFFEE Document - /cli.js - cli entry point, commander setup and runner * * Copyright (c) 2014 PI:NAME:<NAME>END_PI * Licensed under the MIT license. ### "use strict" pkg = require "../package.json" tablodbo = require "./tablodbo.js" exec = require( "child_process" ).exec Table = require "cli-table" chalk = require "chalk" error = ( oError ) -> console.log chalk.bold.red "✘ #{ oError }." process.exit 1 ( spinner = require "simple-spinner" ) .change_sequence [ "◓" "◑" "◒" "◐" ] ( program = require "commander" ) .version pkg.version .usage "[options] <npm-user>" .description "A CLI-dashboard for your npm packages" .parse process.argv fColorizeText = ( sText ) -> switch sText when "passing", "up to date" then chalk.green sText when "failing", "out of date" then chalk.red sText when "pending" then chalk.blue sText when "unknown" then chalk.gray sText else sText fProcess = ( sUser ) -> spinner.start 50 tablodbo sUser, ( oError, aInfos ) -> spinner.stop() error oError if oError error "User #{ sUser } has no packages on npm!" unless aInfos.length oTable = new Table head: [ chalk.cyan( "name" ) chalk.cyan( "version" ) chalk.cyan( "build status" ) chalk.cyan( "dependencies" ) chalk.cyan( "dev dependencies" ) chalk.cyan( "downloads" ) + "\n" + chalk.cyan( "(last month)" ) chalk.cyan( "stars" ) chalk.cyan( "dependents" ) ] for oPackage in aInfos oTable.push [ oPackage.name oPackage.version fColorizeText oPackage.build fColorizeText oPackage.dependencies fColorizeText oPackage.devDependencies fColorizeText oPackage.downloads fColorizeText oPackage.stars fColorizeText oPackage.dependents ] console.log "\n" console.log oTable.toString() process.exit 0 unless sNPMUser = program.args[ 0 ] exec "npm whoami", ( oError, sSTDOut ) -> error oError if oError sNPMUser = sSTDOut.trim() fProcess sNPMUser else fProcess sNPMUser
[ { "context": "GS IN THE SOFTWARE.\n\n# Taken from hubot at commit 71d1c686d9ffdfad54751080c699979fa17190a1 and modified to fit current use.\n\nclass ChatUser\n", "end": 1166, "score": 0.975783109664917, "start": 1126, "tag": "PASSWORD", "value": "71d1c686d9ffdfad54751080c699979fa17190a1" }...
src/user.coffee
kumpelblase2/modlab-chat
0
# Copyright (c) 2013 GitHub Inc. # # 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. # Taken from hubot at commit 71d1c686d9ffdfad54751080c699979fa17190a1 and modified to fit current use. class ChatUser # Represents a participating user in the chat. # # id - A unique ID for the user. # options - An optional Hash of key, value pairs for this user. constructor: (@id, options = {}) -> for k of (options or {}) @[k] = options[k] @['name'] ||= @id.toString() module.exports = ChatUser
206072
# Copyright (c) 2013 GitHub Inc. # # 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. # Taken from hubot at commit <PASSWORD> and modified to fit current use. class ChatUser # Represents a participating user in the chat. # # id - A unique ID for the user. # options - An optional Hash of key, value pairs for this user. constructor: (@id, options = {}) -> for k of (options or {}) @[k] = options[k] @['name'] ||= @id.toString() module.exports = ChatUser
true
# Copyright (c) 2013 GitHub Inc. # # 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. # Taken from hubot at commit PI:PASSWORD:<PASSWORD>END_PI and modified to fit current use. class ChatUser # Represents a participating user in the chat. # # id - A unique ID for the user. # options - An optional Hash of key, value pairs for this user. constructor: (@id, options = {}) -> for k of (options or {}) @[k] = options[k] @['name'] ||= @id.toString() module.exports = ChatUser
[ { "context": "ipt utilities which you may never use.\n @author Draucpid\n @date Dec. 11st, 2014\n###\n((root, fact", "end": 69, "score": 0.5066878795623779, "start": 68, "tag": "USERNAME", "value": "D" }, { "context": "t utilities which you may never use.\n @author Draucpid\...
lessjs.coffee
dracupid/lessjs
0
### A javascript utilities which you may never use. @author Draucpid @date Dec. 11st, 2014 ### ((root, factory)-> if typeof module is "object" && typeof module.exports is "object" module.exports = factory root else if typeof define is 'function' and define.amd define 'lessjs', [], -> factory root else root.L = factory root ) this, (root)-> # If a value is exactly `NaN` # Param: {Any} # Return: {Boolean} isNaN = (val)-> val isnt val # easist and fastest floor function floor = (num)-> ~~num # convert a rgb color to hex rgb2Hex = (r, g, b)-> '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).substr(1) typeOf = (val)-> typeStr = Object::toString.call val typeStr.match(/\[object (.*?)\]/)[1] ### UTF-16 has two kinds of lengths 1. U+0000 ~ U+FFFF: length is 16 bits (2 bytes) 2. U+10000 ~ U+10FFFF: length is 32 bits (4 bytes), of which the first two bytes are 0xD800 ~ 0xDBFF, the last two are 0xDC00 ~ 0xDFFF When it comes to the second situation, the browser will recognize the four bytes as a character and display correctly, but its length will be regarded as 2 units. ### strToArray = (str, utf8Only = true)-> if utf8Only then return str.split('') length = str.length index = -1 array = [] while(++index < length) char = str.charAt index charCode = char.charCodeAt 0 if 0xD800 <= charCode <= 0xDBFF array.push char + str.charAt ++index else array.push char array splitChar = (str, spliter = ' ')-> Array.prototype.join.call(str, spliter) # Native btoa and atob cannot deal with unicode characters btoaUnicode = (str)-> btoa unescape encodeURIComponent str atobUnicode = (str)-> decodeURIComponent escape atob str max = (arr)-> arr.reduce (max, item)-> if item > max then item else max inArray = (arr, item)-> arr.indexOf(item) >= 0 isLittleEndian = do -> buffer = new ArrayBuffer 2 new DataView(buffer).setInt16 0, 256, true new Int16Array(buffer)[0] is 256; # repeat a string n times String::repeat = (times)-> Array(times).join @ # title string String::title = ()-> @.trim().split(/\s+/).map (word)-> word[0].toUpperCase() + word[1..] .join ' ' # remove duplicate items Array::unique = -> obj = {} obj[@[key]] = @[key] for key in [0..@length] value for key, value of obj # revert a obj array to dict can be searched by some property Array::toDict = (keyProperty) -> @reduce (dict, obj)-> dict[obj[keyProperty]] = obj if obj[key]? dict , {} Array::shuffle = -> @sort -> 0.5 - Math.random() # Array-Like objects, such as arguments Object, HTMLCollection class ArrayLike constructor: (@length = 0)-> for i in [0...length] @[i] = null toArray: (self = @)-> Array.prototype.slice.call self forEach: (self, func)-> if arguments.length is 1 then Array.prototype.forEach.call @, self else Array.prototype.forEach.call self, func ArrayLike.toArray = Array::toArray ArrayLike.forEach = Array::forEacgh # Convert many paramters or one array paramter to an array. argsToArray = -> Array::concat.apply [], arguments.callee.caller.arguments # Bit flag class Flag constructor: ()-> @flagNum = 0 @flagState = 0 add: (flagArr)-> flagArr.forEach (flag)-> @flagMap[flag] = 1 << @flagNum++ mask: (flagArr)-> flagArr.map (flagName)-> @flagMap[flagName] .reduce (total, cur)-> total | cur turnOnAll: ()-> @flagState = if @flagNum then -1 >>> (32 - @flagNum) else 0 turnOn: (flagArr)-> @flagState |= @mask flagArr turnOffAll: ()-> @flagState = 0 turnOff: (flagArr)-> @flagState &= ~(@mask flagArr) setAs: (flagArr)-> @flagState &= @mask flagArr toggleAll: ()-> @flagState = ~flags toggle: (flagArr)-> @flagState ^= @mask flagArr checkOn: (curState, flag)-> curState & @flagMap[flag] checkOff: (curState, flag)-> not @checkOn curState, flag class Model constructor: (@_attr)-> get: (key)-> @_attr[key] set: (key, value)-> @_attr[key] = value @ on: (e, handler)->
182421
### A javascript utilities which you may never use. @author D<NAME> @date Dec. 11st, 2014 ### ((root, factory)-> if typeof module is "object" && typeof module.exports is "object" module.exports = factory root else if typeof define is 'function' and define.amd define 'lessjs', [], -> factory root else root.L = factory root ) this, (root)-> # If a value is exactly `NaN` # Param: {Any} # Return: {Boolean} isNaN = (val)-> val isnt val # easist and fastest floor function floor = (num)-> ~~num # convert a rgb color to hex rgb2Hex = (r, g, b)-> '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).substr(1) typeOf = (val)-> typeStr = Object::toString.call val typeStr.match(/\[object (.*?)\]/)[1] ### UTF-16 has two kinds of lengths 1. U+0000 ~ U+FFFF: length is 16 bits (2 bytes) 2. U+10000 ~ U+10FFFF: length is 32 bits (4 bytes), of which the first two bytes are 0xD800 ~ 0xDBFF, the last two are 0xDC00 ~ 0xDFFF When it comes to the second situation, the browser will recognize the four bytes as a character and display correctly, but its length will be regarded as 2 units. ### strToArray = (str, utf8Only = true)-> if utf8Only then return str.split('') length = str.length index = -1 array = [] while(++index < length) char = str.charAt index charCode = char.charCodeAt 0 if 0xD800 <= charCode <= 0xDBFF array.push char + str.charAt ++index else array.push char array splitChar = (str, spliter = ' ')-> Array.prototype.join.call(str, spliter) # Native btoa and atob cannot deal with unicode characters btoaUnicode = (str)-> btoa unescape encodeURIComponent str atobUnicode = (str)-> decodeURIComponent escape atob str max = (arr)-> arr.reduce (max, item)-> if item > max then item else max inArray = (arr, item)-> arr.indexOf(item) >= 0 isLittleEndian = do -> buffer = new ArrayBuffer 2 new DataView(buffer).setInt16 0, 256, true new Int16Array(buffer)[0] is 256; # repeat a string n times String::repeat = (times)-> Array(times).join @ # title string String::title = ()-> @.trim().split(/\s+/).map (word)-> word[0].toUpperCase() + word[1..] .join ' ' # remove duplicate items Array::unique = -> obj = {} obj[@[key]] = @[key] for key in [0..@length] value for key, value of obj # revert a obj array to dict can be searched by some property Array::toDict = (keyProperty) -> @reduce (dict, obj)-> dict[obj[keyProperty]] = obj if obj[key]? dict , {} Array::shuffle = -> @sort -> 0.5 - Math.random() # Array-Like objects, such as arguments Object, HTMLCollection class ArrayLike constructor: (@length = 0)-> for i in [0...length] @[i] = null toArray: (self = @)-> Array.prototype.slice.call self forEach: (self, func)-> if arguments.length is 1 then Array.prototype.forEach.call @, self else Array.prototype.forEach.call self, func ArrayLike.toArray = Array::toArray ArrayLike.forEach = Array::forEacgh # Convert many paramters or one array paramter to an array. argsToArray = -> Array::concat.apply [], arguments.callee.caller.arguments # Bit flag class Flag constructor: ()-> @flagNum = 0 @flagState = 0 add: (flagArr)-> flagArr.forEach (flag)-> @flagMap[flag] = 1 << @flagNum++ mask: (flagArr)-> flagArr.map (flagName)-> @flagMap[flagName] .reduce (total, cur)-> total | cur turnOnAll: ()-> @flagState = if @flagNum then -1 >>> (32 - @flagNum) else 0 turnOn: (flagArr)-> @flagState |= @mask flagArr turnOffAll: ()-> @flagState = 0 turnOff: (flagArr)-> @flagState &= ~(@mask flagArr) setAs: (flagArr)-> @flagState &= @mask flagArr toggleAll: ()-> @flagState = ~flags toggle: (flagArr)-> @flagState ^= @mask flagArr checkOn: (curState, flag)-> curState & @flagMap[flag] checkOff: (curState, flag)-> not @checkOn curState, flag class Model constructor: (@_attr)-> get: (key)-> @_attr[key] set: (key, value)-> @_attr[key] = value @ on: (e, handler)->
true
### A javascript utilities which you may never use. @author DPI:NAME:<NAME>END_PI @date Dec. 11st, 2014 ### ((root, factory)-> if typeof module is "object" && typeof module.exports is "object" module.exports = factory root else if typeof define is 'function' and define.amd define 'lessjs', [], -> factory root else root.L = factory root ) this, (root)-> # If a value is exactly `NaN` # Param: {Any} # Return: {Boolean} isNaN = (val)-> val isnt val # easist and fastest floor function floor = (num)-> ~~num # convert a rgb color to hex rgb2Hex = (r, g, b)-> '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).substr(1) typeOf = (val)-> typeStr = Object::toString.call val typeStr.match(/\[object (.*?)\]/)[1] ### UTF-16 has two kinds of lengths 1. U+0000 ~ U+FFFF: length is 16 bits (2 bytes) 2. U+10000 ~ U+10FFFF: length is 32 bits (4 bytes), of which the first two bytes are 0xD800 ~ 0xDBFF, the last two are 0xDC00 ~ 0xDFFF When it comes to the second situation, the browser will recognize the four bytes as a character and display correctly, but its length will be regarded as 2 units. ### strToArray = (str, utf8Only = true)-> if utf8Only then return str.split('') length = str.length index = -1 array = [] while(++index < length) char = str.charAt index charCode = char.charCodeAt 0 if 0xD800 <= charCode <= 0xDBFF array.push char + str.charAt ++index else array.push char array splitChar = (str, spliter = ' ')-> Array.prototype.join.call(str, spliter) # Native btoa and atob cannot deal with unicode characters btoaUnicode = (str)-> btoa unescape encodeURIComponent str atobUnicode = (str)-> decodeURIComponent escape atob str max = (arr)-> arr.reduce (max, item)-> if item > max then item else max inArray = (arr, item)-> arr.indexOf(item) >= 0 isLittleEndian = do -> buffer = new ArrayBuffer 2 new DataView(buffer).setInt16 0, 256, true new Int16Array(buffer)[0] is 256; # repeat a string n times String::repeat = (times)-> Array(times).join @ # title string String::title = ()-> @.trim().split(/\s+/).map (word)-> word[0].toUpperCase() + word[1..] .join ' ' # remove duplicate items Array::unique = -> obj = {} obj[@[key]] = @[key] for key in [0..@length] value for key, value of obj # revert a obj array to dict can be searched by some property Array::toDict = (keyProperty) -> @reduce (dict, obj)-> dict[obj[keyProperty]] = obj if obj[key]? dict , {} Array::shuffle = -> @sort -> 0.5 - Math.random() # Array-Like objects, such as arguments Object, HTMLCollection class ArrayLike constructor: (@length = 0)-> for i in [0...length] @[i] = null toArray: (self = @)-> Array.prototype.slice.call self forEach: (self, func)-> if arguments.length is 1 then Array.prototype.forEach.call @, self else Array.prototype.forEach.call self, func ArrayLike.toArray = Array::toArray ArrayLike.forEach = Array::forEacgh # Convert many paramters or one array paramter to an array. argsToArray = -> Array::concat.apply [], arguments.callee.caller.arguments # Bit flag class Flag constructor: ()-> @flagNum = 0 @flagState = 0 add: (flagArr)-> flagArr.forEach (flag)-> @flagMap[flag] = 1 << @flagNum++ mask: (flagArr)-> flagArr.map (flagName)-> @flagMap[flagName] .reduce (total, cur)-> total | cur turnOnAll: ()-> @flagState = if @flagNum then -1 >>> (32 - @flagNum) else 0 turnOn: (flagArr)-> @flagState |= @mask flagArr turnOffAll: ()-> @flagState = 0 turnOff: (flagArr)-> @flagState &= ~(@mask flagArr) setAs: (flagArr)-> @flagState &= @mask flagArr toggleAll: ()-> @flagState = ~flags toggle: (flagArr)-> @flagState ^= @mask flagArr checkOn: (curState, flag)-> curState & @flagMap[flag] checkOff: (curState, flag)-> not @checkOn curState, flag class Model constructor: (@_attr)-> get: (key)-> @_attr[key] set: (key, value)-> @_attr[key] = value @ on: (e, handler)->
[ { "context": "=======================================\n # 1 | [Alice 1, Bob 0] | Alice | index 0, [a, b, c]\n # 2 | [", "end": 2091, "score": 0.9904425740242004, "start": 2086, "tag": "NAME", "value": "Alice" }, { "context": "===============================\n # 1 | [Alice 1, Bo...
crdt.coffee
jerico-dev/meteor-versioning
7
# A commutative replicative data type. class Meteor._CrdtDocument constructor: (@collProps = null, serializedCrdt = null) -> if serializedCrdt? { _id: @id _crdtId: @crdtId _clock: @clock _deleted: @deleted } = serializedCrdt @properties = _.omit serializedCrdt, '_id', '_crdtId', '_clock', '_deleted' else @id = undefined @crdtId = undefined @clock = {} @properties = {} @deleted = false getNextIndex: (key) -> if @properties[key]? then @properties[key].length else 0 getOrderedVisiblePayloads: (key) -> return [] unless @properties[key] payloads = [] for sites, index in @properties[key] for site, changes of sites for payload, change in changes _.extend payload, index: index site: site change: change sortedSites = _.sortBy sites, (payload) -> payload.site for changes in sortedSites for payload in changes payloads.push payload unless payload.deleted payloads # Inserts the payload into the property list. # # Order: # - for causally related operations: The ordering is # automatically causal as transactions preserve causality. # Causal order is represented by the index value. # - for concurrent transactions: We order lexicographically # by originating site to ensure a globally unique order. # - for changes within a transaction: Order is the same # as the order of operations in the transaction. # # This ordering has the following properties: # - Causality is preserved (index). # - We get a unique order for concurrent transactions, # independently of the order in which they arrive (site). # - Effects caused by the same transaction will be # kept in a single run so that effects from several # concurrent transactions do not interleave (change). # # Assume we have the following events: # tx | clock vector | site | appended values # ================================================== # 1 | [Alice 1, Bob 0] | Alice | index 0, [a, b, c] # 2 | [Alice 2, Bob 0] | Alice | index 1, [f, g] # 3 | [Alice 0, Bob 1] | Bob | index 0, [d, e] # # This establishes the following causality: # - Transaction 2 happend-after transaction 1. # - Transaction 3 happened concurrently with transactions 1 and 2 # # Now assume that the transactions arrive in the order 3, 2, 1: # When tx 3 arrives, the local clock is [Alice 0, Bob 0]. This # means that tx 3 will be executed immediately: # # properties: # 0: -- index # Bob: -- site # d, e -- changes # # When tx 2 arrives, the local clock is [Alice 0, Bob 1]. This # means that the transaction will be recognized as out-of-order # and staged as a pending transaction. # # When tx 1 arrives, the local clock still is [Alice 0, Bob 1]. # Tx 1 is recognized as concurrent transaction and will be # executed: # # properties: # 0: -- index # Alice: -- site (ordered lexicographically) # a, b, c -- changes # Bob: # d, e # # The clock advanced to [Alice 1, Bob 1]. Now the previously # arrived tx 3 is no longer pending and can be executed: # # properties: # 0: # Alice: # a, b, c # Bob: # d, e # 1: # Alice: # f, g # # So the final order of all operations will be: # a, b, c, d, e, f, g # All participating sites will converge to this unique # order independently of the order in which transactions # arrive. This preserves causality and intention. # # NB: We currently only allow appending of new values as this # is all we need to resolve conflicts for JS objects. # If we want to insert to the middle of the collection # (e.g. to resolve conflicts for a text document) then # we need a more sophisticated index, see the binary tree # index implementation I had in the early versions of this # class (https://gist.github.com/jerico-dev/4566560). insertAtIndex: (key, value, index, site) -> # Create a new entry. payload = deleted: false value: value # Append the property to the crdt's property list. @properties[key] = [] unless @properties[key]? property = @properties[key] # Check that the index is valid. unless index == 0 or property[index-1]? Meteor.log.throw 'crdt.tryingToInsertIndexOutOfOrder', {key: key, index: index, site: site} property[index] = {} unless property[index]? property[index][site] = [] unless property[index][site]? property[index][site].push payload # Return the index of the new property. [index, site, property[index][site].length - 1] # Mark (entries for) the specified property deleted (invisible). # # locator: # - for Arrays: If an (integer) locator N is given, then # only the N'th currently visible entry will be marked # deleted. # - for Subdocs: If a (string) locator key:value is given, then # all entries where the subkey 'key' equals 'value' of the # object will be marked deleted. # - for Scalars: No locator can be given and all currently # visible entries will be deleted. # In all cases: If no locator was given then all property # entries for that property will be marked deleted. delete: (key, locator = null) -> return [] unless @properties[key]? # Find all visible payloads for this key. payloads = @getOrderedVisiblePayloads(key) # In the case of named subdocuments: filter by locator # if a locator has been given. if locator? and @collProps[key]?.type == '[{}]' # Named subdocuments. payloads = _.filter payloads, (payload) => payload.value[@collProps[key].locator] == locator # Delete the specified entry or entries. if locator? and @collProps[key]?.type == '[*]' # A single array index. unless 0 <= locator < payloads.length Meteor.log.throw 'crdt.tryingToDeleteNonexistentKeyAtPos', {key:key, pos: locator, crdtId: @crdtId} delPl = payloads[locator] delPl.deleted = true # Return the index of the deleted entry as an array. [[delPl.index, delPl.site, delPl.change]] else # Scalar, (full) Array or Subdocuments if payloads.length == 0 # This may happen when we have two concurrent delete operations # on exactly the same key. As this is not probable we log # a warning which may help to identify errors. Meteor.log.warning 'crdt.tryingToDeleteNonexistentKey', {key:key, crdtId: @crdtId} # Return the comprehension with the indices of all deleted entries. for delPl in payloads delPl.deleted = true [delPl.index, delPl.site, delPl.change] _setDeleted: (key, index, site, change, deleted) -> unless @properties[key]?[index]?[site]?[change]? Meteor.log.throw 'crdt.tryingToUnDeleteNonexistentIndex', {key: key, index: index, site: site, change: change} payload = @properties[key][index][site][change] if payload.deleted == deleted # This may happen when two sites delete exactly the # same index concurrently. As this is not probable we # provide a warning as this may point to an error. Meteor.log.warning 'crdt.tryingToUnDeleteIndexInVisibleEntry', {key: key, index: index, site: site, change: change} payload.deleted = deleted [index, site, change] # Mark the property at the given index deleted (invisible). The # second argument is redundant and just for consistency checking. deleteIndex: (key, index, site, change) -> @_setDeleted key, index, site, change, true # Mark the property at the given index not deleted (visible). undeleteIndex: (key, index, site) -> @_setDeleted key, index, site, change, false serialize: -> serializedCrdt = @properties _.extend serializedCrdt, _id: @id _crdtId: @crdtId _clock: @clock _deleted: @deleted serializedCrdt snapshot: -> if @deleted null else # Including the clock in the snapshot is not only # informative but makes sure that we always get # notified over DDP when something changed in the # CRDT and get a chance to publish those changes. snapshot = _id: @crdtId _clock: @clock # Build properties but filter deleted entries. for key of @properties for payload in @getOrderedVisiblePayloads(key) value = payload.value switch @collProps[key]?.type when '[*]' # The value of this property is an array. snapshot[key] = [] unless snapshot[key]? snapshot[key].push value when '[{}]' # The value of this property is a collection of # subdocs with a unique key. This guarantees # that subsequent values with the same subkey # will overwrite each other. snapshot[key] = {} unless snapshot[key]? subkey = value[@collProps[key].locator] snapshot[key][subkey] = value else # The value of this property is a scalar # (cardinality 0-1). We let later values # overwrite earlier ones. snapshot[key] = value # Transform lists of subdocuments to arrays. for collKey, collSpec of @collProps when collSpec.type = '[{}]' snapshot[collKey] = _.values snapshot[collKey] snapshot
223830
# A commutative replicative data type. class Meteor._CrdtDocument constructor: (@collProps = null, serializedCrdt = null) -> if serializedCrdt? { _id: @id _crdtId: @crdtId _clock: @clock _deleted: @deleted } = serializedCrdt @properties = _.omit serializedCrdt, '_id', '_crdtId', '_clock', '_deleted' else @id = undefined @crdtId = undefined @clock = {} @properties = {} @deleted = false getNextIndex: (key) -> if @properties[key]? then @properties[key].length else 0 getOrderedVisiblePayloads: (key) -> return [] unless @properties[key] payloads = [] for sites, index in @properties[key] for site, changes of sites for payload, change in changes _.extend payload, index: index site: site change: change sortedSites = _.sortBy sites, (payload) -> payload.site for changes in sortedSites for payload in changes payloads.push payload unless payload.deleted payloads # Inserts the payload into the property list. # # Order: # - for causally related operations: The ordering is # automatically causal as transactions preserve causality. # Causal order is represented by the index value. # - for concurrent transactions: We order lexicographically # by originating site to ensure a globally unique order. # - for changes within a transaction: Order is the same # as the order of operations in the transaction. # # This ordering has the following properties: # - Causality is preserved (index). # - We get a unique order for concurrent transactions, # independently of the order in which they arrive (site). # - Effects caused by the same transaction will be # kept in a single run so that effects from several # concurrent transactions do not interleave (change). # # Assume we have the following events: # tx | clock vector | site | appended values # ================================================== # 1 | [<NAME> 1, <NAME> 0] | <NAME> | index 0, [a, b, c] # 2 | [<NAME> 2, <NAME> 0] | <NAME> | index 1, [f, g] # 3 | [<NAME> 0, <NAME> 1] | <NAME> | index 0, [d, e] # # This establishes the following causality: # - Transaction 2 happend-after transaction 1. # - Transaction 3 happened concurrently with transactions 1 and 2 # # Now assume that the transactions arrive in the order 3, 2, 1: # When tx 3 arrives, the local clock is [<NAME> 0, <NAME> 0]. This # means that tx 3 will be executed immediately: # # properties: # 0: -- index # <NAME>: -- site # d, e -- changes # # When tx 2 arrives, the local clock is [<NAME> 0, <NAME> 1]. This # means that the transaction will be recognized as out-of-order # and staged as a pending transaction. # # When tx 1 arrives, the local clock still is [<NAME> 0, <NAME> 1]. # Tx 1 is recognized as concurrent transaction and will be # executed: # # properties: # 0: -- index # <NAME>: -- site (ordered lexicographically) # a, b, c -- changes # <NAME>: # d, e # # The clock advanced to [<NAME> 1, <NAME> 1]. Now the previously # arrived tx 3 is no longer pending and can be executed: # # properties: # 0: # <NAME>: # a, b, c # <NAME>: # d, e # 1: # <NAME>: # f, g # # So the final order of all operations will be: # a, b, c, d, e, f, g # All participating sites will converge to this unique # order independently of the order in which transactions # arrive. This preserves causality and intention. # # NB: We currently only allow appending of new values as this # is all we need to resolve conflicts for JS objects. # If we want to insert to the middle of the collection # (e.g. to resolve conflicts for a text document) then # we need a more sophisticated index, see the binary tree # index implementation I had in the early versions of this # class (https://gist.github.com/jerico-dev/4566560). insertAtIndex: (key, value, index, site) -> # Create a new entry. payload = deleted: false value: value # Append the property to the crdt's property list. @properties[key] = [] unless @properties[key]? property = @properties[key] # Check that the index is valid. unless index == 0 or property[index-1]? Meteor.log.throw 'crdt.tryingToInsertIndexOutOfOrder', {key: key, index: index, site: site} property[index] = {} unless property[index]? property[index][site] = [] unless property[index][site]? property[index][site].push payload # Return the index of the new property. [index, site, property[index][site].length - 1] # Mark (entries for) the specified property deleted (invisible). # # locator: # - for Arrays: If an (integer) locator N is given, then # only the N'th currently visible entry will be marked # deleted. # - for Subdocs: If a (string) locator key:value is given, then # all entries where the subkey 'key' equals 'value' of the # object will be marked deleted. # - for Scalars: No locator can be given and all currently # visible entries will be deleted. # In all cases: If no locator was given then all property # entries for that property will be marked deleted. delete: (key, locator = null) -> return [] unless @properties[key]? # Find all visible payloads for this key. payloads = @getOrderedVisiblePayloads(key) # In the case of named subdocuments: filter by locator # if a locator has been given. if locator? and @collProps[key]?.type == '[{}]' # Named subdocuments. payloads = _.filter payloads, (payload) => payload.value[@collProps[key].locator] == locator # Delete the specified entry or entries. if locator? and @collProps[key]?.type == '[*]' # A single array index. unless 0 <= locator < payloads.length Meteor.log.throw 'crdt.tryingToDeleteNonexistentKeyAtPos', {key:key, pos: locator, crdtId: @crdtId} delPl = payloads[locator] delPl.deleted = true # Return the index of the deleted entry as an array. [[delPl.index, delPl.site, delPl.change]] else # Scalar, (full) Array or Subdocuments if payloads.length == 0 # This may happen when we have two concurrent delete operations # on exactly the same key. As this is not probable we log # a warning which may help to identify errors. Meteor.log.warning 'crdt.tryingToDeleteNonexistentKey', {key:key, crdtId: @crdtId} # Return the comprehension with the indices of all deleted entries. for delPl in payloads delPl.deleted = true [delPl.index, delPl.site, delPl.change] _setDeleted: (key, index, site, change, deleted) -> unless @properties[key]?[index]?[site]?[change]? Meteor.log.throw 'crdt.tryingToUnDeleteNonexistentIndex', {key: key, index: index, site: site, change: change} payload = @properties[key][index][site][change] if payload.deleted == deleted # This may happen when two sites delete exactly the # same index concurrently. As this is not probable we # provide a warning as this may point to an error. Meteor.log.warning 'crdt.tryingToUnDeleteIndexInVisibleEntry', {key: key, index: index, site: site, change: change} payload.deleted = deleted [index, site, change] # Mark the property at the given index deleted (invisible). The # second argument is redundant and just for consistency checking. deleteIndex: (key, index, site, change) -> @_setDeleted key, index, site, change, true # Mark the property at the given index not deleted (visible). undeleteIndex: (key, index, site) -> @_setDeleted key, index, site, change, false serialize: -> serializedCrdt = @properties _.extend serializedCrdt, _id: @id _crdtId: @crdtId _clock: @clock _deleted: @deleted serializedCrdt snapshot: -> if @deleted null else # Including the clock in the snapshot is not only # informative but makes sure that we always get # notified over DDP when something changed in the # CRDT and get a chance to publish those changes. snapshot = _id: @crdtId _clock: @clock # Build properties but filter deleted entries. for key of @properties for payload in @getOrderedVisiblePayloads(key) value = payload.value switch @collProps[key]?.type when '[*]' # The value of this property is an array. snapshot[key] = [] unless snapshot[key]? snapshot[key].push value when '[{}]' # The value of this property is a collection of # subdocs with a unique key. This guarantees # that subsequent values with the same subkey # will overwrite each other. snapshot[key] = {} unless snapshot[key]? subkey = value[@collProps[key].locator] snapshot[key][subkey] = value else # The value of this property is a scalar # (cardinality 0-1). We let later values # overwrite earlier ones. snapshot[key] = value # Transform lists of subdocuments to arrays. for collKey, collSpec of @collProps when collSpec.type = '[{}]' snapshot[collKey] = _.values snapshot[collKey] snapshot
true
# A commutative replicative data type. class Meteor._CrdtDocument constructor: (@collProps = null, serializedCrdt = null) -> if serializedCrdt? { _id: @id _crdtId: @crdtId _clock: @clock _deleted: @deleted } = serializedCrdt @properties = _.omit serializedCrdt, '_id', '_crdtId', '_clock', '_deleted' else @id = undefined @crdtId = undefined @clock = {} @properties = {} @deleted = false getNextIndex: (key) -> if @properties[key]? then @properties[key].length else 0 getOrderedVisiblePayloads: (key) -> return [] unless @properties[key] payloads = [] for sites, index in @properties[key] for site, changes of sites for payload, change in changes _.extend payload, index: index site: site change: change sortedSites = _.sortBy sites, (payload) -> payload.site for changes in sortedSites for payload in changes payloads.push payload unless payload.deleted payloads # Inserts the payload into the property list. # # Order: # - for causally related operations: The ordering is # automatically causal as transactions preserve causality. # Causal order is represented by the index value. # - for concurrent transactions: We order lexicographically # by originating site to ensure a globally unique order. # - for changes within a transaction: Order is the same # as the order of operations in the transaction. # # This ordering has the following properties: # - Causality is preserved (index). # - We get a unique order for concurrent transactions, # independently of the order in which they arrive (site). # - Effects caused by the same transaction will be # kept in a single run so that effects from several # concurrent transactions do not interleave (change). # # Assume we have the following events: # tx | clock vector | site | appended values # ================================================== # 1 | [PI:NAME:<NAME>END_PI 1, PI:NAME:<NAME>END_PI 0] | PI:NAME:<NAME>END_PI | index 0, [a, b, c] # 2 | [PI:NAME:<NAME>END_PI 2, PI:NAME:<NAME>END_PI 0] | PI:NAME:<NAME>END_PI | index 1, [f, g] # 3 | [PI:NAME:<NAME>END_PI 0, PI:NAME:<NAME>END_PI 1] | PI:NAME:<NAME>END_PI | index 0, [d, e] # # This establishes the following causality: # - Transaction 2 happend-after transaction 1. # - Transaction 3 happened concurrently with transactions 1 and 2 # # Now assume that the transactions arrive in the order 3, 2, 1: # When tx 3 arrives, the local clock is [PI:NAME:<NAME>END_PI 0, PI:NAME:<NAME>END_PI 0]. This # means that tx 3 will be executed immediately: # # properties: # 0: -- index # PI:NAME:<NAME>END_PI: -- site # d, e -- changes # # When tx 2 arrives, the local clock is [PI:NAME:<NAME>END_PI 0, PI:NAME:<NAME>END_PI 1]. This # means that the transaction will be recognized as out-of-order # and staged as a pending transaction. # # When tx 1 arrives, the local clock still is [PI:NAME:<NAME>END_PI 0, PI:NAME:<NAME>END_PI 1]. # Tx 1 is recognized as concurrent transaction and will be # executed: # # properties: # 0: -- index # PI:NAME:<NAME>END_PI: -- site (ordered lexicographically) # a, b, c -- changes # PI:NAME:<NAME>END_PI: # d, e # # The clock advanced to [PI:NAME:<NAME>END_PI 1, PI:NAME:<NAME>END_PI 1]. Now the previously # arrived tx 3 is no longer pending and can be executed: # # properties: # 0: # PI:NAME:<NAME>END_PI: # a, b, c # PI:NAME:<NAME>END_PI: # d, e # 1: # PI:NAME:<NAME>END_PI: # f, g # # So the final order of all operations will be: # a, b, c, d, e, f, g # All participating sites will converge to this unique # order independently of the order in which transactions # arrive. This preserves causality and intention. # # NB: We currently only allow appending of new values as this # is all we need to resolve conflicts for JS objects. # If we want to insert to the middle of the collection # (e.g. to resolve conflicts for a text document) then # we need a more sophisticated index, see the binary tree # index implementation I had in the early versions of this # class (https://gist.github.com/jerico-dev/4566560). insertAtIndex: (key, value, index, site) -> # Create a new entry. payload = deleted: false value: value # Append the property to the crdt's property list. @properties[key] = [] unless @properties[key]? property = @properties[key] # Check that the index is valid. unless index == 0 or property[index-1]? Meteor.log.throw 'crdt.tryingToInsertIndexOutOfOrder', {key: key, index: index, site: site} property[index] = {} unless property[index]? property[index][site] = [] unless property[index][site]? property[index][site].push payload # Return the index of the new property. [index, site, property[index][site].length - 1] # Mark (entries for) the specified property deleted (invisible). # # locator: # - for Arrays: If an (integer) locator N is given, then # only the N'th currently visible entry will be marked # deleted. # - for Subdocs: If a (string) locator key:value is given, then # all entries where the subkey 'key' equals 'value' of the # object will be marked deleted. # - for Scalars: No locator can be given and all currently # visible entries will be deleted. # In all cases: If no locator was given then all property # entries for that property will be marked deleted. delete: (key, locator = null) -> return [] unless @properties[key]? # Find all visible payloads for this key. payloads = @getOrderedVisiblePayloads(key) # In the case of named subdocuments: filter by locator # if a locator has been given. if locator? and @collProps[key]?.type == '[{}]' # Named subdocuments. payloads = _.filter payloads, (payload) => payload.value[@collProps[key].locator] == locator # Delete the specified entry or entries. if locator? and @collProps[key]?.type == '[*]' # A single array index. unless 0 <= locator < payloads.length Meteor.log.throw 'crdt.tryingToDeleteNonexistentKeyAtPos', {key:key, pos: locator, crdtId: @crdtId} delPl = payloads[locator] delPl.deleted = true # Return the index of the deleted entry as an array. [[delPl.index, delPl.site, delPl.change]] else # Scalar, (full) Array or Subdocuments if payloads.length == 0 # This may happen when we have two concurrent delete operations # on exactly the same key. As this is not probable we log # a warning which may help to identify errors. Meteor.log.warning 'crdt.tryingToDeleteNonexistentKey', {key:key, crdtId: @crdtId} # Return the comprehension with the indices of all deleted entries. for delPl in payloads delPl.deleted = true [delPl.index, delPl.site, delPl.change] _setDeleted: (key, index, site, change, deleted) -> unless @properties[key]?[index]?[site]?[change]? Meteor.log.throw 'crdt.tryingToUnDeleteNonexistentIndex', {key: key, index: index, site: site, change: change} payload = @properties[key][index][site][change] if payload.deleted == deleted # This may happen when two sites delete exactly the # same index concurrently. As this is not probable we # provide a warning as this may point to an error. Meteor.log.warning 'crdt.tryingToUnDeleteIndexInVisibleEntry', {key: key, index: index, site: site, change: change} payload.deleted = deleted [index, site, change] # Mark the property at the given index deleted (invisible). The # second argument is redundant and just for consistency checking. deleteIndex: (key, index, site, change) -> @_setDeleted key, index, site, change, true # Mark the property at the given index not deleted (visible). undeleteIndex: (key, index, site) -> @_setDeleted key, index, site, change, false serialize: -> serializedCrdt = @properties _.extend serializedCrdt, _id: @id _crdtId: @crdtId _clock: @clock _deleted: @deleted serializedCrdt snapshot: -> if @deleted null else # Including the clock in the snapshot is not only # informative but makes sure that we always get # notified over DDP when something changed in the # CRDT and get a chance to publish those changes. snapshot = _id: @crdtId _clock: @clock # Build properties but filter deleted entries. for key of @properties for payload in @getOrderedVisiblePayloads(key) value = payload.value switch @collProps[key]?.type when '[*]' # The value of this property is an array. snapshot[key] = [] unless snapshot[key]? snapshot[key].push value when '[{}]' # The value of this property is a collection of # subdocs with a unique key. This guarantees # that subsequent values with the same subkey # will overwrite each other. snapshot[key] = {} unless snapshot[key]? subkey = value[@collProps[key].locator] snapshot[key][subkey] = value else # The value of this property is a scalar # (cardinality 0-1). We let later values # overwrite earlier ones. snapshot[key] = value # Transform lists of subdocuments to arrays. for collKey, collSpec of @collProps when collSpec.type = '[{}]' snapshot[collKey] = _.values snapshot[collKey] snapshot
[ { "context": "e: Backbone.Many\n key: 'managers'\n collectionType: -> factory.invoke 'users:e", "end": 957, "score": 0.9746805429458618, "start": 949, "tag": "KEY", "value": "managers" } ]
src/app/modules/tickets/entities/categories/Category.coffee
josepramon/tfm-adminApp
0
# Dependencies # ------------------------- # Base class (extends Backbone.Model) Model = require 'msq-appbase/lib/appBaseComponents/entities/Model' # Libs/generic stuff: i18n = require 'i18next-client' factory = require 'msq-appbase/lib/utilities/factory' Backbone = require 'backbone' ### Ticket category model ======================= @class @augments Model ### module.exports = class Category extends Model ### @property {String} API url ### urlRoot: '/api/tickets/categories' ### @property {Object} Model default attributes ### defaults: ### @property {ManagersCollection} Managers assigned to this category ### managers: [] ### @property {String} Category name ### name: '' ### @property {String} Category description ### description: '' ### @property {Array} Nested entities ### relations: [ type: Backbone.Many key: 'managers' collectionType: -> factory.invoke 'users:entities|ManagersCollection' saveFilterAttributes: ['id'] ] ### Relations to expand where querying the server @property {Array} the attributes to expand. @static ### @expandedRelations: ['managers', 'managers.profile', 'managers.profile.image'] ### @property {Object} Virtual fields ### computed: managers_total: get: -> managers = @get 'managers' total = if managers and managers.state then managers.state.totalRecords unless total then total = 0 total transient: true ### @property {Object} Model validation rules ### validation: name: required: true ### @property {Object} Custom attribute labels Used by the validator when building the error messages @static #### @labels: name : -> i18n.t 'tickets:::CategoryModel::name' description : -> i18n.t 'tickets:::CategoryModel::description' managers : -> i18n.t 'tickets:::CategoryModel::managers' managers_total : -> i18n.t 'tickets:::CategoryModel::managers'
45977
# Dependencies # ------------------------- # Base class (extends Backbone.Model) Model = require 'msq-appbase/lib/appBaseComponents/entities/Model' # Libs/generic stuff: i18n = require 'i18next-client' factory = require 'msq-appbase/lib/utilities/factory' Backbone = require 'backbone' ### Ticket category model ======================= @class @augments Model ### module.exports = class Category extends Model ### @property {String} API url ### urlRoot: '/api/tickets/categories' ### @property {Object} Model default attributes ### defaults: ### @property {ManagersCollection} Managers assigned to this category ### managers: [] ### @property {String} Category name ### name: '' ### @property {String} Category description ### description: '' ### @property {Array} Nested entities ### relations: [ type: Backbone.Many key: '<KEY>' collectionType: -> factory.invoke 'users:entities|ManagersCollection' saveFilterAttributes: ['id'] ] ### Relations to expand where querying the server @property {Array} the attributes to expand. @static ### @expandedRelations: ['managers', 'managers.profile', 'managers.profile.image'] ### @property {Object} Virtual fields ### computed: managers_total: get: -> managers = @get 'managers' total = if managers and managers.state then managers.state.totalRecords unless total then total = 0 total transient: true ### @property {Object} Model validation rules ### validation: name: required: true ### @property {Object} Custom attribute labels Used by the validator when building the error messages @static #### @labels: name : -> i18n.t 'tickets:::CategoryModel::name' description : -> i18n.t 'tickets:::CategoryModel::description' managers : -> i18n.t 'tickets:::CategoryModel::managers' managers_total : -> i18n.t 'tickets:::CategoryModel::managers'
true
# Dependencies # ------------------------- # Base class (extends Backbone.Model) Model = require 'msq-appbase/lib/appBaseComponents/entities/Model' # Libs/generic stuff: i18n = require 'i18next-client' factory = require 'msq-appbase/lib/utilities/factory' Backbone = require 'backbone' ### Ticket category model ======================= @class @augments Model ### module.exports = class Category extends Model ### @property {String} API url ### urlRoot: '/api/tickets/categories' ### @property {Object} Model default attributes ### defaults: ### @property {ManagersCollection} Managers assigned to this category ### managers: [] ### @property {String} Category name ### name: '' ### @property {String} Category description ### description: '' ### @property {Array} Nested entities ### relations: [ type: Backbone.Many key: 'PI:KEY:<KEY>END_PI' collectionType: -> factory.invoke 'users:entities|ManagersCollection' saveFilterAttributes: ['id'] ] ### Relations to expand where querying the server @property {Array} the attributes to expand. @static ### @expandedRelations: ['managers', 'managers.profile', 'managers.profile.image'] ### @property {Object} Virtual fields ### computed: managers_total: get: -> managers = @get 'managers' total = if managers and managers.state then managers.state.totalRecords unless total then total = 0 total transient: true ### @property {Object} Model validation rules ### validation: name: required: true ### @property {Object} Custom attribute labels Used by the validator when building the error messages @static #### @labels: name : -> i18n.t 'tickets:::CategoryModel::name' description : -> i18n.t 'tickets:::CategoryModel::description' managers : -> i18n.t 'tickets:::CategoryModel::managers' managers_total : -> i18n.t 'tickets:::CategoryModel::managers'
[ { "context": "sion\r\n\r\nuid = (len = 16, prefix = \"\", keyspace = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\") ->\r\n prefix += keyspace.charAt(Math.floor(Math", "end": 248, "score": 0.9995819926261902, "start": 186, "tag": "KEY", "value": "ABCDEFGHIJKLMNOPQRSTUVWX...
servers/www/assets/js/services/panes/streamer.coffee
sitedata/plunker
340
#= require ../../services/panels #= require ../../services/scratch #= require ../../services/url #= require ../../directives/discussion uid = (len = 16, prefix = "", keyspace = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") -> prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0 prefix synchro = new class Synchro constructor: (@scope) -> @localEvents = 0 @remoteEvents = 0 handleRemoteEvent: (cb) -> return false if @localEvents > @remoteEvents @remoteEvents++ cb() @remoteEvents-- true handleLocalEvent: (cb) -> return false if @remoteEvents > @localEvents @localEvents++ cb() @localEvents-- true resetFiles = (scratch, files) -> # We don't want to reset the *whole* scratch here as that would result # in changing the active plunk to a blank one. We will just adjust the # plunk's description and tags and reset the buffers. new_files = [] for channel, file of files new_files.push angular.extend file, channel: channel scratch.buffers.reset(new_files) scratch.buffers.activate(index) if index = scratch.buffers.findBy("filename", "index.html") resetScratch = (scratch, state) -> scratch.plunk.description = state.description scratch.plunk.tags = state.tags resetFiles(scratch, state.files) module = angular.module("plunker.panels") module.directive "plunkerChannel", [ "stream", (stream) -> restrict: "E" replace: true template: """ <div style="display: none;"></div> """ link: ($scope, el, attr) -> buffer = $scope.buffer # finalize = (channel) -> # Sync the content filename = channel.at("filename") content = channel.at("content") content.attach_ace(buffer.session, stream.keep) # Watch for remote changes to filename channel.on "replace", (key, previous, current) -> if key is "filename" then synchro.handleRemoteEvent -> $scope.$apply -> buffer.filename = current # Watch for local changes to filename $scope.$watch "buffer.filename", (new_filename, old_filename) -> if new_filename isnt old_filename then synchro.handleLocalEvent -> filename.set(new_filename) $scope.$on "$destroy", -> content.detach_ace() synchro.handleLocalEvent -> channel.remove() delete buffer.channel # No channel has been created yet. This is a new file, created locally unless buffer.channel buffer.channel = uid(10) state = filename: buffer.filename content: buffer.content channel = stream.doc.at(["files", buffer.channel]) channel.set state, (err) -> if err then console.error("Error creating channel") else finalize(channel) else finalize(stream.doc.at(["files", buffer.channel])) ] module.factory "stream", [ () -> id: uid(16) streaming: false doc: null ] module.requires.push("plunker.discussion", "plunker.url") module.run [ "$location", "$timeout", "$q", "panels", "scratch", "stream", "url", ($location, $timeout, $q, panels, scratch, stream, url) -> panels.push new class name: "streamer" order: 3 size: 340 title: "Real-time collaboration" icon: "icon-fire" template: """ <div id="panel-streamer" class="plnk-stream" ng-switch="stream.streaming"> <div ng-switch-when="streaming"> <plunker-channel ng-repeat="buffer in scratch.buffers.queue"></plunker-channel> <div class="status"> <h4>Streaming enabled</h4> Stream: <a ng-href="{{url.www}}/edit/?p=streamers={{stream.id}}" target="_blank" title="Link to this stream"><code class="stream-id" ng-bind="stream.id"></code></a> <button class="btn btn-mini btn-danger" ng-click="stopStream()" title="Disconnect from stream"> <i class="icon-stop"></i> Disconnect </button> </div> <plunker-discussion room="stream.id"></plunker-discussion> </div> <div ng-switch-default> <h1>Streaming</h1> <p> Streaming enables real-time collaboraboration on Plunker. When you join a stream, the contents of your editor are kept in sync with the stream and reflect changes made by others in the same stream. </p> <form ng-submit="startStream(stream.id)"> <input class="mediumtext" ng-model="stream.id" size="32" /> <button class="btn btn-primary" type="submit">Stream</button> </form> <h4>What happens if I hit save?</h4> <p> The current contents of your plunk will be saved as if you had made all the changes to the files yourself. No one else in the stream will be affected at all by saving your state. </p> <h4>What happens if I load a template?</h4> <p> If you load a template, the resulting files will be sent to everyone else in the stream as if you had made the changes yourself. This is usually not what you want to do. </p> </div> </div> """ getConnection: -> location = window.location @conn ||= new sharejs.Connection("#{location.protocol}//#{location.host}/channel") getLocalState: -> state = description: scratch.plunk.description tags: scratch.plunk.tags files: {} state join: (id = uid()) -> self = @ deferred = $q.defer() @getConnection().open "stream:#{id}", "json", (err, doc) -> if err then return deferred.reject "Stream error: Unable to join stream" stream.id = id stream.doc = doc stream.keep = doc.created is true stream.streaming = "streaming" if stream.keep # Reset the channel to the current local state doc.submitOp [ { p: [], od: doc.snapshot, oi: self.getLocalState() } ], (err) -> self.scope.$apply -> if err doc.close() deferred.reject("Stream error: Error setting initial state") else deferred.resolve(stream) else self.scope.$apply -> synchro.handleRemoteEvent -> deferred.resolve(stream) deferred.promise stop: -> self = @ if self.doc self.scope.scratch = null stream.doc.close() stream.streaming = false stream.doc = null stream.id = uid() search = $location.search() delete search.s scratch.unlock() $location.search(search).replace() start: (stream) -> self = @ self.doc = stream.doc resetScratch(scratch, stream.doc.get()) unless stream.keep scratch.lock("Connected to stream") # Assign the scratch to the local scope which will trigger creation of # custom directives for each channel self.scope.scratch = scratch files = @doc.at("files") files.on "insert", (pos, data) -> synchro.handleRemoteEvent -> unless scratch.buffers.findBy("channel", pos) self.scope.$apply -> scratch.buffers.add angular.extend(data, channel: pos) files.on "delete", (pos, data) -> synchro.handleRemoteEvent -> self.scope.$apply -> scratch.buffers.remove(buffer) if buffer = scratch.buffers.findBy("channel", pos) search = $location.search() search.s = stream.id $location.search(search).replace() link: ($scope, el, attrs) -> self = @ self.scope = $scope synchro.scope = $scope $scope.url = url $scope.stream = stream $scope.startStream = (id) -> scratch.loading = true self.join(id).then (id, doc, keep) -> self.start(id, doc, keep) scratch.loading = false , (error) -> alert(error) scratch.loading = false $scope.stopStream = -> self.stop() if id = $location.search().s then $timeout -> $scope.startStream(id) , 500 #TODO: HACK! deactivate: ($scope, el, attrs) -> activate: ($scope, el, attrs) -> ] # This is some utility code to connect an ace editor to a sharejs document. Range = require("ace/range").Range # Convert an ace delta into an op understood by share.js applyToShareJS = (editorDoc, delta, doc) -> # Get the start position of the range, in no. of characters getStartOffsetPosition = (range) -> # This is quite inefficient - getLines makes a copy of the entire # lines array in the document. It would be nice if we could just # access them directly. lines = editorDoc.getLines 0, range.start.row offset = 0 for line, i in lines offset += if i < range.start.row line.length else range.start.column # Add the row number to include newlines. offset + range.start.row pos = getStartOffsetPosition(delta.range) switch delta.action when 'insertText' then doc.insert pos, delta.text when 'removeText' then doc.del pos, delta.text.length when 'insertLines' text = delta.lines.join('\n') + '\n' doc.insert pos, text when 'removeLines' text = delta.lines.join('\n') + '\n' doc.del pos, text.length else throw new Error "unknown action: #{delta.action}" return # Attach an ace editor to the document. The editor's contents are replaced # with the document's contents unless keepEditorContents is true. (In which case the document's # contents are nuked and replaced with the editor's). window.sharejs.extendDoc 'attach_ace', (session, keepEditorContents) -> doc = this editorDoc = session.getDocument() editorDoc.setNewLineMode 'unix' check = -> window.setTimeout -> editorText = editorDoc.getValue() otText = doc.getText() if editorText != otText console.error "Text does not match!" console.error "editor: #{editorText}" console.error "ot: #{otText}" # Should probably also replace the editor text with the doc snapshot. , 0 # Not needed because we ALWAYS either create a new channel or keep the old one #if keepEditorContents # doc.del 0, doc.getText().length # doc.insert 0, editorDoc.getValue() #else # Already done by custom code # editorDoc.setValue doc.getText() check() # When we apply ops from sharejs, ace emits edit events. We need to ignore those # to prevent an infinite typing loop. suppress = false # Listen for edits in ace editorListener = (change) -> return if suppress applyToShareJS editorDoc, change.data, doc check() session.on 'change', editorListener # Horribly inefficient. offsetToPos = (offset) -> # Again, very inefficient. lines = editorDoc.getAllLines() row = 0 for line, row in lines break if offset <= line.length # +1 for the newline. offset -= lines[row].length + 1 row:row, column:offset doc.on 'insert', (pos, text) -> suppress = true editorDoc.insert offsetToPos(pos), text suppress = false check() doc.on 'delete', (pos, text) -> suppress = true range = Range.fromPoints offsetToPos(pos), offsetToPos(pos + text.length) editorDoc.remove range suppress = false check() doc.detach_ace = -> session.removeListener 'change', editorListener delete doc.detach_ace return
154123
#= require ../../services/panels #= require ../../services/scratch #= require ../../services/url #= require ../../directives/discussion uid = (len = 16, prefix = "", keyspace = "<KEY>") -> prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0 prefix synchro = new class Synchro constructor: (@scope) -> @localEvents = 0 @remoteEvents = 0 handleRemoteEvent: (cb) -> return false if @localEvents > @remoteEvents @remoteEvents++ cb() @remoteEvents-- true handleLocalEvent: (cb) -> return false if @remoteEvents > @localEvents @localEvents++ cb() @localEvents-- true resetFiles = (scratch, files) -> # We don't want to reset the *whole* scratch here as that would result # in changing the active plunk to a blank one. We will just adjust the # plunk's description and tags and reset the buffers. new_files = [] for channel, file of files new_files.push angular.extend file, channel: channel scratch.buffers.reset(new_files) scratch.buffers.activate(index) if index = scratch.buffers.findBy("filename", "index.html") resetScratch = (scratch, state) -> scratch.plunk.description = state.description scratch.plunk.tags = state.tags resetFiles(scratch, state.files) module = angular.module("plunker.panels") module.directive "plunkerChannel", [ "stream", (stream) -> restrict: "E" replace: true template: """ <div style="display: none;"></div> """ link: ($scope, el, attr) -> buffer = $scope.buffer # finalize = (channel) -> # Sync the content filename = channel.at("filename") content = channel.at("content") content.attach_ace(buffer.session, stream.keep) # Watch for remote changes to filename channel.on "replace", (key, previous, current) -> if key is "filename" then synchro.handleRemoteEvent -> $scope.$apply -> buffer.filename = current # Watch for local changes to filename $scope.$watch "buffer.filename", (new_filename, old_filename) -> if new_filename isnt old_filename then synchro.handleLocalEvent -> filename.set(new_filename) $scope.$on "$destroy", -> content.detach_ace() synchro.handleLocalEvent -> channel.remove() delete buffer.channel # No channel has been created yet. This is a new file, created locally unless buffer.channel buffer.channel = uid(10) state = filename: buffer.filename content: buffer.content channel = stream.doc.at(["files", buffer.channel]) channel.set state, (err) -> if err then console.error("Error creating channel") else finalize(channel) else finalize(stream.doc.at(["files", buffer.channel])) ] module.factory "stream", [ () -> id: uid(16) streaming: false doc: null ] module.requires.push("plunker.discussion", "plunker.url") module.run [ "$location", "$timeout", "$q", "panels", "scratch", "stream", "url", ($location, $timeout, $q, panels, scratch, stream, url) -> panels.push new class name: "streamer" order: 3 size: 340 title: "Real-time collaboration" icon: "icon-fire" template: """ <div id="panel-streamer" class="plnk-stream" ng-switch="stream.streaming"> <div ng-switch-when="streaming"> <plunker-channel ng-repeat="buffer in scratch.buffers.queue"></plunker-channel> <div class="status"> <h4>Streaming enabled</h4> Stream: <a ng-href="{{url.www}}/edit/?p=streamers={{stream.id}}" target="_blank" title="Link to this stream"><code class="stream-id" ng-bind="stream.id"></code></a> <button class="btn btn-mini btn-danger" ng-click="stopStream()" title="Disconnect from stream"> <i class="icon-stop"></i> Disconnect </button> </div> <plunker-discussion room="stream.id"></plunker-discussion> </div> <div ng-switch-default> <h1>Streaming</h1> <p> Streaming enables real-time collaboraboration on Plunker. When you join a stream, the contents of your editor are kept in sync with the stream and reflect changes made by others in the same stream. </p> <form ng-submit="startStream(stream.id)"> <input class="mediumtext" ng-model="stream.id" size="32" /> <button class="btn btn-primary" type="submit">Stream</button> </form> <h4>What happens if I hit save?</h4> <p> The current contents of your plunk will be saved as if you had made all the changes to the files yourself. No one else in the stream will be affected at all by saving your state. </p> <h4>What happens if I load a template?</h4> <p> If you load a template, the resulting files will be sent to everyone else in the stream as if you had made the changes yourself. This is usually not what you want to do. </p> </div> </div> """ getConnection: -> location = window.location @conn ||= new sharejs.Connection("#{location.protocol}//#{location.host}/channel") getLocalState: -> state = description: scratch.plunk.description tags: scratch.plunk.tags files: {} state join: (id = uid()) -> self = @ deferred = $q.defer() @getConnection().open "stream:#{id}", "json", (err, doc) -> if err then return deferred.reject "Stream error: Unable to join stream" stream.id = id stream.doc = doc stream.keep = doc.created is true stream.streaming = "streaming" if stream.keep # Reset the channel to the current local state doc.submitOp [ { p: [], od: doc.snapshot, oi: self.getLocalState() } ], (err) -> self.scope.$apply -> if err doc.close() deferred.reject("Stream error: Error setting initial state") else deferred.resolve(stream) else self.scope.$apply -> synchro.handleRemoteEvent -> deferred.resolve(stream) deferred.promise stop: -> self = @ if self.doc self.scope.scratch = null stream.doc.close() stream.streaming = false stream.doc = null stream.id = uid() search = $location.search() delete search.s scratch.unlock() $location.search(search).replace() start: (stream) -> self = @ self.doc = stream.doc resetScratch(scratch, stream.doc.get()) unless stream.keep scratch.lock("Connected to stream") # Assign the scratch to the local scope which will trigger creation of # custom directives for each channel self.scope.scratch = scratch files = @doc.at("files") files.on "insert", (pos, data) -> synchro.handleRemoteEvent -> unless scratch.buffers.findBy("channel", pos) self.scope.$apply -> scratch.buffers.add angular.extend(data, channel: pos) files.on "delete", (pos, data) -> synchro.handleRemoteEvent -> self.scope.$apply -> scratch.buffers.remove(buffer) if buffer = scratch.buffers.findBy("channel", pos) search = $location.search() search.s = stream.id $location.search(search).replace() link: ($scope, el, attrs) -> self = @ self.scope = $scope synchro.scope = $scope $scope.url = url $scope.stream = stream $scope.startStream = (id) -> scratch.loading = true self.join(id).then (id, doc, keep) -> self.start(id, doc, keep) scratch.loading = false , (error) -> alert(error) scratch.loading = false $scope.stopStream = -> self.stop() if id = $location.search().s then $timeout -> $scope.startStream(id) , 500 #TODO: HACK! deactivate: ($scope, el, attrs) -> activate: ($scope, el, attrs) -> ] # This is some utility code to connect an ace editor to a sharejs document. Range = require("ace/range").Range # Convert an ace delta into an op understood by share.js applyToShareJS = (editorDoc, delta, doc) -> # Get the start position of the range, in no. of characters getStartOffsetPosition = (range) -> # This is quite inefficient - getLines makes a copy of the entire # lines array in the document. It would be nice if we could just # access them directly. lines = editorDoc.getLines 0, range.start.row offset = 0 for line, i in lines offset += if i < range.start.row line.length else range.start.column # Add the row number to include newlines. offset + range.start.row pos = getStartOffsetPosition(delta.range) switch delta.action when 'insertText' then doc.insert pos, delta.text when 'removeText' then doc.del pos, delta.text.length when 'insertLines' text = delta.lines.join('\n') + '\n' doc.insert pos, text when 'removeLines' text = delta.lines.join('\n') + '\n' doc.del pos, text.length else throw new Error "unknown action: #{delta.action}" return # Attach an ace editor to the document. The editor's contents are replaced # with the document's contents unless keepEditorContents is true. (In which case the document's # contents are nuked and replaced with the editor's). window.sharejs.extendDoc 'attach_ace', (session, keepEditorContents) -> doc = this editorDoc = session.getDocument() editorDoc.setNewLineMode 'unix' check = -> window.setTimeout -> editorText = editorDoc.getValue() otText = doc.getText() if editorText != otText console.error "Text does not match!" console.error "editor: #{editorText}" console.error "ot: #{otText}" # Should probably also replace the editor text with the doc snapshot. , 0 # Not needed because we ALWAYS either create a new channel or keep the old one #if keepEditorContents # doc.del 0, doc.getText().length # doc.insert 0, editorDoc.getValue() #else # Already done by custom code # editorDoc.setValue doc.getText() check() # When we apply ops from sharejs, ace emits edit events. We need to ignore those # to prevent an infinite typing loop. suppress = false # Listen for edits in ace editorListener = (change) -> return if suppress applyToShareJS editorDoc, change.data, doc check() session.on 'change', editorListener # Horribly inefficient. offsetToPos = (offset) -> # Again, very inefficient. lines = editorDoc.getAllLines() row = 0 for line, row in lines break if offset <= line.length # +1 for the newline. offset -= lines[row].length + 1 row:row, column:offset doc.on 'insert', (pos, text) -> suppress = true editorDoc.insert offsetToPos(pos), text suppress = false check() doc.on 'delete', (pos, text) -> suppress = true range = Range.fromPoints offsetToPos(pos), offsetToPos(pos + text.length) editorDoc.remove range suppress = false check() doc.detach_ace = -> session.removeListener 'change', editorListener delete doc.detach_ace return
true
#= require ../../services/panels #= require ../../services/scratch #= require ../../services/url #= require ../../directives/discussion uid = (len = 16, prefix = "", keyspace = "PI:KEY:<KEY>END_PI") -> prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0 prefix synchro = new class Synchro constructor: (@scope) -> @localEvents = 0 @remoteEvents = 0 handleRemoteEvent: (cb) -> return false if @localEvents > @remoteEvents @remoteEvents++ cb() @remoteEvents-- true handleLocalEvent: (cb) -> return false if @remoteEvents > @localEvents @localEvents++ cb() @localEvents-- true resetFiles = (scratch, files) -> # We don't want to reset the *whole* scratch here as that would result # in changing the active plunk to a blank one. We will just adjust the # plunk's description and tags and reset the buffers. new_files = [] for channel, file of files new_files.push angular.extend file, channel: channel scratch.buffers.reset(new_files) scratch.buffers.activate(index) if index = scratch.buffers.findBy("filename", "index.html") resetScratch = (scratch, state) -> scratch.plunk.description = state.description scratch.plunk.tags = state.tags resetFiles(scratch, state.files) module = angular.module("plunker.panels") module.directive "plunkerChannel", [ "stream", (stream) -> restrict: "E" replace: true template: """ <div style="display: none;"></div> """ link: ($scope, el, attr) -> buffer = $scope.buffer # finalize = (channel) -> # Sync the content filename = channel.at("filename") content = channel.at("content") content.attach_ace(buffer.session, stream.keep) # Watch for remote changes to filename channel.on "replace", (key, previous, current) -> if key is "filename" then synchro.handleRemoteEvent -> $scope.$apply -> buffer.filename = current # Watch for local changes to filename $scope.$watch "buffer.filename", (new_filename, old_filename) -> if new_filename isnt old_filename then synchro.handleLocalEvent -> filename.set(new_filename) $scope.$on "$destroy", -> content.detach_ace() synchro.handleLocalEvent -> channel.remove() delete buffer.channel # No channel has been created yet. This is a new file, created locally unless buffer.channel buffer.channel = uid(10) state = filename: buffer.filename content: buffer.content channel = stream.doc.at(["files", buffer.channel]) channel.set state, (err) -> if err then console.error("Error creating channel") else finalize(channel) else finalize(stream.doc.at(["files", buffer.channel])) ] module.factory "stream", [ () -> id: uid(16) streaming: false doc: null ] module.requires.push("plunker.discussion", "plunker.url") module.run [ "$location", "$timeout", "$q", "panels", "scratch", "stream", "url", ($location, $timeout, $q, panels, scratch, stream, url) -> panels.push new class name: "streamer" order: 3 size: 340 title: "Real-time collaboration" icon: "icon-fire" template: """ <div id="panel-streamer" class="plnk-stream" ng-switch="stream.streaming"> <div ng-switch-when="streaming"> <plunker-channel ng-repeat="buffer in scratch.buffers.queue"></plunker-channel> <div class="status"> <h4>Streaming enabled</h4> Stream: <a ng-href="{{url.www}}/edit/?p=streamers={{stream.id}}" target="_blank" title="Link to this stream"><code class="stream-id" ng-bind="stream.id"></code></a> <button class="btn btn-mini btn-danger" ng-click="stopStream()" title="Disconnect from stream"> <i class="icon-stop"></i> Disconnect </button> </div> <plunker-discussion room="stream.id"></plunker-discussion> </div> <div ng-switch-default> <h1>Streaming</h1> <p> Streaming enables real-time collaboraboration on Plunker. When you join a stream, the contents of your editor are kept in sync with the stream and reflect changes made by others in the same stream. </p> <form ng-submit="startStream(stream.id)"> <input class="mediumtext" ng-model="stream.id" size="32" /> <button class="btn btn-primary" type="submit">Stream</button> </form> <h4>What happens if I hit save?</h4> <p> The current contents of your plunk will be saved as if you had made all the changes to the files yourself. No one else in the stream will be affected at all by saving your state. </p> <h4>What happens if I load a template?</h4> <p> If you load a template, the resulting files will be sent to everyone else in the stream as if you had made the changes yourself. This is usually not what you want to do. </p> </div> </div> """ getConnection: -> location = window.location @conn ||= new sharejs.Connection("#{location.protocol}//#{location.host}/channel") getLocalState: -> state = description: scratch.plunk.description tags: scratch.plunk.tags files: {} state join: (id = uid()) -> self = @ deferred = $q.defer() @getConnection().open "stream:#{id}", "json", (err, doc) -> if err then return deferred.reject "Stream error: Unable to join stream" stream.id = id stream.doc = doc stream.keep = doc.created is true stream.streaming = "streaming" if stream.keep # Reset the channel to the current local state doc.submitOp [ { p: [], od: doc.snapshot, oi: self.getLocalState() } ], (err) -> self.scope.$apply -> if err doc.close() deferred.reject("Stream error: Error setting initial state") else deferred.resolve(stream) else self.scope.$apply -> synchro.handleRemoteEvent -> deferred.resolve(stream) deferred.promise stop: -> self = @ if self.doc self.scope.scratch = null stream.doc.close() stream.streaming = false stream.doc = null stream.id = uid() search = $location.search() delete search.s scratch.unlock() $location.search(search).replace() start: (stream) -> self = @ self.doc = stream.doc resetScratch(scratch, stream.doc.get()) unless stream.keep scratch.lock("Connected to stream") # Assign the scratch to the local scope which will trigger creation of # custom directives for each channel self.scope.scratch = scratch files = @doc.at("files") files.on "insert", (pos, data) -> synchro.handleRemoteEvent -> unless scratch.buffers.findBy("channel", pos) self.scope.$apply -> scratch.buffers.add angular.extend(data, channel: pos) files.on "delete", (pos, data) -> synchro.handleRemoteEvent -> self.scope.$apply -> scratch.buffers.remove(buffer) if buffer = scratch.buffers.findBy("channel", pos) search = $location.search() search.s = stream.id $location.search(search).replace() link: ($scope, el, attrs) -> self = @ self.scope = $scope synchro.scope = $scope $scope.url = url $scope.stream = stream $scope.startStream = (id) -> scratch.loading = true self.join(id).then (id, doc, keep) -> self.start(id, doc, keep) scratch.loading = false , (error) -> alert(error) scratch.loading = false $scope.stopStream = -> self.stop() if id = $location.search().s then $timeout -> $scope.startStream(id) , 500 #TODO: HACK! deactivate: ($scope, el, attrs) -> activate: ($scope, el, attrs) -> ] # This is some utility code to connect an ace editor to a sharejs document. Range = require("ace/range").Range # Convert an ace delta into an op understood by share.js applyToShareJS = (editorDoc, delta, doc) -> # Get the start position of the range, in no. of characters getStartOffsetPosition = (range) -> # This is quite inefficient - getLines makes a copy of the entire # lines array in the document. It would be nice if we could just # access them directly. lines = editorDoc.getLines 0, range.start.row offset = 0 for line, i in lines offset += if i < range.start.row line.length else range.start.column # Add the row number to include newlines. offset + range.start.row pos = getStartOffsetPosition(delta.range) switch delta.action when 'insertText' then doc.insert pos, delta.text when 'removeText' then doc.del pos, delta.text.length when 'insertLines' text = delta.lines.join('\n') + '\n' doc.insert pos, text when 'removeLines' text = delta.lines.join('\n') + '\n' doc.del pos, text.length else throw new Error "unknown action: #{delta.action}" return # Attach an ace editor to the document. The editor's contents are replaced # with the document's contents unless keepEditorContents is true. (In which case the document's # contents are nuked and replaced with the editor's). window.sharejs.extendDoc 'attach_ace', (session, keepEditorContents) -> doc = this editorDoc = session.getDocument() editorDoc.setNewLineMode 'unix' check = -> window.setTimeout -> editorText = editorDoc.getValue() otText = doc.getText() if editorText != otText console.error "Text does not match!" console.error "editor: #{editorText}" console.error "ot: #{otText}" # Should probably also replace the editor text with the doc snapshot. , 0 # Not needed because we ALWAYS either create a new channel or keep the old one #if keepEditorContents # doc.del 0, doc.getText().length # doc.insert 0, editorDoc.getValue() #else # Already done by custom code # editorDoc.setValue doc.getText() check() # When we apply ops from sharejs, ace emits edit events. We need to ignore those # to prevent an infinite typing loop. suppress = false # Listen for edits in ace editorListener = (change) -> return if suppress applyToShareJS editorDoc, change.data, doc check() session.on 'change', editorListener # Horribly inefficient. offsetToPos = (offset) -> # Again, very inefficient. lines = editorDoc.getAllLines() row = 0 for line, row in lines break if offset <= line.length # +1 for the newline. offset -= lines[row].length + 1 row:row, column:offset doc.on 'insert', (pos, text) -> suppress = true editorDoc.insert offsetToPos(pos), text suppress = false check() doc.on 'delete', (pos, text) -> suppress = true range = Range.fromPoints offsetToPos(pos), offsetToPos(pos + text.length) editorDoc.remove range suppress = false check() doc.detach_ace = -> session.removeListener 'change', editorListener delete doc.detach_ace return
[ { "context": "ult()\n navigator.id.request {\n siteName: 'Asciinema',\n siteLogo: 'data:image/png;base64,iV", "end": 128, "score": 0.841982364654541, "start": 125, "tag": "NAME", "value": "Asc" } ]
app/assets/javascripts/persona.js.coffee
zouguangxian/asciinema.org
1
$ -> $('#persona-button, #log-in').click (event) -> event.preventDefault() navigator.id.request { siteName: 'Asciinema', siteLogo: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAABlBMVEUAAAD///+l2Z/dAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wHGBMiFVqqanYAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVRo3u3KoQEAAAgDoP3/tBaD0WiATAJwVIsgCIIgCIIgCIIgCIIgCIIgCMKHADAafyL3ebnQxskAAAAASUVORK5CYII=', backgroundColor: '#d95525', privacyPolicy: 'https://asciinema.org/privacy', termsOfService: 'https://asciinema.org/tos' } if window.browserIdUser $('header .logout').click (event) -> event.preventDefault() navigator.id.logout() navigator.id.watch loggedInUser: window.browserIdUser onlogin: (assertion) -> if assertion form = $( "<form action='/auth/browser_id/callback'>" + "<input type='hidden' name='assertion' value='#{assertion}' />" ) $('body').append form form.submit() onlogout: -> window.location = '/logout'
69342
$ -> $('#persona-button, #log-in').click (event) -> event.preventDefault() navigator.id.request { siteName: '<NAME>iinema', siteLogo: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAABlBMVEUAAAD///+l2Z/dAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wHGBMiFVqqanYAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVRo3u3KoQEAAAgDoP3/tBaD0WiATAJwVIsgCIIgCIIgCIIgCIIgCIIgCMKHADAafyL3ebnQxskAAAAASUVORK5CYII=', backgroundColor: '#d95525', privacyPolicy: 'https://asciinema.org/privacy', termsOfService: 'https://asciinema.org/tos' } if window.browserIdUser $('header .logout').click (event) -> event.preventDefault() navigator.id.logout() navigator.id.watch loggedInUser: window.browserIdUser onlogin: (assertion) -> if assertion form = $( "<form action='/auth/browser_id/callback'>" + "<input type='hidden' name='assertion' value='#{assertion}' />" ) $('body').append form form.submit() onlogout: -> window.location = '/logout'
true
$ -> $('#persona-button, #log-in').click (event) -> event.preventDefault() navigator.id.request { siteName: 'PI:NAME:<NAME>END_PIiinema', siteLogo: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAABlBMVEUAAAD///+l2Z/dAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9wHGBMiFVqqanYAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVRo3u3KoQEAAAgDoP3/tBaD0WiATAJwVIsgCIIgCIIgCIIgCIIgCIIgCMKHADAafyL3ebnQxskAAAAASUVORK5CYII=', backgroundColor: '#d95525', privacyPolicy: 'https://asciinema.org/privacy', termsOfService: 'https://asciinema.org/tos' } if window.browserIdUser $('header .logout').click (event) -> event.preventDefault() navigator.id.logout() navigator.id.watch loggedInUser: window.browserIdUser onlogin: (assertion) -> if assertion form = $( "<form action='/auth/browser_id/callback'>" + "<input type='hidden' name='assertion' value='#{assertion}' />" ) $('body').append form form.submit() onlogout: -> window.location = '/logout'
[ { "context": " validate that a value matches a regex\n # @author Daniel Bartholomae\n class RegexValidatorRule extends ValidatorRule\n", "end": 366, "score": 0.9998599886894226, "start": 348, "tag": "NAME", "value": "Daniel Bartholomae" } ]
src/rules/Regex.coffee
dbartholomae/node-validation-codes
0
((modules, factory) -> # Use define if amd compatible define function is defined if typeof define is 'function' && define.amd define modules, factory # Use node require if not else module.exports = factory (require m for m in modules)... )( ['./Rule'], (ValidatorRule) -> # A rule to validate that a value matches a regex # @author Daniel Bartholomae class RegexValidatorRule extends ValidatorRule # Create a new RegexValidatorRule. As default it uses /(?:)/ # # @param [Regex] regex The regular expression to use constructor: (options) -> @options = regex: /(?:)/ super options # Return all possible violation codes for this rule. # @return [Array<String>] An array of all possible violation codes for this rule. getViolationCodes: -> ['RegexMismatch'] # Validate that a String is either undefined or matches this.regex # When the regex is not matched the method returns this.getViolationCodes(), # which can be used when inheriting from this class. # # @param [String] str The string to validate # @return [Array<String>] [] if the string is valid or undefined, ['RegexMismatch'] if it does not match this.regex validate: (str) -> return [] if !str? return @getViolationCodes() unless @options.regex.test str return [] )
54291
((modules, factory) -> # Use define if amd compatible define function is defined if typeof define is 'function' && define.amd define modules, factory # Use node require if not else module.exports = factory (require m for m in modules)... )( ['./Rule'], (ValidatorRule) -> # A rule to validate that a value matches a regex # @author <NAME> class RegexValidatorRule extends ValidatorRule # Create a new RegexValidatorRule. As default it uses /(?:)/ # # @param [Regex] regex The regular expression to use constructor: (options) -> @options = regex: /(?:)/ super options # Return all possible violation codes for this rule. # @return [Array<String>] An array of all possible violation codes for this rule. getViolationCodes: -> ['RegexMismatch'] # Validate that a String is either undefined or matches this.regex # When the regex is not matched the method returns this.getViolationCodes(), # which can be used when inheriting from this class. # # @param [String] str The string to validate # @return [Array<String>] [] if the string is valid or undefined, ['RegexMismatch'] if it does not match this.regex validate: (str) -> return [] if !str? return @getViolationCodes() unless @options.regex.test str return [] )
true
((modules, factory) -> # Use define if amd compatible define function is defined if typeof define is 'function' && define.amd define modules, factory # Use node require if not else module.exports = factory (require m for m in modules)... )( ['./Rule'], (ValidatorRule) -> # A rule to validate that a value matches a regex # @author PI:NAME:<NAME>END_PI class RegexValidatorRule extends ValidatorRule # Create a new RegexValidatorRule. As default it uses /(?:)/ # # @param [Regex] regex The regular expression to use constructor: (options) -> @options = regex: /(?:)/ super options # Return all possible violation codes for this rule. # @return [Array<String>] An array of all possible violation codes for this rule. getViolationCodes: -> ['RegexMismatch'] # Validate that a String is either undefined or matches this.regex # When the regex is not matched the method returns this.getViolationCodes(), # which can be used when inheriting from this class. # # @param [String] str The string to validate # @return [Array<String>] [] if the string is valid or undefined, ['RegexMismatch'] if it does not match this.regex validate: (str) -> return [] if !str? return @getViolationCodes() unless @options.regex.test str return [] )
[ { "context": "return model =\n name: 'Killer-Cube',\n level: 7,\n model: 1\n size: 2,\n zoom: 1,\n ", "end": 35, "score": 0.9991844296455383, "start": 24, "tag": "NAME", "value": "Killer-Cube" } ]
utilities/starblast_bed_wars/broken/starblast_killer_cube.coffee
JavRedstone/Starblast.io-Modding
5
return model = name: 'Killer-Cube', level: 7, model: 1 size: 2, zoom: 1, specs: shield: capacity: [400,400] reload: [15, 15] generator: capacity: [200, 200] reload: [50, 50] ship: mass: 100 speed: [150, 150] rotation: [100, 100] acceleration: [150, 150] bodies: cube: section_segments: [40, 45, 135, 140, 220, 225, 315, 320] offset: x: 0 y: 0 z: 0 position: x: [0, 0, 0, 0] y: [0, 0, 140, 0] z: [0, 0, 0, 0] width: [0, 50, 50, 0] height: [0, 50, 50, 0] propeller: true texture: [63, 63, 17] cannon: section_segments: 5 offset: x: 0 y: 100 z: 50 position: x: [0 ,0 ,0 ,0 ,0] y: [-80, -50, -20, 0, 20] z: [0, 0, 0, 0, 0] width: [0, 5, 5, 10, 0] height: [0, 5, 5, 10, 0] angle: 0 laser: damage: [20, 20] rate: 10 type: 1 speed: [250, 250] number: 1 error: 5 texture: [4,3,17,6]
183429
return model = name: '<NAME>', level: 7, model: 1 size: 2, zoom: 1, specs: shield: capacity: [400,400] reload: [15, 15] generator: capacity: [200, 200] reload: [50, 50] ship: mass: 100 speed: [150, 150] rotation: [100, 100] acceleration: [150, 150] bodies: cube: section_segments: [40, 45, 135, 140, 220, 225, 315, 320] offset: x: 0 y: 0 z: 0 position: x: [0, 0, 0, 0] y: [0, 0, 140, 0] z: [0, 0, 0, 0] width: [0, 50, 50, 0] height: [0, 50, 50, 0] propeller: true texture: [63, 63, 17] cannon: section_segments: 5 offset: x: 0 y: 100 z: 50 position: x: [0 ,0 ,0 ,0 ,0] y: [-80, -50, -20, 0, 20] z: [0, 0, 0, 0, 0] width: [0, 5, 5, 10, 0] height: [0, 5, 5, 10, 0] angle: 0 laser: damage: [20, 20] rate: 10 type: 1 speed: [250, 250] number: 1 error: 5 texture: [4,3,17,6]
true
return model = name: 'PI:NAME:<NAME>END_PI', level: 7, model: 1 size: 2, zoom: 1, specs: shield: capacity: [400,400] reload: [15, 15] generator: capacity: [200, 200] reload: [50, 50] ship: mass: 100 speed: [150, 150] rotation: [100, 100] acceleration: [150, 150] bodies: cube: section_segments: [40, 45, 135, 140, 220, 225, 315, 320] offset: x: 0 y: 0 z: 0 position: x: [0, 0, 0, 0] y: [0, 0, 140, 0] z: [0, 0, 0, 0] width: [0, 50, 50, 0] height: [0, 50, 50, 0] propeller: true texture: [63, 63, 17] cannon: section_segments: 5 offset: x: 0 y: 100 z: 50 position: x: [0 ,0 ,0 ,0 ,0] y: [-80, -50, -20, 0, 20] z: [0, 0, 0, 0, 0] width: [0, 5, 5, 10, 0] height: [0, 5, 5, 10, 0] angle: 0 laser: damage: [20, 20] rate: 10 type: 1 speed: [250, 250] number: 1 error: 5 texture: [4,3,17,6]
[ { "context": "->\n User.login\n id: req.body.id,\n password: req.body.password\n (err, user) ->\n if user\n req.sess", "end": 558, "score": 0.9985567331314087, "start": 541, "tag": "PASSWORD", "value": "req.body.password" } ]
userApp.coffee
madnite1/devnote
11
User = require('./lib/users').User util = require('./lib/util') exports.getUsers = (req, res) -> switch req.query.action when 'login' then login req, res else users req, res exports.login = (req, res) -> res.render 'user/login', title: 'login' return_to: req.header('Referrer') # get userlist users = (req, res) -> userlist = User.findAll() res.render 'admin/userlist', title: 'User List', userlist: userlist # post login exports.postLogin = (req, res) -> User.login id: req.body.id, password: req.body.password (err, user) -> if user req.session.regenerate -> req.session.user = User.findUserById(req.body.id) req.session.success = req.session.user.name + ' logined.' console.log req.session.success if req.body.return_to and req.body.return_to != req.header('Referrer') res.redirect req.body.return_to else res.redirect '/' else req.session.error = err.message res.redirect '/login' # post logout exports.postLogout = (req, res) -> if req.session.user name = req.session.user.name delete req.session.user delete req.session.success console.log name + ' logout.' res.redirect req.header('Referrer') exports.getNew = (req, res) -> res.render 'admin/adduser', title: 'new user' defaultTimezone: util.convertOffsetToTimezone new Date().getTimezoneOffset() exports.postNew = (req, res) -> timezone = util.parseTimezone req.body.timezone timezone = timezone.sign + timezone.hour + timezone.min User.add id: req.body.id, name: req.body.name, email: req.body.email, timezone: timezone, password: req.body.password userInfo = User.findUserById req.body.id res.render 'admin/user', title: '사용자가 등록되었습니다.', content: "사용자 정보", userInfo: userInfo exports.getId = (req, res) -> userInfo = User.findUserById req.params.id res.render 'admin/edituser', title: 'User information', content: "사용자 정보", user: userInfo exports.postId = (req, res) -> targetUser = User.findUserById req.params.id timezone = util.parseTimezone req.body.timezone targetUser.timezone = timezone.sign + timezone.hour + timezone.min isValid = User.changePassword req.body.previousPassword, req.body.newPassword, targetUser targetUser.email = req.body.email if isValid User.save targetUser if isValid userInfo = User.findUserById req.params.id res.render 'admin/user', title: '사용자 정보가 변경되었습니다.', content: "사용자 정보", userInfo: userInfo exports.postDropuser = (req, res) -> userInfo = User.findUserById req.body.id User.remove({id: req.body.id}) if userInfo res.redirect '/wikis/note/users'
173480
User = require('./lib/users').User util = require('./lib/util') exports.getUsers = (req, res) -> switch req.query.action when 'login' then login req, res else users req, res exports.login = (req, res) -> res.render 'user/login', title: 'login' return_to: req.header('Referrer') # get userlist users = (req, res) -> userlist = User.findAll() res.render 'admin/userlist', title: 'User List', userlist: userlist # post login exports.postLogin = (req, res) -> User.login id: req.body.id, password: <PASSWORD> (err, user) -> if user req.session.regenerate -> req.session.user = User.findUserById(req.body.id) req.session.success = req.session.user.name + ' logined.' console.log req.session.success if req.body.return_to and req.body.return_to != req.header('Referrer') res.redirect req.body.return_to else res.redirect '/' else req.session.error = err.message res.redirect '/login' # post logout exports.postLogout = (req, res) -> if req.session.user name = req.session.user.name delete req.session.user delete req.session.success console.log name + ' logout.' res.redirect req.header('Referrer') exports.getNew = (req, res) -> res.render 'admin/adduser', title: 'new user' defaultTimezone: util.convertOffsetToTimezone new Date().getTimezoneOffset() exports.postNew = (req, res) -> timezone = util.parseTimezone req.body.timezone timezone = timezone.sign + timezone.hour + timezone.min User.add id: req.body.id, name: req.body.name, email: req.body.email, timezone: timezone, password: req.body.password userInfo = User.findUserById req.body.id res.render 'admin/user', title: '사용자가 등록되었습니다.', content: "사용자 정보", userInfo: userInfo exports.getId = (req, res) -> userInfo = User.findUserById req.params.id res.render 'admin/edituser', title: 'User information', content: "사용자 정보", user: userInfo exports.postId = (req, res) -> targetUser = User.findUserById req.params.id timezone = util.parseTimezone req.body.timezone targetUser.timezone = timezone.sign + timezone.hour + timezone.min isValid = User.changePassword req.body.previousPassword, req.body.newPassword, targetUser targetUser.email = req.body.email if isValid User.save targetUser if isValid userInfo = User.findUserById req.params.id res.render 'admin/user', title: '사용자 정보가 변경되었습니다.', content: "사용자 정보", userInfo: userInfo exports.postDropuser = (req, res) -> userInfo = User.findUserById req.body.id User.remove({id: req.body.id}) if userInfo res.redirect '/wikis/note/users'
true
User = require('./lib/users').User util = require('./lib/util') exports.getUsers = (req, res) -> switch req.query.action when 'login' then login req, res else users req, res exports.login = (req, res) -> res.render 'user/login', title: 'login' return_to: req.header('Referrer') # get userlist users = (req, res) -> userlist = User.findAll() res.render 'admin/userlist', title: 'User List', userlist: userlist # post login exports.postLogin = (req, res) -> User.login id: req.body.id, password: PI:PASSWORD:<PASSWORD>END_PI (err, user) -> if user req.session.regenerate -> req.session.user = User.findUserById(req.body.id) req.session.success = req.session.user.name + ' logined.' console.log req.session.success if req.body.return_to and req.body.return_to != req.header('Referrer') res.redirect req.body.return_to else res.redirect '/' else req.session.error = err.message res.redirect '/login' # post logout exports.postLogout = (req, res) -> if req.session.user name = req.session.user.name delete req.session.user delete req.session.success console.log name + ' logout.' res.redirect req.header('Referrer') exports.getNew = (req, res) -> res.render 'admin/adduser', title: 'new user' defaultTimezone: util.convertOffsetToTimezone new Date().getTimezoneOffset() exports.postNew = (req, res) -> timezone = util.parseTimezone req.body.timezone timezone = timezone.sign + timezone.hour + timezone.min User.add id: req.body.id, name: req.body.name, email: req.body.email, timezone: timezone, password: req.body.password userInfo = User.findUserById req.body.id res.render 'admin/user', title: '사용자가 등록되었습니다.', content: "사용자 정보", userInfo: userInfo exports.getId = (req, res) -> userInfo = User.findUserById req.params.id res.render 'admin/edituser', title: 'User information', content: "사용자 정보", user: userInfo exports.postId = (req, res) -> targetUser = User.findUserById req.params.id timezone = util.parseTimezone req.body.timezone targetUser.timezone = timezone.sign + timezone.hour + timezone.min isValid = User.changePassword req.body.previousPassword, req.body.newPassword, targetUser targetUser.email = req.body.email if isValid User.save targetUser if isValid userInfo = User.findUserById req.params.id res.render 'admin/user', title: '사용자 정보가 변경되었습니다.', content: "사용자 정보", userInfo: userInfo exports.postDropuser = (req, res) -> userInfo = User.findUserById req.body.id User.remove({id: req.body.id}) if userInfo res.redirect '/wikis/note/users'
[ { "context": " return\n else\n id_key = \"#{domain_id}_#{record}_#{addr}_#{type}\"\n dns_cache.records[id_key] = {}\n ", "end": 9764, "score": 0.9989577531814575, "start": 9724, "tag": "KEY", "value": "\"#{domain_id}_#{record}_#{addr}_#{type}\"" }...
src/scripts/dnsmadeeasy.coffee
lusis/hubot-dnsmadeeasy
1
# Description # Creates a new DNS entry with DNS Made Easy # # Dependencies: # "dme2": "0.0.2" # "underscore": "^1.6.0" # "clark": "0.0.6" # # Configuration: # HUBOT_DME2_API_KEY # HUBOT_DME2_API_SECRET # # Commands: # hubot dns me domains - returns a list of domains in DME account # hubot dns me stats - returns a sparkline of query counts from DME # hubot dns me lookup <record> <domain name> - returns and results for <record> in <domain name> # hubot dns me create <hostname> <domain name> <address> <type> - creates a record in <domain name> # hubot dns me delete <domain name> <record id> - deletes the record with id <record id> from <domain name> # hubot dns me log (max|count) - returns (max|count) entries from the audit log # hubot dns me last <n> <action> - returns the last N results for <action> operations from the audit log # hubot dns me max results <n> - sets the allowed max results returned from audit log queries # # Notes: # <optional notes required for the script> # # Author: # <github username of the original script author> _ = require('underscore') inspect = require('util').inspect crypto = require 'crypto' clark = require('clark') dns_cache = {} save = (robot) -> robot.brain.data.dnsme_cache = dns_cache module.exports = (robot) -> dme_base_url = "https://api.dnsmadeeasy.com/V2.0" default_ttl = 86400 logger = robot.logger logger.debug(inspect robot.brain.data.dnsme_cache) robot.brain.on 'loaded', => dns_cache = robot.brain.data.dnsme_cache or {} dns_cache.domains or= {} dns_cache.records or= {} dns_cache.audit or= [] dns_cache.max_results or= 10 logger.info("Loaded dnsme_cache from brain with #{if dns_cache.domains isnt {} then Object.keys(dns_cache.domains).length else 0} domains and #{Object.keys(dns_cache.records).length} records") auth = api_key: process.env.HUBOT_DME2_API_KEY secret_key: process.env.HUBOT_DME2_API_SECRET robot.respond /dns me domains/i, (msg) -> _checkEnv msg _listDomains msg, (err, data) -> if err msg.send "Got a problem talking to DME: ", inspect err return if JSON.stringify(data) == '{}' msg.send "Looks like you have no domains? That can't be right" return buff = [] for d in data.data dns_cache.domains[d.name] = d buff.push "#{d.name} - #{d.id}" save(robot) msg.send buff.join("\n") robot.respond /dns me stats/i, (msg) -> _checkEnv msg _getUsage msg, (err, data) -> if err msg.send "Problem making API call: ", err if JSON.stringify(data) == '{}' msg.send "Looks like we have no usage data" return logger.debug("Data is: #{inspect data}") stats = [] for d in data stats.push d.total logger.debug("Stats: #{stats.join(' ')}") msg.send(clark(stats)) return robot.respond /dns me delete (.*) (.*)/i, (msg) -> domain = _sanitize msg.match[1] record_id = parseInt(_sanitize(msg.match[2]), 10) logger.info("Delete request for #{record_id} in #{domain} record from #{msg.message.user.name}") logger.debug("Keys #{Object.keys(msg.message.user).join(", ")}") if "roles" of msg.message.user and "dns_admin" in msg.message.user.roles is_authorized = true else is_authorized = false logger.error("User #{msg.message.user.name} is authorized? #{is_authorized}") unless is_authorized msg.send "#{msg.message.user.name} is not authorized for this operation" return _checkEnv msg, (err) -> if err msg.send("Missing env vars for DME") return _findIdForDomain msg, domain, (err, data) -> if err msg.send "Unable to find id for #{domain}. Rebuild cache with 'hubot dns me domains'" return else domain_id = data logger.debug(inspect data) #msg.send("Functionality disabled for now") #return current_record = null current_record_key = null logger.debug("Current cache: #{Object.keys(dns_cache.records).join(", ")}") for k in Object.keys(dns_cache.records) logger.debug("Inspecting #{k}") c = dns_cache.records[k] #logger.debug(inspect c) if 'details' of c and c.details.id == record_id current_record_key = k current_record = c k = '' else logger.debug("No match from #{c.details.name} (#{c.details.id})") unless current_record logger.error("Could not find a cached record for #{record_id}") msg.reply "Unable to find a cached record for #{record_id}. Cannot continue" return logger.info("Found record in cache: #{current_record.details.id} - #{current_record.details.value} - #{current_record.details.type}") _deleteRecord msg, domain_id, record_id, (err, data) -> if JSON.parse(err) msg.send "#{err}" return else if err logger.error(err) msg.reply "Unknown error from DME API. Check hubot logs" return else logger.info("Entry deleted: Adding audit entry") dns_cache.audit = [] unless 'audit' of dns_cache audit = action: 'DELETE' domain: parseInt(domain_id, 10) id: parseInt(current_record.details.id, 10) name: current_record.details.name type: current_record.details.type value: current_record.details.value previous_value: null user: msg.message.user.name timestamp: Math.round((new Date()).getTime() / 1000) logger.info("Audit data: #{JSON.stringify(audit)}") dns_cache.audit.push audit logger.info("Attempting to delete #{current_record_key} from cache") delete dns_cache.records[current_record_key] msg.reply("Deleted entry for #{current_record.details.name}") return robot.respond /dns me max results (\d+)/i, (msg) -> if "roles" of msg.message.user and "dns_admin" in msg.message.user.roles is_authorized = true else is_authorized = false logger.error("User #{msg.message.user.name} is authorized? #{is_authorized}") unless is_authorized msg.send "#{msg.message.user.name} is not authorized for this operation" return dns_cache.max_results = parseInt(msg.match[1], 10) msg.send "Setting max allowable results to #{msg.match[1]}" return robot.respond /dns me log (max|\d+)/i, (msg) -> num_records = msg.match[1] if dns_cache.audit.length == 0 msg.send "No audit entries found =(" return buff = ["\n"] if num_records == 'max' num_records = dns_cache.max_results sorted_data = (_(dns_cache.audit).sortBy (a) -> [a.timestamp]).reverse() for entry in _.take(sorted_data, num_records) buff.push "#{entry.action} | #{entry.domain} | #{entry.id} | #{entry.name} | #{entry.type} | #{entry.value} | #{entry.user} | #{_twd entry.timestamp} ago" msg.reply buff.join("\n") robot.respond /dns me last (\d+) (\w+)/i, (msg) -> num_records = parseInt(msg.match[1], 10) logger.debug("count = #{num_records}") action = msg.match[2].toUpperCase() logger.debug("action = #{action}") if dns_cache.audit.length == 0 msg.send "No audit entries found =(" return buff = ["\n"] if num_records > dns_cache.max_results buff.push "(#{num_records} is larger than max allowed. Only returning last #{dns_cache.max_results})" num_records = dns_cache.max_results sorted_data = (_(dns_cache.audit).sortBy (a) -> [a.timestamp]).reverse() logger.debug(inspect sorted_data) valid_entries = _.where(sorted_data, {action: action}) if valid_entries.length == 0 msg.reply("No entries found") return for entry in _.take(valid_entries, num_records) buff.push "#{entry.action} | #{entry.domain} | #{entry.id} | #{entry.name} | #{entry.type} | #{entry.value} | #{entry.user} | #{_twd entry.timestamp} ago" msg.reply buff.join("\n") robot.respond /dns me create (.*) (.*) (.*) (.*)/i, (msg) -> record = _sanitize msg.match[1] domain = _sanitize msg.match[2] addr = _sanitize msg.match[3] type = _sanitize msg.match[4] logger.info("Create request for #{record} in #{domain} with value #{addr} as #{type} record from #{msg.message.user.name}") logger.debug(inspect msg.message.user) if "roles" of msg.message.user and "dns_admin" in msg.message.user.roles is_authorized = true else is_authorized = false logger.error("User #{msg.message.user.name} is authorized? #{is_authorized}") unless is_authorized msg.send "#{msg.message.user.name} is not authorized for this operation" return _checkEnv msg, (err) -> if err msg.send("Missing env vars for DME") return _findIdForDomain msg, domain, (err, data) -> if err msg.send "Unable to find id for #{domain}. Rebuild cache with 'hubot dns me domains'" return else domain_id = data logger.debug("Got request: #{record} #{domain} #{addr} #{type}") #msg.reply("Functionality disabled for now") #return _addRecord msg, domain_id, record, type, addr, default_ttl, (err, data) -> if JSON.parse(err) msg.send "#{inspect err}" return else if err logger.error(err) msg.reply "Unknown error from DME API. Check hubot logs" return else id_key = "#{domain_id}_#{record}_#{addr}_#{type}" dns_cache.records[id_key] = {} dns_cache.audit = [] unless 'audit' of dns_cache audit = action: 'CREATE' domain: parseInt(domain_id, 10) id: parseInt(data.id, 10) name: data.name type: data.type value: data.value change: null user: msg.message.user.name timestamp: Math.round((new Date()).getTime() / 1000) logger.info("Audit data: #{JSON.stringify(audit)}") dns_cache.audit.push audit msg.reply("Created entry for #{data.name}. ID is #{data.id} and TTL is #{data.ttl}") return robot.respond /dns me lookup (.*) (.*$)/i, (msg) -> _checkEnv msg, (err) -> if err msg.send("Missing env vars for DME") return record = _sanitize(msg.match[1]) domain = _sanitize(msg.match[2]) logger.info("Lookup request for #{record} in #{domain}") _findIdForDomain msg, domain, (err, data) -> if err msg.send "Unable to find id for #{domain}. Rebuild cache with 'hubot dns me domains'" return else domain_id = data _getRecord msg, domain_id, record, (err, data) -> if err msg.send "Got a problem talking to DME: ", inspect err if JSON.stringify(data) == '{}' msg.send "looks like no matches" return matches = [] for r in data.data if r.name == '' logger.debug("Name is missing for record #{r.value} of type #{r.type}. Replacing with domain") r.name = domain logger.debug("Found record: #{r.name}\t#{r.value}\t#{r.id}\t#{r.type}") id_key = "#{domain_id}_#{r.name}_#{r.value}_#{r.type}" dns_cache.records[id_key] = details: r valid_result = "^#{record}.*$" if "#{r.name}".match valid_result matches.push "#{r.name} | #{r.type} | #{r.value} | #{r.id}" save(robot) if matches.length > 0 msg.send matches.join("\n") return else msg.send "No matches found =(" return _checkEnv = (msg, cb) -> unless auth.api_key or auth.api_secret return cb(true) _findIdForDomain = (msg, domain, cb) -> logger.debug("Looking up id for domain #{domain}") if 'domains' of dns_cache and domain of dns_cache.domains and 'id' of dns_cache.domains[domain] logger.debug(Object.keys(dns_cache.domains).join(",")) logger.debug("Found domain id for #{domain}") return cb(null, dns_cache.domains[domain].id) else logger.debug(Object.keys(dns_cache.domains).join(",")) logger.debug("Unable to find domain id for #{domain}") return cb("Unable to find domain id") _getUsage = (msg, cb) -> return _dmeGet msg, '/usageApi/queriesApi/', cb _listDomains = (msg, cb) -> return _dmeGet msg, '/dns/managed/', cb _addRecord = (msg, id, name, type, addr, ttl, cb) -> data = name: name type: type value: addr ttl: ttl logger.debug(JSON.stringify(data)) return _dmePost msg, "/dns/managed/#{id}/records", data, cb _deleteRecord = (msg, domain_id, record_id, cb) -> logger.debug("Got to delete request for record #{record_id} for domain #{domain_id}") return _dmeDelete msg, "/dns/managed/#{domain_id}/records/#{record_id}/", cb _getRecord = (msg, id, record, cb) -> all_records = _dmeGet msg, "/dns/managed/#{id}/records", cb logger.debug("Got back #{all_records.data.length} records") return all_records _dmeGet = (msg, resource, cb) -> logger.debug("Got a request for: ",resource) logger.debug("Req url is: ",dme_base_url + resource) logger.debug("Callback is: ", inspect cb) req = msg.http(dme_base_url + resource) logger.debug("Req: ", inspect req) h = _dmeAuth() logger.debug("Headers: ", inspect h) req.headers(h) req.get() (err, res, body) -> if err return cb err json_body = null switch res.statusCode when 200 json_body = JSON.parse(body) return cb(null, json_body) else logger.error("Error from DME API: ", body) return cb(body) _dmePost = (msg, resource, data, cb) -> logger.debug("Got a request for: ", resource) logger.debug("Req url is ",dme_base_url + resource) logger.debug("Data is ", inspect data) req = msg.http(dme_base_url + resource) h = _dmeAuth() req.headers(h) req.post(JSON.stringify(data)) (err, res, body) -> if err return cb err['error'] json_body = null switch res.statusCode when 201 json_body = JSON.parse(body) return cb(null, json_body) else logger.error("Error from DME API: ", body) return cb(body) _dmeDelete = (msg, resource, cb) -> logger.debug("Got a request for: ", resource) logger.debug("Req url is ",dme_base_url + resource) req = msg.http(dme_base_url + resource) h = _dmeAuth() req.headers(h) req.delete() (err, res, body) -> if err return cb err['error'] switch res.statusCode when 200 return cb(null, true) else logger.error("Error from DME API: ", body) return cb(body, false) _dmeAuth = -> logger.debug("Request for auth headers") date = new Date().toGMTString() logger.debug("Date string is: ", date) headers = {} headers['x-dnsme-apiKey'] = auth.api_key headers['x-dnsme-requestDate'] = date headers['x-dnsme-hmac'] = crypto.createHmac('sha1', auth.secret_key).update(date).digest('hex') headers['Content-Type'] = 'application/json' logger.debug("Computed headers: ", inspect headers) return headers _sanitize = (string) -> if string.match(/^http/) logger.info("Found html in text. Cleaning up") return string.replace /.*?:\/\//g, "" else return string _twd = (time) -> date = new Date(time * 1e3) diff = ((+new Date - date.getTime()) / 1e3) ddiff = Math.floor(diff / 86400) d = date.getDate() m = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" ")[date.getMonth()] y = date.getFullYear().toString().slice(2) return if isNaN(ddiff) or ddiff < 0 ddiff is 0 and (diff < 60 and Math.floor(diff) + "s" or diff < 3600 and Math.floor(diff / 60) + "m" or diff < 86400 and Math.floor(diff / 3600) + "h") or ddiff < 365 and d + " " + m or ddiff >= 365 and d + " " + m + " " + y
4718
# Description # Creates a new DNS entry with DNS Made Easy # # Dependencies: # "dme2": "0.0.2" # "underscore": "^1.6.0" # "clark": "0.0.6" # # Configuration: # HUBOT_DME2_API_KEY # HUBOT_DME2_API_SECRET # # Commands: # hubot dns me domains - returns a list of domains in DME account # hubot dns me stats - returns a sparkline of query counts from DME # hubot dns me lookup <record> <domain name> - returns and results for <record> in <domain name> # hubot dns me create <hostname> <domain name> <address> <type> - creates a record in <domain name> # hubot dns me delete <domain name> <record id> - deletes the record with id <record id> from <domain name> # hubot dns me log (max|count) - returns (max|count) entries from the audit log # hubot dns me last <n> <action> - returns the last N results for <action> operations from the audit log # hubot dns me max results <n> - sets the allowed max results returned from audit log queries # # Notes: # <optional notes required for the script> # # Author: # <github username of the original script author> _ = require('underscore') inspect = require('util').inspect crypto = require 'crypto' clark = require('clark') dns_cache = {} save = (robot) -> robot.brain.data.dnsme_cache = dns_cache module.exports = (robot) -> dme_base_url = "https://api.dnsmadeeasy.com/V2.0" default_ttl = 86400 logger = robot.logger logger.debug(inspect robot.brain.data.dnsme_cache) robot.brain.on 'loaded', => dns_cache = robot.brain.data.dnsme_cache or {} dns_cache.domains or= {} dns_cache.records or= {} dns_cache.audit or= [] dns_cache.max_results or= 10 logger.info("Loaded dnsme_cache from brain with #{if dns_cache.domains isnt {} then Object.keys(dns_cache.domains).length else 0} domains and #{Object.keys(dns_cache.records).length} records") auth = api_key: process.env.HUBOT_DME2_API_KEY secret_key: process.env.HUBOT_DME2_API_SECRET robot.respond /dns me domains/i, (msg) -> _checkEnv msg _listDomains msg, (err, data) -> if err msg.send "Got a problem talking to DME: ", inspect err return if JSON.stringify(data) == '{}' msg.send "Looks like you have no domains? That can't be right" return buff = [] for d in data.data dns_cache.domains[d.name] = d buff.push "#{d.name} - #{d.id}" save(robot) msg.send buff.join("\n") robot.respond /dns me stats/i, (msg) -> _checkEnv msg _getUsage msg, (err, data) -> if err msg.send "Problem making API call: ", err if JSON.stringify(data) == '{}' msg.send "Looks like we have no usage data" return logger.debug("Data is: #{inspect data}") stats = [] for d in data stats.push d.total logger.debug("Stats: #{stats.join(' ')}") msg.send(clark(stats)) return robot.respond /dns me delete (.*) (.*)/i, (msg) -> domain = _sanitize msg.match[1] record_id = parseInt(_sanitize(msg.match[2]), 10) logger.info("Delete request for #{record_id} in #{domain} record from #{msg.message.user.name}") logger.debug("Keys #{Object.keys(msg.message.user).join(", ")}") if "roles" of msg.message.user and "dns_admin" in msg.message.user.roles is_authorized = true else is_authorized = false logger.error("User #{msg.message.user.name} is authorized? #{is_authorized}") unless is_authorized msg.send "#{msg.message.user.name} is not authorized for this operation" return _checkEnv msg, (err) -> if err msg.send("Missing env vars for DME") return _findIdForDomain msg, domain, (err, data) -> if err msg.send "Unable to find id for #{domain}. Rebuild cache with 'hubot dns me domains'" return else domain_id = data logger.debug(inspect data) #msg.send("Functionality disabled for now") #return current_record = null current_record_key = null logger.debug("Current cache: #{Object.keys(dns_cache.records).join(", ")}") for k in Object.keys(dns_cache.records) logger.debug("Inspecting #{k}") c = dns_cache.records[k] #logger.debug(inspect c) if 'details' of c and c.details.id == record_id current_record_key = k current_record = c k = '' else logger.debug("No match from #{c.details.name} (#{c.details.id})") unless current_record logger.error("Could not find a cached record for #{record_id}") msg.reply "Unable to find a cached record for #{record_id}. Cannot continue" return logger.info("Found record in cache: #{current_record.details.id} - #{current_record.details.value} - #{current_record.details.type}") _deleteRecord msg, domain_id, record_id, (err, data) -> if JSON.parse(err) msg.send "#{err}" return else if err logger.error(err) msg.reply "Unknown error from DME API. Check hubot logs" return else logger.info("Entry deleted: Adding audit entry") dns_cache.audit = [] unless 'audit' of dns_cache audit = action: 'DELETE' domain: parseInt(domain_id, 10) id: parseInt(current_record.details.id, 10) name: current_record.details.name type: current_record.details.type value: current_record.details.value previous_value: null user: msg.message.user.name timestamp: Math.round((new Date()).getTime() / 1000) logger.info("Audit data: #{JSON.stringify(audit)}") dns_cache.audit.push audit logger.info("Attempting to delete #{current_record_key} from cache") delete dns_cache.records[current_record_key] msg.reply("Deleted entry for #{current_record.details.name}") return robot.respond /dns me max results (\d+)/i, (msg) -> if "roles" of msg.message.user and "dns_admin" in msg.message.user.roles is_authorized = true else is_authorized = false logger.error("User #{msg.message.user.name} is authorized? #{is_authorized}") unless is_authorized msg.send "#{msg.message.user.name} is not authorized for this operation" return dns_cache.max_results = parseInt(msg.match[1], 10) msg.send "Setting max allowable results to #{msg.match[1]}" return robot.respond /dns me log (max|\d+)/i, (msg) -> num_records = msg.match[1] if dns_cache.audit.length == 0 msg.send "No audit entries found =(" return buff = ["\n"] if num_records == 'max' num_records = dns_cache.max_results sorted_data = (_(dns_cache.audit).sortBy (a) -> [a.timestamp]).reverse() for entry in _.take(sorted_data, num_records) buff.push "#{entry.action} | #{entry.domain} | #{entry.id} | #{entry.name} | #{entry.type} | #{entry.value} | #{entry.user} | #{_twd entry.timestamp} ago" msg.reply buff.join("\n") robot.respond /dns me last (\d+) (\w+)/i, (msg) -> num_records = parseInt(msg.match[1], 10) logger.debug("count = #{num_records}") action = msg.match[2].toUpperCase() logger.debug("action = #{action}") if dns_cache.audit.length == 0 msg.send "No audit entries found =(" return buff = ["\n"] if num_records > dns_cache.max_results buff.push "(#{num_records} is larger than max allowed. Only returning last #{dns_cache.max_results})" num_records = dns_cache.max_results sorted_data = (_(dns_cache.audit).sortBy (a) -> [a.timestamp]).reverse() logger.debug(inspect sorted_data) valid_entries = _.where(sorted_data, {action: action}) if valid_entries.length == 0 msg.reply("No entries found") return for entry in _.take(valid_entries, num_records) buff.push "#{entry.action} | #{entry.domain} | #{entry.id} | #{entry.name} | #{entry.type} | #{entry.value} | #{entry.user} | #{_twd entry.timestamp} ago" msg.reply buff.join("\n") robot.respond /dns me create (.*) (.*) (.*) (.*)/i, (msg) -> record = _sanitize msg.match[1] domain = _sanitize msg.match[2] addr = _sanitize msg.match[3] type = _sanitize msg.match[4] logger.info("Create request for #{record} in #{domain} with value #{addr} as #{type} record from #{msg.message.user.name}") logger.debug(inspect msg.message.user) if "roles" of msg.message.user and "dns_admin" in msg.message.user.roles is_authorized = true else is_authorized = false logger.error("User #{msg.message.user.name} is authorized? #{is_authorized}") unless is_authorized msg.send "#{msg.message.user.name} is not authorized for this operation" return _checkEnv msg, (err) -> if err msg.send("Missing env vars for DME") return _findIdForDomain msg, domain, (err, data) -> if err msg.send "Unable to find id for #{domain}. Rebuild cache with 'hubot dns me domains'" return else domain_id = data logger.debug("Got request: #{record} #{domain} #{addr} #{type}") #msg.reply("Functionality disabled for now") #return _addRecord msg, domain_id, record, type, addr, default_ttl, (err, data) -> if JSON.parse(err) msg.send "#{inspect err}" return else if err logger.error(err) msg.reply "Unknown error from DME API. Check hubot logs" return else id_key = <KEY> dns_cache.records[id_key] = {} dns_cache.audit = [] unless 'audit' of dns_cache audit = action: 'CREATE' domain: parseInt(domain_id, 10) id: parseInt(data.id, 10) name: data.name type: data.type value: data.value change: null user: msg.message.user.name timestamp: Math.round((new Date()).getTime() / 1000) logger.info("Audit data: #{JSON.stringify(audit)}") dns_cache.audit.push audit msg.reply("Created entry for #{data.name}. ID is #{data.id} and TTL is #{data.ttl}") return robot.respond /dns me lookup (.*) (.*$)/i, (msg) -> _checkEnv msg, (err) -> if err msg.send("Missing env vars for DME") return record = _sanitize(msg.match[1]) domain = _sanitize(msg.match[2]) logger.info("Lookup request for #{record} in #{domain}") _findIdForDomain msg, domain, (err, data) -> if err msg.send "Unable to find id for #{domain}. Rebuild cache with 'hubot dns me domains'" return else domain_id = data _getRecord msg, domain_id, record, (err, data) -> if err msg.send "Got a problem talking to DME: ", inspect err if JSON.stringify(data) == '{}' msg.send "looks like no matches" return matches = [] for r in data.data if r.name == '' logger.debug("Name is missing for record #{r.value} of type #{r.type}. Replacing with domain") r.name = domain logger.debug("Found record: #{r.name}\t#{r.value}\t#{r.id}\t#{r.type}") id_key = <KEY> dns_cache.records[id_key] = details: r valid_result = "^#{record}.*$" if "#{r.name}".match valid_result matches.push "#{r.name} | #{r.type} | #{r.value} | #{r.id}" save(robot) if matches.length > 0 msg.send matches.join("\n") return else msg.send "No matches found =(" return _checkEnv = (msg, cb) -> unless auth.api_key or auth.api_secret return cb(true) _findIdForDomain = (msg, domain, cb) -> logger.debug("Looking up id for domain #{domain}") if 'domains' of dns_cache and domain of dns_cache.domains and 'id' of dns_cache.domains[domain] logger.debug(Object.keys(dns_cache.domains).join(",")) logger.debug("Found domain id for #{domain}") return cb(null, dns_cache.domains[domain].id) else logger.debug(Object.keys(dns_cache.domains).join(",")) logger.debug("Unable to find domain id for #{domain}") return cb("Unable to find domain id") _getUsage = (msg, cb) -> return _dmeGet msg, '/usageApi/queriesApi/', cb _listDomains = (msg, cb) -> return _dmeGet msg, '/dns/managed/', cb _addRecord = (msg, id, name, type, addr, ttl, cb) -> data = name: name type: type value: addr ttl: ttl logger.debug(JSON.stringify(data)) return _dmePost msg, "/dns/managed/#{id}/records", data, cb _deleteRecord = (msg, domain_id, record_id, cb) -> logger.debug("Got to delete request for record #{record_id} for domain #{domain_id}") return _dmeDelete msg, "/dns/managed/#{domain_id}/records/#{record_id}/", cb _getRecord = (msg, id, record, cb) -> all_records = _dmeGet msg, "/dns/managed/#{id}/records", cb logger.debug("Got back #{all_records.data.length} records") return all_records _dmeGet = (msg, resource, cb) -> logger.debug("Got a request for: ",resource) logger.debug("Req url is: ",dme_base_url + resource) logger.debug("Callback is: ", inspect cb) req = msg.http(dme_base_url + resource) logger.debug("Req: ", inspect req) h = _dmeAuth() logger.debug("Headers: ", inspect h) req.headers(h) req.get() (err, res, body) -> if err return cb err json_body = null switch res.statusCode when 200 json_body = JSON.parse(body) return cb(null, json_body) else logger.error("Error from DME API: ", body) return cb(body) _dmePost = (msg, resource, data, cb) -> logger.debug("Got a request for: ", resource) logger.debug("Req url is ",dme_base_url + resource) logger.debug("Data is ", inspect data) req = msg.http(dme_base_url + resource) h = _dmeAuth() req.headers(h) req.post(JSON.stringify(data)) (err, res, body) -> if err return cb err['error'] json_body = null switch res.statusCode when 201 json_body = JSON.parse(body) return cb(null, json_body) else logger.error("Error from DME API: ", body) return cb(body) _dmeDelete = (msg, resource, cb) -> logger.debug("Got a request for: ", resource) logger.debug("Req url is ",dme_base_url + resource) req = msg.http(dme_base_url + resource) h = _dmeAuth() req.headers(h) req.delete() (err, res, body) -> if err return cb err['error'] switch res.statusCode when 200 return cb(null, true) else logger.error("Error from DME API: ", body) return cb(body, false) _dmeAuth = -> logger.debug("Request for auth headers") date = new Date().toGMTString() logger.debug("Date string is: ", date) headers = {} headers['x-dnsme-apiKey'] = auth.api_key headers['x-dnsme-requestDate'] = date headers['x-dnsme-hmac'] = crypto.createHmac('sha1', auth.secret_key).update(date).digest('hex') headers['Content-Type'] = 'application/json' logger.debug("Computed headers: ", inspect headers) return headers _sanitize = (string) -> if string.match(/^http/) logger.info("Found html in text. Cleaning up") return string.replace /.*?:\/\//g, "" else return string _twd = (time) -> date = new Date(time * 1e3) diff = ((+new Date - date.getTime()) / 1e3) ddiff = Math.floor(diff / 86400) d = date.getDate() m = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" ")[date.getMonth()] y = date.getFullYear().toString().slice(2) return if isNaN(ddiff) or ddiff < 0 ddiff is 0 and (diff < 60 and Math.floor(diff) + "s" or diff < 3600 and Math.floor(diff / 60) + "m" or diff < 86400 and Math.floor(diff / 3600) + "h") or ddiff < 365 and d + " " + m or ddiff >= 365 and d + " " + m + " " + y
true
# Description # Creates a new DNS entry with DNS Made Easy # # Dependencies: # "dme2": "0.0.2" # "underscore": "^1.6.0" # "clark": "0.0.6" # # Configuration: # HUBOT_DME2_API_KEY # HUBOT_DME2_API_SECRET # # Commands: # hubot dns me domains - returns a list of domains in DME account # hubot dns me stats - returns a sparkline of query counts from DME # hubot dns me lookup <record> <domain name> - returns and results for <record> in <domain name> # hubot dns me create <hostname> <domain name> <address> <type> - creates a record in <domain name> # hubot dns me delete <domain name> <record id> - deletes the record with id <record id> from <domain name> # hubot dns me log (max|count) - returns (max|count) entries from the audit log # hubot dns me last <n> <action> - returns the last N results for <action> operations from the audit log # hubot dns me max results <n> - sets the allowed max results returned from audit log queries # # Notes: # <optional notes required for the script> # # Author: # <github username of the original script author> _ = require('underscore') inspect = require('util').inspect crypto = require 'crypto' clark = require('clark') dns_cache = {} save = (robot) -> robot.brain.data.dnsme_cache = dns_cache module.exports = (robot) -> dme_base_url = "https://api.dnsmadeeasy.com/V2.0" default_ttl = 86400 logger = robot.logger logger.debug(inspect robot.brain.data.dnsme_cache) robot.brain.on 'loaded', => dns_cache = robot.brain.data.dnsme_cache or {} dns_cache.domains or= {} dns_cache.records or= {} dns_cache.audit or= [] dns_cache.max_results or= 10 logger.info("Loaded dnsme_cache from brain with #{if dns_cache.domains isnt {} then Object.keys(dns_cache.domains).length else 0} domains and #{Object.keys(dns_cache.records).length} records") auth = api_key: process.env.HUBOT_DME2_API_KEY secret_key: process.env.HUBOT_DME2_API_SECRET robot.respond /dns me domains/i, (msg) -> _checkEnv msg _listDomains msg, (err, data) -> if err msg.send "Got a problem talking to DME: ", inspect err return if JSON.stringify(data) == '{}' msg.send "Looks like you have no domains? That can't be right" return buff = [] for d in data.data dns_cache.domains[d.name] = d buff.push "#{d.name} - #{d.id}" save(robot) msg.send buff.join("\n") robot.respond /dns me stats/i, (msg) -> _checkEnv msg _getUsage msg, (err, data) -> if err msg.send "Problem making API call: ", err if JSON.stringify(data) == '{}' msg.send "Looks like we have no usage data" return logger.debug("Data is: #{inspect data}") stats = [] for d in data stats.push d.total logger.debug("Stats: #{stats.join(' ')}") msg.send(clark(stats)) return robot.respond /dns me delete (.*) (.*)/i, (msg) -> domain = _sanitize msg.match[1] record_id = parseInt(_sanitize(msg.match[2]), 10) logger.info("Delete request for #{record_id} in #{domain} record from #{msg.message.user.name}") logger.debug("Keys #{Object.keys(msg.message.user).join(", ")}") if "roles" of msg.message.user and "dns_admin" in msg.message.user.roles is_authorized = true else is_authorized = false logger.error("User #{msg.message.user.name} is authorized? #{is_authorized}") unless is_authorized msg.send "#{msg.message.user.name} is not authorized for this operation" return _checkEnv msg, (err) -> if err msg.send("Missing env vars for DME") return _findIdForDomain msg, domain, (err, data) -> if err msg.send "Unable to find id for #{domain}. Rebuild cache with 'hubot dns me domains'" return else domain_id = data logger.debug(inspect data) #msg.send("Functionality disabled for now") #return current_record = null current_record_key = null logger.debug("Current cache: #{Object.keys(dns_cache.records).join(", ")}") for k in Object.keys(dns_cache.records) logger.debug("Inspecting #{k}") c = dns_cache.records[k] #logger.debug(inspect c) if 'details' of c and c.details.id == record_id current_record_key = k current_record = c k = '' else logger.debug("No match from #{c.details.name} (#{c.details.id})") unless current_record logger.error("Could not find a cached record for #{record_id}") msg.reply "Unable to find a cached record for #{record_id}. Cannot continue" return logger.info("Found record in cache: #{current_record.details.id} - #{current_record.details.value} - #{current_record.details.type}") _deleteRecord msg, domain_id, record_id, (err, data) -> if JSON.parse(err) msg.send "#{err}" return else if err logger.error(err) msg.reply "Unknown error from DME API. Check hubot logs" return else logger.info("Entry deleted: Adding audit entry") dns_cache.audit = [] unless 'audit' of dns_cache audit = action: 'DELETE' domain: parseInt(domain_id, 10) id: parseInt(current_record.details.id, 10) name: current_record.details.name type: current_record.details.type value: current_record.details.value previous_value: null user: msg.message.user.name timestamp: Math.round((new Date()).getTime() / 1000) logger.info("Audit data: #{JSON.stringify(audit)}") dns_cache.audit.push audit logger.info("Attempting to delete #{current_record_key} from cache") delete dns_cache.records[current_record_key] msg.reply("Deleted entry for #{current_record.details.name}") return robot.respond /dns me max results (\d+)/i, (msg) -> if "roles" of msg.message.user and "dns_admin" in msg.message.user.roles is_authorized = true else is_authorized = false logger.error("User #{msg.message.user.name} is authorized? #{is_authorized}") unless is_authorized msg.send "#{msg.message.user.name} is not authorized for this operation" return dns_cache.max_results = parseInt(msg.match[1], 10) msg.send "Setting max allowable results to #{msg.match[1]}" return robot.respond /dns me log (max|\d+)/i, (msg) -> num_records = msg.match[1] if dns_cache.audit.length == 0 msg.send "No audit entries found =(" return buff = ["\n"] if num_records == 'max' num_records = dns_cache.max_results sorted_data = (_(dns_cache.audit).sortBy (a) -> [a.timestamp]).reverse() for entry in _.take(sorted_data, num_records) buff.push "#{entry.action} | #{entry.domain} | #{entry.id} | #{entry.name} | #{entry.type} | #{entry.value} | #{entry.user} | #{_twd entry.timestamp} ago" msg.reply buff.join("\n") robot.respond /dns me last (\d+) (\w+)/i, (msg) -> num_records = parseInt(msg.match[1], 10) logger.debug("count = #{num_records}") action = msg.match[2].toUpperCase() logger.debug("action = #{action}") if dns_cache.audit.length == 0 msg.send "No audit entries found =(" return buff = ["\n"] if num_records > dns_cache.max_results buff.push "(#{num_records} is larger than max allowed. Only returning last #{dns_cache.max_results})" num_records = dns_cache.max_results sorted_data = (_(dns_cache.audit).sortBy (a) -> [a.timestamp]).reverse() logger.debug(inspect sorted_data) valid_entries = _.where(sorted_data, {action: action}) if valid_entries.length == 0 msg.reply("No entries found") return for entry in _.take(valid_entries, num_records) buff.push "#{entry.action} | #{entry.domain} | #{entry.id} | #{entry.name} | #{entry.type} | #{entry.value} | #{entry.user} | #{_twd entry.timestamp} ago" msg.reply buff.join("\n") robot.respond /dns me create (.*) (.*) (.*) (.*)/i, (msg) -> record = _sanitize msg.match[1] domain = _sanitize msg.match[2] addr = _sanitize msg.match[3] type = _sanitize msg.match[4] logger.info("Create request for #{record} in #{domain} with value #{addr} as #{type} record from #{msg.message.user.name}") logger.debug(inspect msg.message.user) if "roles" of msg.message.user and "dns_admin" in msg.message.user.roles is_authorized = true else is_authorized = false logger.error("User #{msg.message.user.name} is authorized? #{is_authorized}") unless is_authorized msg.send "#{msg.message.user.name} is not authorized for this operation" return _checkEnv msg, (err) -> if err msg.send("Missing env vars for DME") return _findIdForDomain msg, domain, (err, data) -> if err msg.send "Unable to find id for #{domain}. Rebuild cache with 'hubot dns me domains'" return else domain_id = data logger.debug("Got request: #{record} #{domain} #{addr} #{type}") #msg.reply("Functionality disabled for now") #return _addRecord msg, domain_id, record, type, addr, default_ttl, (err, data) -> if JSON.parse(err) msg.send "#{inspect err}" return else if err logger.error(err) msg.reply "Unknown error from DME API. Check hubot logs" return else id_key = PI:KEY:<KEY>END_PI dns_cache.records[id_key] = {} dns_cache.audit = [] unless 'audit' of dns_cache audit = action: 'CREATE' domain: parseInt(domain_id, 10) id: parseInt(data.id, 10) name: data.name type: data.type value: data.value change: null user: msg.message.user.name timestamp: Math.round((new Date()).getTime() / 1000) logger.info("Audit data: #{JSON.stringify(audit)}") dns_cache.audit.push audit msg.reply("Created entry for #{data.name}. ID is #{data.id} and TTL is #{data.ttl}") return robot.respond /dns me lookup (.*) (.*$)/i, (msg) -> _checkEnv msg, (err) -> if err msg.send("Missing env vars for DME") return record = _sanitize(msg.match[1]) domain = _sanitize(msg.match[2]) logger.info("Lookup request for #{record} in #{domain}") _findIdForDomain msg, domain, (err, data) -> if err msg.send "Unable to find id for #{domain}. Rebuild cache with 'hubot dns me domains'" return else domain_id = data _getRecord msg, domain_id, record, (err, data) -> if err msg.send "Got a problem talking to DME: ", inspect err if JSON.stringify(data) == '{}' msg.send "looks like no matches" return matches = [] for r in data.data if r.name == '' logger.debug("Name is missing for record #{r.value} of type #{r.type}. Replacing with domain") r.name = domain logger.debug("Found record: #{r.name}\t#{r.value}\t#{r.id}\t#{r.type}") id_key = PI:KEY:<KEY>END_PI dns_cache.records[id_key] = details: r valid_result = "^#{record}.*$" if "#{r.name}".match valid_result matches.push "#{r.name} | #{r.type} | #{r.value} | #{r.id}" save(robot) if matches.length > 0 msg.send matches.join("\n") return else msg.send "No matches found =(" return _checkEnv = (msg, cb) -> unless auth.api_key or auth.api_secret return cb(true) _findIdForDomain = (msg, domain, cb) -> logger.debug("Looking up id for domain #{domain}") if 'domains' of dns_cache and domain of dns_cache.domains and 'id' of dns_cache.domains[domain] logger.debug(Object.keys(dns_cache.domains).join(",")) logger.debug("Found domain id for #{domain}") return cb(null, dns_cache.domains[domain].id) else logger.debug(Object.keys(dns_cache.domains).join(",")) logger.debug("Unable to find domain id for #{domain}") return cb("Unable to find domain id") _getUsage = (msg, cb) -> return _dmeGet msg, '/usageApi/queriesApi/', cb _listDomains = (msg, cb) -> return _dmeGet msg, '/dns/managed/', cb _addRecord = (msg, id, name, type, addr, ttl, cb) -> data = name: name type: type value: addr ttl: ttl logger.debug(JSON.stringify(data)) return _dmePost msg, "/dns/managed/#{id}/records", data, cb _deleteRecord = (msg, domain_id, record_id, cb) -> logger.debug("Got to delete request for record #{record_id} for domain #{domain_id}") return _dmeDelete msg, "/dns/managed/#{domain_id}/records/#{record_id}/", cb _getRecord = (msg, id, record, cb) -> all_records = _dmeGet msg, "/dns/managed/#{id}/records", cb logger.debug("Got back #{all_records.data.length} records") return all_records _dmeGet = (msg, resource, cb) -> logger.debug("Got a request for: ",resource) logger.debug("Req url is: ",dme_base_url + resource) logger.debug("Callback is: ", inspect cb) req = msg.http(dme_base_url + resource) logger.debug("Req: ", inspect req) h = _dmeAuth() logger.debug("Headers: ", inspect h) req.headers(h) req.get() (err, res, body) -> if err return cb err json_body = null switch res.statusCode when 200 json_body = JSON.parse(body) return cb(null, json_body) else logger.error("Error from DME API: ", body) return cb(body) _dmePost = (msg, resource, data, cb) -> logger.debug("Got a request for: ", resource) logger.debug("Req url is ",dme_base_url + resource) logger.debug("Data is ", inspect data) req = msg.http(dme_base_url + resource) h = _dmeAuth() req.headers(h) req.post(JSON.stringify(data)) (err, res, body) -> if err return cb err['error'] json_body = null switch res.statusCode when 201 json_body = JSON.parse(body) return cb(null, json_body) else logger.error("Error from DME API: ", body) return cb(body) _dmeDelete = (msg, resource, cb) -> logger.debug("Got a request for: ", resource) logger.debug("Req url is ",dme_base_url + resource) req = msg.http(dme_base_url + resource) h = _dmeAuth() req.headers(h) req.delete() (err, res, body) -> if err return cb err['error'] switch res.statusCode when 200 return cb(null, true) else logger.error("Error from DME API: ", body) return cb(body, false) _dmeAuth = -> logger.debug("Request for auth headers") date = new Date().toGMTString() logger.debug("Date string is: ", date) headers = {} headers['x-dnsme-apiKey'] = auth.api_key headers['x-dnsme-requestDate'] = date headers['x-dnsme-hmac'] = crypto.createHmac('sha1', auth.secret_key).update(date).digest('hex') headers['Content-Type'] = 'application/json' logger.debug("Computed headers: ", inspect headers) return headers _sanitize = (string) -> if string.match(/^http/) logger.info("Found html in text. Cleaning up") return string.replace /.*?:\/\//g, "" else return string _twd = (time) -> date = new Date(time * 1e3) diff = ((+new Date - date.getTime()) / 1e3) ddiff = Math.floor(diff / 86400) d = date.getDate() m = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" ")[date.getMonth()] y = date.getFullYear().toString().slice(2) return if isNaN(ddiff) or ddiff < 0 ddiff is 0 and (diff < 60 and Math.floor(diff) + "s" or diff < 3600 and Math.floor(diff / 60) + "m" or diff < 86400 and Math.floor(diff / 3600) + "h") or ddiff < 365 and d + " " + m or ddiff >= 365 and d + " " + m + " " + y
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999138116836548, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/_classes/gallery.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @Gallery constructor: -> @container = document.getElementsByClassName('pswp') $(document).on 'click', '.js-gallery', @initiateOpen $(document).on 'click', '.js-gallery-thumbnail', @switchPreview $(document).on 'turbolinks:before-cache', -> $('.js-gallery--container').remove() initiateOpen: (e) => $target = $(e.currentTarget) return if $target.parents('a').length e.preventDefault() index = parseInt $target.attr('data-index'), 10 galleryId = $target.attr('data-gallery-id') @open {galleryId, index} open: ({galleryId, index}) => container = @container[0].cloneNode(true) container.classList.add 'js-gallery--container' document.body.appendChild container pswp = new PhotoSwipe container, PhotoSwipeUI_Default @data galleryId showHideOpacity: true getThumbBoundsFn: @thumbBoundsFn(galleryId) index: index history: false timeToIdle: null if _.startsWith(galleryId, 'contest-') new _exported.GalleryContest(container, pswp) pswp.init() $(document).one 'gallery:close', -> # ignore any failures (in case already destroyed) try pswp.close() data: (galleryId) -> for el in document.querySelectorAll(".js-gallery[data-gallery-id='#{galleryId}']") src = el.getAttribute('data-src') ? el.getAttribute('href') element: el msrc: src src: src w: parseInt el.getAttribute('data-width'), 10 h: parseInt el.getAttribute('data-height'), 10 thumbBoundsFn: (galleryId) => (i) => $thumb = $(".js-gallery[data-gallery-id='#{galleryId}'][data-index='#{i}']") thumbPos = $thumb.offset() thumbDim = [ $thumb.width() $thumb.height() ] center = [ thumbPos.left + thumbDim[0] / 2 thumbPos.top + thumbDim[1] / 2 ] imageDim = [ parseInt $thumb.attr('data-width'), 10 parseInt $thumb.attr('data-height'), 10 ] scale = Math.max thumbDim[0] / imageDim[0], thumbDim[1] / imageDim[1] scaledImageDim = imageDim.map (s) -> s * scale x: center[0] - scaledImageDim[0] / 2 y: center[1] - scaledImageDim[1] / 2 w: scaledImageDim[0] switchPreview: (e) => e.preventDefault() $link = $(e.currentTarget) {galleryId, index} = $link[0].dataset $previews = $(".js-gallery[data-gallery-id='#{galleryId}']") $links = $(".js-gallery-thumbnail[data-gallery-id='#{galleryId}']") for pair in _.zip($links, $previews) if index == pair[0].dataset.index pair[0].classList.add 'js-gallery-thumbnail--active' Fade.in pair[1] else pair[0].classList.remove 'js-gallery-thumbnail--active' Fade.out pair[1]
24891
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @Gallery constructor: -> @container = document.getElementsByClassName('pswp') $(document).on 'click', '.js-gallery', @initiateOpen $(document).on 'click', '.js-gallery-thumbnail', @switchPreview $(document).on 'turbolinks:before-cache', -> $('.js-gallery--container').remove() initiateOpen: (e) => $target = $(e.currentTarget) return if $target.parents('a').length e.preventDefault() index = parseInt $target.attr('data-index'), 10 galleryId = $target.attr('data-gallery-id') @open {galleryId, index} open: ({galleryId, index}) => container = @container[0].cloneNode(true) container.classList.add 'js-gallery--container' document.body.appendChild container pswp = new PhotoSwipe container, PhotoSwipeUI_Default @data galleryId showHideOpacity: true getThumbBoundsFn: @thumbBoundsFn(galleryId) index: index history: false timeToIdle: null if _.startsWith(galleryId, 'contest-') new _exported.GalleryContest(container, pswp) pswp.init() $(document).one 'gallery:close', -> # ignore any failures (in case already destroyed) try pswp.close() data: (galleryId) -> for el in document.querySelectorAll(".js-gallery[data-gallery-id='#{galleryId}']") src = el.getAttribute('data-src') ? el.getAttribute('href') element: el msrc: src src: src w: parseInt el.getAttribute('data-width'), 10 h: parseInt el.getAttribute('data-height'), 10 thumbBoundsFn: (galleryId) => (i) => $thumb = $(".js-gallery[data-gallery-id='#{galleryId}'][data-index='#{i}']") thumbPos = $thumb.offset() thumbDim = [ $thumb.width() $thumb.height() ] center = [ thumbPos.left + thumbDim[0] / 2 thumbPos.top + thumbDim[1] / 2 ] imageDim = [ parseInt $thumb.attr('data-width'), 10 parseInt $thumb.attr('data-height'), 10 ] scale = Math.max thumbDim[0] / imageDim[0], thumbDim[1] / imageDim[1] scaledImageDim = imageDim.map (s) -> s * scale x: center[0] - scaledImageDim[0] / 2 y: center[1] - scaledImageDim[1] / 2 w: scaledImageDim[0] switchPreview: (e) => e.preventDefault() $link = $(e.currentTarget) {galleryId, index} = $link[0].dataset $previews = $(".js-gallery[data-gallery-id='#{galleryId}']") $links = $(".js-gallery-thumbnail[data-gallery-id='#{galleryId}']") for pair in _.zip($links, $previews) if index == pair[0].dataset.index pair[0].classList.add 'js-gallery-thumbnail--active' Fade.in pair[1] else pair[0].classList.remove 'js-gallery-thumbnail--active' Fade.out pair[1]
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @Gallery constructor: -> @container = document.getElementsByClassName('pswp') $(document).on 'click', '.js-gallery', @initiateOpen $(document).on 'click', '.js-gallery-thumbnail', @switchPreview $(document).on 'turbolinks:before-cache', -> $('.js-gallery--container').remove() initiateOpen: (e) => $target = $(e.currentTarget) return if $target.parents('a').length e.preventDefault() index = parseInt $target.attr('data-index'), 10 galleryId = $target.attr('data-gallery-id') @open {galleryId, index} open: ({galleryId, index}) => container = @container[0].cloneNode(true) container.classList.add 'js-gallery--container' document.body.appendChild container pswp = new PhotoSwipe container, PhotoSwipeUI_Default @data galleryId showHideOpacity: true getThumbBoundsFn: @thumbBoundsFn(galleryId) index: index history: false timeToIdle: null if _.startsWith(galleryId, 'contest-') new _exported.GalleryContest(container, pswp) pswp.init() $(document).one 'gallery:close', -> # ignore any failures (in case already destroyed) try pswp.close() data: (galleryId) -> for el in document.querySelectorAll(".js-gallery[data-gallery-id='#{galleryId}']") src = el.getAttribute('data-src') ? el.getAttribute('href') element: el msrc: src src: src w: parseInt el.getAttribute('data-width'), 10 h: parseInt el.getAttribute('data-height'), 10 thumbBoundsFn: (galleryId) => (i) => $thumb = $(".js-gallery[data-gallery-id='#{galleryId}'][data-index='#{i}']") thumbPos = $thumb.offset() thumbDim = [ $thumb.width() $thumb.height() ] center = [ thumbPos.left + thumbDim[0] / 2 thumbPos.top + thumbDim[1] / 2 ] imageDim = [ parseInt $thumb.attr('data-width'), 10 parseInt $thumb.attr('data-height'), 10 ] scale = Math.max thumbDim[0] / imageDim[0], thumbDim[1] / imageDim[1] scaledImageDim = imageDim.map (s) -> s * scale x: center[0] - scaledImageDim[0] / 2 y: center[1] - scaledImageDim[1] / 2 w: scaledImageDim[0] switchPreview: (e) => e.preventDefault() $link = $(e.currentTarget) {galleryId, index} = $link[0].dataset $previews = $(".js-gallery[data-gallery-id='#{galleryId}']") $links = $(".js-gallery-thumbnail[data-gallery-id='#{galleryId}']") for pair in _.zip($links, $previews) if index == pair[0].dataset.index pair[0].classList.add 'js-gallery-thumbnail--active' Fade.in pair[1] else pair[0].classList.remove 'js-gallery-thumbnail--active' Fade.out pair[1]
[ { "context": "et: {}\n user: appConfig.database.user\n pass: appConfig.database.pass\n\n options.server.socketOptions = options.replset", "end": 2038, "score": 0.787752091884613, "start": 2015, "tag": "PASSWORD", "value": "appConfig.database.pass" } ]
src/server/database/connection.coffee
ingshtrom/mystic-noggin
0
### * The bootstrapping for connecting to the MongoDB database. * @module mystic-noggin * @submodule server/database/connection * @requires {module} bluebird * @requires {module} mongoose * @requires {module} async * @requires {module} fs * @requires {module} path * @requires {submodule} server/app-config * @requires {submodules} server/logger ### P = require('bluebird') mongoose = P.promisifyAll(require('mongoose')) async = require('async') fs = require('fs') path = require('path') appConfig = require('../app-config') logger = require('../logger').logger schemas = require('./schemas') ### * Whether or not the database connection is open * @type {Boolean} * @private ### isOpen = false ### * Start a connection to the MongoDB database * @function start * @return {void} ### module.exports.start = -> dbUri = _buildConnectionString() options = _generateOptionsObj() # early return in case the connection is already open return mongoose.connection if mongoose.connection.readyState == 1 || mongoose.connection.readyState == 2 logger.debug 'going to load schemas', conn: mongoose.connection.readyState schemas.load() mongoose.connection.on('error', logger.error.bind(logger, 'mongodb error: ')) mongoose.connection.once('close', -> isOpen = false logger.info('connection with mongodb server closed.') ) mongoose.connection.once('open', -> isOpen = true logger.info('connection with mongodb server established.') ) mongoose.connect(dbUri, options) return mongoose.connection ### * Close the connection now! * @function close * @public * @return {void} ### module.exports.close = -> mongoose.connection.close() ### * Generate and return an options {object} that * can be passed directly to mongoose.connect() * @function _generateOptionsObj * @private * @return {object} ### _generateOptionsObj = -> options = server: auto_reconnect: true poolSize: 1 replset: {} user: appConfig.database.user pass: appConfig.database.pass options.server.socketOptions = options.replset.socketOptions = { keepAlive: 1 } return options ### * Builds and returns a string that can be passed * to mongoose.connect * @function _buildConnectionString * @private * @return {string} - mongoose connection string ### _buildConnectionString = -> conString = "mongodb://" conString += appConfig.database.serverName conString += ":#{appConfig.database.port}" conString += "/#{appConfig.database.dbName}" return conString
115655
### * The bootstrapping for connecting to the MongoDB database. * @module mystic-noggin * @submodule server/database/connection * @requires {module} bluebird * @requires {module} mongoose * @requires {module} async * @requires {module} fs * @requires {module} path * @requires {submodule} server/app-config * @requires {submodules} server/logger ### P = require('bluebird') mongoose = P.promisifyAll(require('mongoose')) async = require('async') fs = require('fs') path = require('path') appConfig = require('../app-config') logger = require('../logger').logger schemas = require('./schemas') ### * Whether or not the database connection is open * @type {Boolean} * @private ### isOpen = false ### * Start a connection to the MongoDB database * @function start * @return {void} ### module.exports.start = -> dbUri = _buildConnectionString() options = _generateOptionsObj() # early return in case the connection is already open return mongoose.connection if mongoose.connection.readyState == 1 || mongoose.connection.readyState == 2 logger.debug 'going to load schemas', conn: mongoose.connection.readyState schemas.load() mongoose.connection.on('error', logger.error.bind(logger, 'mongodb error: ')) mongoose.connection.once('close', -> isOpen = false logger.info('connection with mongodb server closed.') ) mongoose.connection.once('open', -> isOpen = true logger.info('connection with mongodb server established.') ) mongoose.connect(dbUri, options) return mongoose.connection ### * Close the connection now! * @function close * @public * @return {void} ### module.exports.close = -> mongoose.connection.close() ### * Generate and return an options {object} that * can be passed directly to mongoose.connect() * @function _generateOptionsObj * @private * @return {object} ### _generateOptionsObj = -> options = server: auto_reconnect: true poolSize: 1 replset: {} user: appConfig.database.user pass: <PASSWORD> options.server.socketOptions = options.replset.socketOptions = { keepAlive: 1 } return options ### * Builds and returns a string that can be passed * to mongoose.connect * @function _buildConnectionString * @private * @return {string} - mongoose connection string ### _buildConnectionString = -> conString = "mongodb://" conString += appConfig.database.serverName conString += ":#{appConfig.database.port}" conString += "/#{appConfig.database.dbName}" return conString
true
### * The bootstrapping for connecting to the MongoDB database. * @module mystic-noggin * @submodule server/database/connection * @requires {module} bluebird * @requires {module} mongoose * @requires {module} async * @requires {module} fs * @requires {module} path * @requires {submodule} server/app-config * @requires {submodules} server/logger ### P = require('bluebird') mongoose = P.promisifyAll(require('mongoose')) async = require('async') fs = require('fs') path = require('path') appConfig = require('../app-config') logger = require('../logger').logger schemas = require('./schemas') ### * Whether or not the database connection is open * @type {Boolean} * @private ### isOpen = false ### * Start a connection to the MongoDB database * @function start * @return {void} ### module.exports.start = -> dbUri = _buildConnectionString() options = _generateOptionsObj() # early return in case the connection is already open return mongoose.connection if mongoose.connection.readyState == 1 || mongoose.connection.readyState == 2 logger.debug 'going to load schemas', conn: mongoose.connection.readyState schemas.load() mongoose.connection.on('error', logger.error.bind(logger, 'mongodb error: ')) mongoose.connection.once('close', -> isOpen = false logger.info('connection with mongodb server closed.') ) mongoose.connection.once('open', -> isOpen = true logger.info('connection with mongodb server established.') ) mongoose.connect(dbUri, options) return mongoose.connection ### * Close the connection now! * @function close * @public * @return {void} ### module.exports.close = -> mongoose.connection.close() ### * Generate and return an options {object} that * can be passed directly to mongoose.connect() * @function _generateOptionsObj * @private * @return {object} ### _generateOptionsObj = -> options = server: auto_reconnect: true poolSize: 1 replset: {} user: appConfig.database.user pass: PI:PASSWORD:<PASSWORD>END_PI options.server.socketOptions = options.replset.socketOptions = { keepAlive: 1 } return options ### * Builds and returns a string that can be passed * to mongoose.connect * @function _buildConnectionString * @private * @return {string} - mongoose connection string ### _buildConnectionString = -> conString = "mongodb://" conString += appConfig.database.serverName conString += ":#{appConfig.database.port}" conString += "/#{appConfig.database.dbName}" return conString
[ { "context": "# Copyright (c) 2008-2014 Michael Dvorkin and contributors.\n#\n# Fat Free CRM is freely dist", "end": 41, "score": 0.9998666644096375, "start": 26, "tag": "NAME", "value": "Michael Dvorkin" } ]
app/assets/javascripts/pagination.js.coffee
roadt/fat_free_crm
1,290
# Copyright (c) 2008-2014 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ (($) -> $(document).on 'ajax:send', '.pagination, .per_page_options', -> $(this).find('a').prop('disabled', true) $(this).closest('#paginate').find('.spinner').show() $(document).on 'ajax:complete', '.pagination, .per_page_options', -> $(this).find('a').prop('disabled', false) $(this).closest('#paginate').find('.spinner').hide() ) jQuery
181329
# Copyright (c) 2008-2014 <NAME> and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ (($) -> $(document).on 'ajax:send', '.pagination, .per_page_options', -> $(this).find('a').prop('disabled', true) $(this).closest('#paginate').find('.spinner').show() $(document).on 'ajax:complete', '.pagination, .per_page_options', -> $(this).find('a').prop('disabled', false) $(this).closest('#paginate').find('.spinner').hide() ) jQuery
true
# Copyright (c) 2008-2014 PI:NAME:<NAME>END_PI and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ (($) -> $(document).on 'ajax:send', '.pagination, .per_page_options', -> $(this).find('a').prop('disabled', true) $(this).closest('#paginate').find('.spinner').show() $(document).on 'ajax:complete', '.pagination, .per_page_options', -> $(this).find('a').prop('disabled', false) $(this).closest('#paginate').find('.spinner').hide() ) jQuery
[ { "context": " I could not get it to work with $ajax :(\n\nkey = 'faa63307397f9a8437455fc4cacc3cd2'\n\nprevSch = []\n\npersist = ->\n elStorage.empty()\n", "end": 139, "score": 0.9997732639312744, "start": 107, "tag": "KEY", "value": "faa63307397f9a8437455fc4cacc3cd2" } ]
script.coffee
ratalla816/weather-dashborad
1
# I tried to write this in coffeescript for funzies, but I could not get it to work with $ajax :( key = 'faa63307397f9a8437455fc4cacc3cd2' prevSch = [] persist = -> elStorage.empty() i = 0 while i < prevSch.length elHistory = $('<row>') elButton = $('<button>') .text(''.concat(prevSch[i])) elHistory.addClass 'row prevTab' elButton.addClass 'prevTab' elButton.attr 'type', 'button' elStorage.prepend elHistory elHistory.append elButton i++ return # # _ # .__(.)< (YOWZA) # \___) # ~~~~~~~~~~~~~~~~~~~ persist = -> elPrevList.empty() i = 0 while i < prevSch.length listItem = $('<row>') listButton = $('<button>').text('' + prevSch[i]) listButton.addClass 'btn btn-primary prevObjBtn <br>' listItem.addClass 'row prevObjRow' listButton.attr 'type', 'button' elPrevList.prepend listItem listItem.append listButton i++ $('.prevObjBtn').on 'click', (event) -> city = $(this).text() event.preventDefault() elOutlook.empty() currentWeather() return return currentWeather = -> apiCurrent = 'https://api.openweathermap.org/data/2.5/weather?q=' .concat(city, '&units=imperial&appid=').concat(key) $(cityCurrentMain).empty() $.ajax( url: apiCurrent method: 'GET').then (response) -> $('.icons').attr 'src', 'https://openweathermap.org/img/wn/' .concat(response.weather[0].icon, '@2x.png') $('.cityCurrentName').text response.name $('.cityCurrentDate').text date coordLon = response.coord.lon coordLat = response.coord.lat elSpeed = $('<a>').text('Wind Speed: '.concat(response.wind.speed, ' MPH')) cityCurrentMain.append elSpeed elMain = $('<p>').text('Temperature: '.concat(response.main.temp, ' °F')) cityCurrentMain.append elMain elHumidity = $('<a>').text('Humidity: '.concat(response.main.humidity, ' %')) cityCurrentMain.append elHumidity fetchUvi = 'https://api.openweathermap.org/data/2.5/onecall?lat=' .concat(coordLat, '&lon=').concat(coordLon, '&exclude=hourly,daily,minutely&appid=').concat(key) $.ajax( url: fetchUvi method: 'GET').then (response) -> uviIndex = $('<p>').text('UV Index: ') elUvi = $('<span>').text(response.current.uvi) uvi = response.current.uvi cityCurrentMain.append uviIndex uviIndex.append elUvi if uvi >= 0 and uvi <= 4 elUvi.attr 'class', 'low' else if uvi > 5 and uvi <= 7 elUvi.attr 'class', 'medium' else if uvi > 8 and uvi <= 12 elUvi.attr 'class', 'barbeque' return return renderOutlook() return renderOutlook = -> fetchOutlook = 'https://api.openweathermap.org/data/2.5/forecast?q=' .concat(city, '&units=imperial&appid=').concat(key) $.ajax( url: fetchOutlook method: 'GET').then (response) -> aussichtsGruppe = response.list elWeather = [] $.each aussichtsGruppe, (index, value) -> elData = icon: value.weather[0].icon time: value.dt_txt.split(' ')[1] date: value.dt_txt.split(' ')[0] humidity: value.main.humidity temp: value.main.temp if value.dt_txt.split(' ')[1] == '12:00:00' elWeather.push elData return i = 0 while i < elWeather.length elCard = $('<div>') elCard.attr 'class', 'card bg-primary text-white mb-4' elOutlook.append elCard elHeader = $('<div>') elHeader.attr 'class', 'card-header' m = moment(''.concat(elWeather[i].date)).format('MM-DD-YYYY') elHeader.text m elCard.append elHeader elMain = $('<div>') elMain.attr 'class', 'card-body' elCard.append elMain elIcon = $('<img>') elIcon.attr 'src', 'https://openweathermap.org/img/wn/' .concat(elWeather[i].icon, '@2x.png') elMain.append elIcon elHumidity = $('<a>').text('Humidity: '.concat(elWeather[i].humidity, ' %')) elMain.append elHumidity elTemp = $('<p>').text('Temperature: '.concat(elWeather[i].temp, ' °F')) elMain.append elTemp i++ return return render = -> prevSchSet = JSON.parse(localStorage.getItem('city')) if prevSchSet != null prevSch = prevSchSet persist() currentWeather() return $('.search').on 'click', (event) -> event.preventDefault() city = $(this).parent('.srcInit').siblings('.cityText').val().trim() prevSch.push city localStorage.setItem 'city', JSON.stringify(prevSch) elOutlook.empty() currentWeather() persist() return elStorage = $('.prevSch') elPrevList = $('.prevSch') dateTime = moment().format('YYYY-MM-DD HH:MM:SS') date = moment().format('dddd, MMMM Do YYYY') cityCurrentMain = $('.cityCurrentMain') elOutlook = $('.fiveDay') render()
13677
# I tried to write this in coffeescript for funzies, but I could not get it to work with $ajax :( key = '<KEY>' prevSch = [] persist = -> elStorage.empty() i = 0 while i < prevSch.length elHistory = $('<row>') elButton = $('<button>') .text(''.concat(prevSch[i])) elHistory.addClass 'row prevTab' elButton.addClass 'prevTab' elButton.attr 'type', 'button' elStorage.prepend elHistory elHistory.append elButton i++ return # # _ # .__(.)< (YOWZA) # \___) # ~~~~~~~~~~~~~~~~~~~ persist = -> elPrevList.empty() i = 0 while i < prevSch.length listItem = $('<row>') listButton = $('<button>').text('' + prevSch[i]) listButton.addClass 'btn btn-primary prevObjBtn <br>' listItem.addClass 'row prevObjRow' listButton.attr 'type', 'button' elPrevList.prepend listItem listItem.append listButton i++ $('.prevObjBtn').on 'click', (event) -> city = $(this).text() event.preventDefault() elOutlook.empty() currentWeather() return return currentWeather = -> apiCurrent = 'https://api.openweathermap.org/data/2.5/weather?q=' .concat(city, '&units=imperial&appid=').concat(key) $(cityCurrentMain).empty() $.ajax( url: apiCurrent method: 'GET').then (response) -> $('.icons').attr 'src', 'https://openweathermap.org/img/wn/' .concat(response.weather[0].icon, '@2x.png') $('.cityCurrentName').text response.name $('.cityCurrentDate').text date coordLon = response.coord.lon coordLat = response.coord.lat elSpeed = $('<a>').text('Wind Speed: '.concat(response.wind.speed, ' MPH')) cityCurrentMain.append elSpeed elMain = $('<p>').text('Temperature: '.concat(response.main.temp, ' °F')) cityCurrentMain.append elMain elHumidity = $('<a>').text('Humidity: '.concat(response.main.humidity, ' %')) cityCurrentMain.append elHumidity fetchUvi = 'https://api.openweathermap.org/data/2.5/onecall?lat=' .concat(coordLat, '&lon=').concat(coordLon, '&exclude=hourly,daily,minutely&appid=').concat(key) $.ajax( url: fetchUvi method: 'GET').then (response) -> uviIndex = $('<p>').text('UV Index: ') elUvi = $('<span>').text(response.current.uvi) uvi = response.current.uvi cityCurrentMain.append uviIndex uviIndex.append elUvi if uvi >= 0 and uvi <= 4 elUvi.attr 'class', 'low' else if uvi > 5 and uvi <= 7 elUvi.attr 'class', 'medium' else if uvi > 8 and uvi <= 12 elUvi.attr 'class', 'barbeque' return return renderOutlook() return renderOutlook = -> fetchOutlook = 'https://api.openweathermap.org/data/2.5/forecast?q=' .concat(city, '&units=imperial&appid=').concat(key) $.ajax( url: fetchOutlook method: 'GET').then (response) -> aussichtsGruppe = response.list elWeather = [] $.each aussichtsGruppe, (index, value) -> elData = icon: value.weather[0].icon time: value.dt_txt.split(' ')[1] date: value.dt_txt.split(' ')[0] humidity: value.main.humidity temp: value.main.temp if value.dt_txt.split(' ')[1] == '12:00:00' elWeather.push elData return i = 0 while i < elWeather.length elCard = $('<div>') elCard.attr 'class', 'card bg-primary text-white mb-4' elOutlook.append elCard elHeader = $('<div>') elHeader.attr 'class', 'card-header' m = moment(''.concat(elWeather[i].date)).format('MM-DD-YYYY') elHeader.text m elCard.append elHeader elMain = $('<div>') elMain.attr 'class', 'card-body' elCard.append elMain elIcon = $('<img>') elIcon.attr 'src', 'https://openweathermap.org/img/wn/' .concat(elWeather[i].icon, '@2x.png') elMain.append elIcon elHumidity = $('<a>').text('Humidity: '.concat(elWeather[i].humidity, ' %')) elMain.append elHumidity elTemp = $('<p>').text('Temperature: '.concat(elWeather[i].temp, ' °F')) elMain.append elTemp i++ return return render = -> prevSchSet = JSON.parse(localStorage.getItem('city')) if prevSchSet != null prevSch = prevSchSet persist() currentWeather() return $('.search').on 'click', (event) -> event.preventDefault() city = $(this).parent('.srcInit').siblings('.cityText').val().trim() prevSch.push city localStorage.setItem 'city', JSON.stringify(prevSch) elOutlook.empty() currentWeather() persist() return elStorage = $('.prevSch') elPrevList = $('.prevSch') dateTime = moment().format('YYYY-MM-DD HH:MM:SS') date = moment().format('dddd, MMMM Do YYYY') cityCurrentMain = $('.cityCurrentMain') elOutlook = $('.fiveDay') render()
true
# I tried to write this in coffeescript for funzies, but I could not get it to work with $ajax :( key = 'PI:KEY:<KEY>END_PI' prevSch = [] persist = -> elStorage.empty() i = 0 while i < prevSch.length elHistory = $('<row>') elButton = $('<button>') .text(''.concat(prevSch[i])) elHistory.addClass 'row prevTab' elButton.addClass 'prevTab' elButton.attr 'type', 'button' elStorage.prepend elHistory elHistory.append elButton i++ return # # _ # .__(.)< (YOWZA) # \___) # ~~~~~~~~~~~~~~~~~~~ persist = -> elPrevList.empty() i = 0 while i < prevSch.length listItem = $('<row>') listButton = $('<button>').text('' + prevSch[i]) listButton.addClass 'btn btn-primary prevObjBtn <br>' listItem.addClass 'row prevObjRow' listButton.attr 'type', 'button' elPrevList.prepend listItem listItem.append listButton i++ $('.prevObjBtn').on 'click', (event) -> city = $(this).text() event.preventDefault() elOutlook.empty() currentWeather() return return currentWeather = -> apiCurrent = 'https://api.openweathermap.org/data/2.5/weather?q=' .concat(city, '&units=imperial&appid=').concat(key) $(cityCurrentMain).empty() $.ajax( url: apiCurrent method: 'GET').then (response) -> $('.icons').attr 'src', 'https://openweathermap.org/img/wn/' .concat(response.weather[0].icon, '@2x.png') $('.cityCurrentName').text response.name $('.cityCurrentDate').text date coordLon = response.coord.lon coordLat = response.coord.lat elSpeed = $('<a>').text('Wind Speed: '.concat(response.wind.speed, ' MPH')) cityCurrentMain.append elSpeed elMain = $('<p>').text('Temperature: '.concat(response.main.temp, ' °F')) cityCurrentMain.append elMain elHumidity = $('<a>').text('Humidity: '.concat(response.main.humidity, ' %')) cityCurrentMain.append elHumidity fetchUvi = 'https://api.openweathermap.org/data/2.5/onecall?lat=' .concat(coordLat, '&lon=').concat(coordLon, '&exclude=hourly,daily,minutely&appid=').concat(key) $.ajax( url: fetchUvi method: 'GET').then (response) -> uviIndex = $('<p>').text('UV Index: ') elUvi = $('<span>').text(response.current.uvi) uvi = response.current.uvi cityCurrentMain.append uviIndex uviIndex.append elUvi if uvi >= 0 and uvi <= 4 elUvi.attr 'class', 'low' else if uvi > 5 and uvi <= 7 elUvi.attr 'class', 'medium' else if uvi > 8 and uvi <= 12 elUvi.attr 'class', 'barbeque' return return renderOutlook() return renderOutlook = -> fetchOutlook = 'https://api.openweathermap.org/data/2.5/forecast?q=' .concat(city, '&units=imperial&appid=').concat(key) $.ajax( url: fetchOutlook method: 'GET').then (response) -> aussichtsGruppe = response.list elWeather = [] $.each aussichtsGruppe, (index, value) -> elData = icon: value.weather[0].icon time: value.dt_txt.split(' ')[1] date: value.dt_txt.split(' ')[0] humidity: value.main.humidity temp: value.main.temp if value.dt_txt.split(' ')[1] == '12:00:00' elWeather.push elData return i = 0 while i < elWeather.length elCard = $('<div>') elCard.attr 'class', 'card bg-primary text-white mb-4' elOutlook.append elCard elHeader = $('<div>') elHeader.attr 'class', 'card-header' m = moment(''.concat(elWeather[i].date)).format('MM-DD-YYYY') elHeader.text m elCard.append elHeader elMain = $('<div>') elMain.attr 'class', 'card-body' elCard.append elMain elIcon = $('<img>') elIcon.attr 'src', 'https://openweathermap.org/img/wn/' .concat(elWeather[i].icon, '@2x.png') elMain.append elIcon elHumidity = $('<a>').text('Humidity: '.concat(elWeather[i].humidity, ' %')) elMain.append elHumidity elTemp = $('<p>').text('Temperature: '.concat(elWeather[i].temp, ' °F')) elMain.append elTemp i++ return return render = -> prevSchSet = JSON.parse(localStorage.getItem('city')) if prevSchSet != null prevSch = prevSchSet persist() currentWeather() return $('.search').on 'click', (event) -> event.preventDefault() city = $(this).parent('.srcInit').siblings('.cityText').val().trim() prevSch.push city localStorage.setItem 'city', JSON.stringify(prevSch) elOutlook.empty() currentWeather() persist() return elStorage = $('.prevSch') elPrevList = $('.prevSch') dateTime = moment().format('YYYY-MM-DD HH:MM:SS') date = moment().format('dddd, MMMM Do YYYY') cityCurrentMain = $('.cityCurrentMain') elOutlook = $('.fiveDay') render()
[ { "context": "'\n 'body': \"issues_url '${1:https://github.com/johndoe/mycookbook/issues}'\"\n 'license metadata':\n 'p", "end": 537, "score": 0.9961466193199158, "start": 530, "tag": "USERNAME", "value": "johndoe" }, { "context": "ntainer_email'\n 'body': \"maintainer_emai...
snippets/metadata.cson
pschaumburg/language-chef
3
'.source.chef.metadata': 'chef_version metadata': 'prefix': 'chef_version' 'body': "chef_version '${1:>=} ${2:13}'" 'depends metadata': 'prefix': 'depends' 'body': "depends '${1:apache2}', '${2:<} ${3:1.0}'" 'description metadata': 'prefix': 'description' 'body': "description '${1:A fancy cookbook that manages a herd of cats!}'" 'gem metadata': 'prefix': 'gem' 'body': "gem '${1:poise}'" 'issues_url metadata': 'prefix': 'issues_url' 'body': "issues_url '${1:https://github.com/johndoe/mycookbook/issues}'" 'license metadata': 'prefix': 'license' 'body': "license '${1:All Rights Reserved}'" 'long_description metadata': 'prefix': 'long_description' 'body': "long_description ${1:IO.read(File.join(File.dirname(__FILE__), 'README.md'))}" 'maintainer_email metadata': 'prefix': 'maintainer_email' 'body': "maintainer_email '${1:john_doe@example.com}'" 'maintainer metadata': 'prefix': 'maintainer' 'body': "maintainer '${1:John Doe}'" 'name metadata': 'prefix': 'name' 'body': "name '${1:cats}'" 'ohai_version metadata': 'prefix': 'ohai_version' 'body': "ohai_version '${1:>=} ${2:13}'" 'privacy metadata': 'prefix': 'privacy' 'body': "privacy" 'provides metadata recipes': 'prefix': 'provides recipe' 'body': "provides '${1:cats::sleep}'" 'provides metadata definitions': 'prefix': 'provides definitions' 'body': "provides '${1:here(:kitty, :time_to_eat)}'" 'provides metadata resources': 'prefix': 'provides resources' 'body': "provides '${1:service[snuggle]}'" 'recipe metadata': 'prefix': 'recipe' 'body': "recipe '${1:cats::sleep}', '${2:For a crazy 20 hours a day.}'" 'source_url metadata': 'prefix': 'source_url' 'body': "source_url '${1:https://github.com/johndoe/mycookbook}'" 'supports metadata': 'prefix': 'supports' 'body': "supports '${1:ubuntu}'" 'version metadata': 'prefix': 'version' 'body': "version '${0:2.0.0}'"
9727
'.source.chef.metadata': 'chef_version metadata': 'prefix': 'chef_version' 'body': "chef_version '${1:>=} ${2:13}'" 'depends metadata': 'prefix': 'depends' 'body': "depends '${1:apache2}', '${2:<} ${3:1.0}'" 'description metadata': 'prefix': 'description' 'body': "description '${1:A fancy cookbook that manages a herd of cats!}'" 'gem metadata': 'prefix': 'gem' 'body': "gem '${1:poise}'" 'issues_url metadata': 'prefix': 'issues_url' 'body': "issues_url '${1:https://github.com/johndoe/mycookbook/issues}'" 'license metadata': 'prefix': 'license' 'body': "license '${1:All Rights Reserved}'" 'long_description metadata': 'prefix': 'long_description' 'body': "long_description ${1:IO.read(File.join(File.dirname(__FILE__), 'README.md'))}" 'maintainer_email metadata': 'prefix': 'maintainer_email' 'body': "maintainer_email '${1:<EMAIL>}'" 'maintainer metadata': 'prefix': 'maintainer' 'body': "maintainer '${1:<NAME>}'" 'name metadata': 'prefix': 'name' 'body': "name '${1:cats}'" 'ohai_version metadata': 'prefix': 'ohai_version' 'body': "ohai_version '${1:>=} ${2:13}'" 'privacy metadata': 'prefix': 'privacy' 'body': "privacy" 'provides metadata recipes': 'prefix': 'provides recipe' 'body': "provides '${1:cats::sleep}'" 'provides metadata definitions': 'prefix': 'provides definitions' 'body': "provides '${1:here(:kitty, :time_to_eat)}'" 'provides metadata resources': 'prefix': 'provides resources' 'body': "provides '${1:service[snuggle]}'" 'recipe metadata': 'prefix': 'recipe' 'body': "recipe '${1:cats::sleep}', '${2:For a crazy 20 hours a day.}'" 'source_url metadata': 'prefix': 'source_url' 'body': "source_url '${1:https://github.com/johndoe/mycookbook}'" 'supports metadata': 'prefix': 'supports' 'body': "supports '${1:ubuntu}'" 'version metadata': 'prefix': 'version' 'body': "version '${0:2.0.0}'"
true
'.source.chef.metadata': 'chef_version metadata': 'prefix': 'chef_version' 'body': "chef_version '${1:>=} ${2:13}'" 'depends metadata': 'prefix': 'depends' 'body': "depends '${1:apache2}', '${2:<} ${3:1.0}'" 'description metadata': 'prefix': 'description' 'body': "description '${1:A fancy cookbook that manages a herd of cats!}'" 'gem metadata': 'prefix': 'gem' 'body': "gem '${1:poise}'" 'issues_url metadata': 'prefix': 'issues_url' 'body': "issues_url '${1:https://github.com/johndoe/mycookbook/issues}'" 'license metadata': 'prefix': 'license' 'body': "license '${1:All Rights Reserved}'" 'long_description metadata': 'prefix': 'long_description' 'body': "long_description ${1:IO.read(File.join(File.dirname(__FILE__), 'README.md'))}" 'maintainer_email metadata': 'prefix': 'maintainer_email' 'body': "maintainer_email '${1:PI:EMAIL:<EMAIL>END_PI}'" 'maintainer metadata': 'prefix': 'maintainer' 'body': "maintainer '${1:PI:NAME:<NAME>END_PI}'" 'name metadata': 'prefix': 'name' 'body': "name '${1:cats}'" 'ohai_version metadata': 'prefix': 'ohai_version' 'body': "ohai_version '${1:>=} ${2:13}'" 'privacy metadata': 'prefix': 'privacy' 'body': "privacy" 'provides metadata recipes': 'prefix': 'provides recipe' 'body': "provides '${1:cats::sleep}'" 'provides metadata definitions': 'prefix': 'provides definitions' 'body': "provides '${1:here(:kitty, :time_to_eat)}'" 'provides metadata resources': 'prefix': 'provides resources' 'body': "provides '${1:service[snuggle]}'" 'recipe metadata': 'prefix': 'recipe' 'body': "recipe '${1:cats::sleep}', '${2:For a crazy 20 hours a day.}'" 'source_url metadata': 'prefix': 'source_url' 'body': "source_url '${1:https://github.com/johndoe/mycookbook}'" 'supports metadata': 'prefix': 'supports' 'body': "supports '${1:ubuntu}'" 'version metadata': 'prefix': 'version' 'body': "version '${0:2.0.0}'"
[ { "context": " ->\n expect(commit.author.login).to.equal('caboteria')\n done()\n\n it \"returns a detailed git ", "end": 1072, "score": 0.9969938397407532, "start": 1063, "tag": "USERNAME", "value": "caboteria" }, { "context": ") ->\n expect(commit.author.name...
test/ruby-specs/commits.spec.coffee
BafS/octokat.js
59
define = window?.define or (cb) -> cb ((dep) -> require(dep.replace('cs!', ''))) define (require) -> {expect} = require 'chai' {client, LONG_TIMEOUT, test_repo} = require 'cs!../test-config' describe 'Commits', () -> @timeout(LONG_TIMEOUT) it "returns all commits", (done) -> client.repos("sferik/rails_admin").commits.fetch() .then (commits) -> expect(commits[0].author).to.be.ok done() # it "handles branch or sha argument", (done) -> it "handles the sha option", (done) -> client.repos("sferik/rails_admin").commits.fetch({sha:"master"}) .then () -> done() it "returns all commits on the specified date", (done) -> client.repos("sferik/rails_admin").commits.fetch({since:"2011-01-20"}) .then (commits) -> expect(commits).to.be.an.Array done() it "returns a commit", (done) -> client.repos("sferik/rails_admin").commits("3cdfabd973bc3caac209cba903cfdb3bf6636bcd").fetch() .then (commit) -> expect(commit.author.login).to.equal('caboteria') done() it "returns a detailed git commit", (done) -> client.repos("octokit/octokit.rb").git.commits("2bfca14ed8ebc3dad75082ff175e6703aed7ccc0").fetch() .then (commit) -> expect(commit.author.name).to.equal('Joey Wendt') done() it "creates a commit", (done) -> client.repos(test_repo).commits.fetch() .then (commits) -> last_commit = commits[commits.length-1] client.repos(test_repo).git.commits.create({message: "My commit message", tree:last_commit.commit.tree.sha, parents:[last_commit.sha]}) .then () -> done() it "merges a branch into another", (done) -> afterRemove = () -> repo = client.repos(test_repo) repo.commits.fetch() .then (commits) -> last_commit = commits[commits.length-1] repo.git.refs.create({ref:"refs/heads/branch-to-merge", sha:last_commit.sha}) .then (v) -> head = 'master' base = 'branch-to-merge' commitMessage = "Testing the merge API" client.repos(test_repo).merges.create({base, head, commitMessage}) .then () -> done() client.repos(test_repo).git.refs.heads('branch-to-merge').remove() .then(afterRemove, afterRemove) it "returns a comparison", (done) -> client.repos("gvaughn/octokit").compare('0e0d7ae299514da692eb1cab741562c253d44188', 'b7b37f75a80b8e84061cd45b246232ad958158f5').fetch() .then (comparison) -> expect(comparison.baseCommit.sha).to.equal('0e0d7ae299514da692eb1cab741562c253d44188') expect(comparison.mergeBaseCommit.sha).to.equal('b7b37f75a80b8e84061cd45b246232ad958158f5') done()
158129
define = window?.define or (cb) -> cb ((dep) -> require(dep.replace('cs!', ''))) define (require) -> {expect} = require 'chai' {client, LONG_TIMEOUT, test_repo} = require 'cs!../test-config' describe 'Commits', () -> @timeout(LONG_TIMEOUT) it "returns all commits", (done) -> client.repos("sferik/rails_admin").commits.fetch() .then (commits) -> expect(commits[0].author).to.be.ok done() # it "handles branch or sha argument", (done) -> it "handles the sha option", (done) -> client.repos("sferik/rails_admin").commits.fetch({sha:"master"}) .then () -> done() it "returns all commits on the specified date", (done) -> client.repos("sferik/rails_admin").commits.fetch({since:"2011-01-20"}) .then (commits) -> expect(commits).to.be.an.Array done() it "returns a commit", (done) -> client.repos("sferik/rails_admin").commits("3cdfabd973bc3caac209cba903cfdb3bf6636bcd").fetch() .then (commit) -> expect(commit.author.login).to.equal('caboteria') done() it "returns a detailed git commit", (done) -> client.repos("octokit/octokit.rb").git.commits("2bfca14ed8ebc3dad75082ff175e6703aed7ccc0").fetch() .then (commit) -> expect(commit.author.name).to.equal('<NAME>') done() it "creates a commit", (done) -> client.repos(test_repo).commits.fetch() .then (commits) -> last_commit = commits[commits.length-1] client.repos(test_repo).git.commits.create({message: "My commit message", tree:last_commit.commit.tree.sha, parents:[last_commit.sha]}) .then () -> done() it "merges a branch into another", (done) -> afterRemove = () -> repo = client.repos(test_repo) repo.commits.fetch() .then (commits) -> last_commit = commits[commits.length-1] repo.git.refs.create({ref:"refs/heads/branch-to-merge", sha:last_commit.sha}) .then (v) -> head = 'master' base = 'branch-to-merge' commitMessage = "Testing the merge API" client.repos(test_repo).merges.create({base, head, commitMessage}) .then () -> done() client.repos(test_repo).git.refs.heads('branch-to-merge').remove() .then(afterRemove, afterRemove) it "returns a comparison", (done) -> client.repos("gvaughn/octokit").compare('0e0d7ae299514da692eb1cab741562c253d44188', 'b7b37f75a80b8e84061cd45b246232ad958158f5').fetch() .then (comparison) -> expect(comparison.baseCommit.sha).to.equal('0e0d7ae299514da692eb1cab741562c253d44188') expect(comparison.mergeBaseCommit.sha).to.equal('b7b37f75a80b8e84061cd45b246232ad958158f5') done()
true
define = window?.define or (cb) -> cb ((dep) -> require(dep.replace('cs!', ''))) define (require) -> {expect} = require 'chai' {client, LONG_TIMEOUT, test_repo} = require 'cs!../test-config' describe 'Commits', () -> @timeout(LONG_TIMEOUT) it "returns all commits", (done) -> client.repos("sferik/rails_admin").commits.fetch() .then (commits) -> expect(commits[0].author).to.be.ok done() # it "handles branch or sha argument", (done) -> it "handles the sha option", (done) -> client.repos("sferik/rails_admin").commits.fetch({sha:"master"}) .then () -> done() it "returns all commits on the specified date", (done) -> client.repos("sferik/rails_admin").commits.fetch({since:"2011-01-20"}) .then (commits) -> expect(commits).to.be.an.Array done() it "returns a commit", (done) -> client.repos("sferik/rails_admin").commits("3cdfabd973bc3caac209cba903cfdb3bf6636bcd").fetch() .then (commit) -> expect(commit.author.login).to.equal('caboteria') done() it "returns a detailed git commit", (done) -> client.repos("octokit/octokit.rb").git.commits("2bfca14ed8ebc3dad75082ff175e6703aed7ccc0").fetch() .then (commit) -> expect(commit.author.name).to.equal('PI:NAME:<NAME>END_PI') done() it "creates a commit", (done) -> client.repos(test_repo).commits.fetch() .then (commits) -> last_commit = commits[commits.length-1] client.repos(test_repo).git.commits.create({message: "My commit message", tree:last_commit.commit.tree.sha, parents:[last_commit.sha]}) .then () -> done() it "merges a branch into another", (done) -> afterRemove = () -> repo = client.repos(test_repo) repo.commits.fetch() .then (commits) -> last_commit = commits[commits.length-1] repo.git.refs.create({ref:"refs/heads/branch-to-merge", sha:last_commit.sha}) .then (v) -> head = 'master' base = 'branch-to-merge' commitMessage = "Testing the merge API" client.repos(test_repo).merges.create({base, head, commitMessage}) .then () -> done() client.repos(test_repo).git.refs.heads('branch-to-merge').remove() .then(afterRemove, afterRemove) it "returns a comparison", (done) -> client.repos("gvaughn/octokit").compare('0e0d7ae299514da692eb1cab741562c253d44188', 'b7b37f75a80b8e84061cd45b246232ad958158f5').fetch() .then (comparison) -> expect(comparison.baseCommit.sha).to.equal('0e0d7ae299514da692eb1cab741562c253d44188') expect(comparison.mergeBaseCommit.sha).to.equal('b7b37f75a80b8e84061cd45b246232ad958158f5') done()
[ { "context": "n @props.projectModal.steps\n step._key ?= Math.random()\n <ProjectModalStepEditor\n k", "end": 2344, "score": 0.9415947794914246, "start": 2333, "tag": "KEY", "value": "Math.random" } ]
app/partials/project-modal-editor.cjsx
cientopolis/collaboratory-frontend
1
React = require 'react' apiClient = require 'panoptes-client/lib/api-client' putFile = require '../lib/put-file' FileButton = require '../components/file-button' {MarkdownEditor} = require 'markdownz' debounce = require 'debounce' ProjectModalStepEditor = React.createClass getDefaultProps: -> step: null media: null onChange: -> console.log 'ProjectModalStepEditor onChange', arguments onMediaSelect: -> console.log 'ProjectModalStepEditor onMediaSelect', arguments onMediaClear: -> console.log 'ProjectModalStepEditor onMediaClear', arguments onRemove: -> console.log 'ProjectModalStepEditor onRemove', arguments render: -> <div className="project-modal-step-editor"> <header> <button type="button" className="secret-button" title="Remove step" aria-label="Remove step" onClick={@props.onRemove}> <i className="fa fa-times fa-fw"></i> </button> </header> <p> {if @props.media? <span> <img className="project-modal-step-editor-media" src={@props.media.src} />{' '} <button type="button" className="minor-button" onClick={@props.onMediaClear}>Clear</button> </span>}{' '} <FileButton className="standard-button" onSelect={@handleMediaChange}>Select media</FileButton> </p> <div> <MarkdownEditor className="full" value={@props.step.content} onChange={@handleContentChange} /> </div> </div> handleMediaChange: (e) -> @props.onMediaSelect e.target.files[0], arguments... handleContentChange: (e) -> @props.onChange 'content', e.target.value, arguments... ProjectModalEditor = React.createClass getDefaultProps: -> projectModal: null media: null type: null onStepAdd: -> console.log 'ProjectModalEditor onStepAdd', arguments onStepRemove: -> console.log 'ProjectModalEditor onStepRemove', arguments onMediaSelect: -> console.log 'ProjectModalEditor onMediaSelect', arguments onStepChange: -> console.log 'ProjectModalEditor onChange', arguments render: -> <div style={maxWidth: '50ch'}> {if @props.projectModal.steps.length is 0 <p>This tutorial has no steps.</p> else for step, i in @props.projectModal.steps step._key ?= Math.random() <ProjectModalStepEditor key={step._key} step={step} media={@props.media?[step.media]} onMediaSelect={@props.onMediaSelect.bind null, i} onMediaClear={@props.onMediaClear.bind null, i} onChange={@props.onStepChange.bind null, i} onRemove={@props.onStepRemove.bind null, i} />} <div> <button type="button" onClick={@props.onStepAdd}>Add a step</button> </div> </div> ProjectModalEditorController = React.createClass getDefaultProps: -> project: null projectModal: null media: {} delayBeforeSave: 5000 type: null onChangeMedia: -> console.log 'ProjectModalEditorController onChangeMedia', arguments onDelete: -> console.log 'ProjectModalEditorController onDelete', arguments componentDidMount: -> @_boundForceUpdate = @forceUpdate.bind this @props.projectModal.listen @_boundForceUpdate componentWillUnmount: -> @props.projectModal.stopListening @_boundForceUpdate render: -> <ProjectModalEditor projectModal={@props.projectModal} media={@props.media} type={@props.type} onStepAdd={@handleStepAdd} onStepRemove={@handleStepRemove} onMediaSelect={@handleStepMediaChange} onMediaClear={@handleStepMediaClear} onStepChange={@handleStepChange} /> handleStepAdd: -> @props.projectModal.steps.push media: '' content: '' @props.projectModal.update 'steps' @props.projectModal.save() handleStepRemove: (index) -> @handleStepMediaClear index changes = {} changes["steps.#{index}"] = undefined @props.projectModal.update changes if @props.projectModal.steps.length is 0 @props.projectModal.delete() .then => @props.onDelete() else @props.projectModal.save() handleStepMediaChange: (index, file) -> @handleStepMediaClear index payload = media: content_type: file.type metadata: filename: file.name apiClient.post @props.projectModal._getURL('attached_images'), payload .then (media) => media = [].concat(media)[0] putFile media.src, file, {'Content-Type': file.type} .then => changes = {} changes["steps.#{index}.media"] = media.id @props.projectModal.update changes @props.projectModal.save() .then => @props.onChangeMedia() .catch (error) => console.error error handleStepMediaClear: (index) -> @props.media[@props.projectModal.steps[index].media]?.delete() changes = {} changes["steps.#{index}.media"] = undefined @props.projectModal.update changes @props.projectModal.save() handleStepChange: (index, key, value) -> changes = {} changes["steps.#{index}.#{key}"] = value @props.projectModal.update changes @saveProjectModal() saveProjectModal: -> unless @_debouncedSaveProjectModal? boundProjectModalSave = @props.projectModal.save.bind @props.projectModal @_debouncedSaveProjectModal = debounce boundProjectModalSave, @props.delayBeforeSave @_debouncedSaveProjectModal arguments... ProjectModalCreator = React.createClass getDefaultProps: -> project: null type: null onCreate: -> console.log 'ProjectModalCreator onCreate', arguments getInitialState: -> error: null render: -> <div> <p>This project doesn’t have a tutorial.</p> {if @state.error? <p>{@state.error.toString()}</p>} <p> <button type="button" onClick={@handleCreateClick}>Build one</button> </p> </div> handleCreateClick: -> projectModalType = @props.type projectModalData = steps: [] language: 'en' links: project: @props.project.id @setState error: null apiClient.type(projectModalType).create(projectModalData).save() .then (createdProjectModal) => @props.onCreate createdProjectModal .catch (error) => @setState {error} ProjectModalEditorFetcher = React.createClass getDefaultProps: -> project: null type: null getInitialState: -> loading: false error: null projectModal: null media: {} componentDidMount: -> @_boundForceUpdate = @forceUpdate.bind this @props.project.listen @_boundForceUpdate @fetchProjectModalFor @props.project componentWillUnmount: -> @props.project.stopListening @_boundForceUpdate componentWillReceiveProps: (nextProps) -> unless nextProps.project is @props.project @props.project.stopListening @_boundForceUpdate nextProps.project.listen @_boundForceUpdate @fetchProjectModalFor nextProps.project fetchProjectModalFor: (project) -> @setState loading: true error: null projectModal: null apiClient.type(@props.type).get project_id: project.id .then ([projectModal]) => @setState {projectModal} @fetchMediaFor projectModal .catch (error) => @setState {error} .then => @setState loading: false fetchMediaFor: (projectModal) -> if projectModal? projectModal.get 'attached_images', {} # Prevent caching. .catch => [] # We get an an error if there're no attached images. .then (mediaResources) => media = {} for mediaResource in mediaResources media[mediaResource.id] = mediaResource @setState {media} else @setState media: {} render: -> if @state.loading <p>Loading...</p> else if @state.error? <p>{@state.error.toString()}</p> else if @state.projectModal? window?.editingProjectModal = @state.projectModal <ProjectModalEditorController project={@props.project} projectModal={@state.projectModal} media={@state.media} type={@props.type} onChangeMedia={@handleChangeToMedia} onDelete={@handleProjectModalCreateOrDelete} /> else <ProjectModalCreator project={@props.project} type={@props.type} onCreate={@handleProjectModalCreateOrDelete} /> handleChangeToMedia: -> @fetchMediaFor @state.projectModal handleProjectModalCreateOrDelete: -> @fetchProjectModalFor @props.project module.exports = ProjectModalEditorFetcher
159807
React = require 'react' apiClient = require 'panoptes-client/lib/api-client' putFile = require '../lib/put-file' FileButton = require '../components/file-button' {MarkdownEditor} = require 'markdownz' debounce = require 'debounce' ProjectModalStepEditor = React.createClass getDefaultProps: -> step: null media: null onChange: -> console.log 'ProjectModalStepEditor onChange', arguments onMediaSelect: -> console.log 'ProjectModalStepEditor onMediaSelect', arguments onMediaClear: -> console.log 'ProjectModalStepEditor onMediaClear', arguments onRemove: -> console.log 'ProjectModalStepEditor onRemove', arguments render: -> <div className="project-modal-step-editor"> <header> <button type="button" className="secret-button" title="Remove step" aria-label="Remove step" onClick={@props.onRemove}> <i className="fa fa-times fa-fw"></i> </button> </header> <p> {if @props.media? <span> <img className="project-modal-step-editor-media" src={@props.media.src} />{' '} <button type="button" className="minor-button" onClick={@props.onMediaClear}>Clear</button> </span>}{' '} <FileButton className="standard-button" onSelect={@handleMediaChange}>Select media</FileButton> </p> <div> <MarkdownEditor className="full" value={@props.step.content} onChange={@handleContentChange} /> </div> </div> handleMediaChange: (e) -> @props.onMediaSelect e.target.files[0], arguments... handleContentChange: (e) -> @props.onChange 'content', e.target.value, arguments... ProjectModalEditor = React.createClass getDefaultProps: -> projectModal: null media: null type: null onStepAdd: -> console.log 'ProjectModalEditor onStepAdd', arguments onStepRemove: -> console.log 'ProjectModalEditor onStepRemove', arguments onMediaSelect: -> console.log 'ProjectModalEditor onMediaSelect', arguments onStepChange: -> console.log 'ProjectModalEditor onChange', arguments render: -> <div style={maxWidth: '50ch'}> {if @props.projectModal.steps.length is 0 <p>This tutorial has no steps.</p> else for step, i in @props.projectModal.steps step._key ?= <KEY>() <ProjectModalStepEditor key={step._key} step={step} media={@props.media?[step.media]} onMediaSelect={@props.onMediaSelect.bind null, i} onMediaClear={@props.onMediaClear.bind null, i} onChange={@props.onStepChange.bind null, i} onRemove={@props.onStepRemove.bind null, i} />} <div> <button type="button" onClick={@props.onStepAdd}>Add a step</button> </div> </div> ProjectModalEditorController = React.createClass getDefaultProps: -> project: null projectModal: null media: {} delayBeforeSave: 5000 type: null onChangeMedia: -> console.log 'ProjectModalEditorController onChangeMedia', arguments onDelete: -> console.log 'ProjectModalEditorController onDelete', arguments componentDidMount: -> @_boundForceUpdate = @forceUpdate.bind this @props.projectModal.listen @_boundForceUpdate componentWillUnmount: -> @props.projectModal.stopListening @_boundForceUpdate render: -> <ProjectModalEditor projectModal={@props.projectModal} media={@props.media} type={@props.type} onStepAdd={@handleStepAdd} onStepRemove={@handleStepRemove} onMediaSelect={@handleStepMediaChange} onMediaClear={@handleStepMediaClear} onStepChange={@handleStepChange} /> handleStepAdd: -> @props.projectModal.steps.push media: '' content: '' @props.projectModal.update 'steps' @props.projectModal.save() handleStepRemove: (index) -> @handleStepMediaClear index changes = {} changes["steps.#{index}"] = undefined @props.projectModal.update changes if @props.projectModal.steps.length is 0 @props.projectModal.delete() .then => @props.onDelete() else @props.projectModal.save() handleStepMediaChange: (index, file) -> @handleStepMediaClear index payload = media: content_type: file.type metadata: filename: file.name apiClient.post @props.projectModal._getURL('attached_images'), payload .then (media) => media = [].concat(media)[0] putFile media.src, file, {'Content-Type': file.type} .then => changes = {} changes["steps.#{index}.media"] = media.id @props.projectModal.update changes @props.projectModal.save() .then => @props.onChangeMedia() .catch (error) => console.error error handleStepMediaClear: (index) -> @props.media[@props.projectModal.steps[index].media]?.delete() changes = {} changes["steps.#{index}.media"] = undefined @props.projectModal.update changes @props.projectModal.save() handleStepChange: (index, key, value) -> changes = {} changes["steps.#{index}.#{key}"] = value @props.projectModal.update changes @saveProjectModal() saveProjectModal: -> unless @_debouncedSaveProjectModal? boundProjectModalSave = @props.projectModal.save.bind @props.projectModal @_debouncedSaveProjectModal = debounce boundProjectModalSave, @props.delayBeforeSave @_debouncedSaveProjectModal arguments... ProjectModalCreator = React.createClass getDefaultProps: -> project: null type: null onCreate: -> console.log 'ProjectModalCreator onCreate', arguments getInitialState: -> error: null render: -> <div> <p>This project doesn’t have a tutorial.</p> {if @state.error? <p>{@state.error.toString()}</p>} <p> <button type="button" onClick={@handleCreateClick}>Build one</button> </p> </div> handleCreateClick: -> projectModalType = @props.type projectModalData = steps: [] language: 'en' links: project: @props.project.id @setState error: null apiClient.type(projectModalType).create(projectModalData).save() .then (createdProjectModal) => @props.onCreate createdProjectModal .catch (error) => @setState {error} ProjectModalEditorFetcher = React.createClass getDefaultProps: -> project: null type: null getInitialState: -> loading: false error: null projectModal: null media: {} componentDidMount: -> @_boundForceUpdate = @forceUpdate.bind this @props.project.listen @_boundForceUpdate @fetchProjectModalFor @props.project componentWillUnmount: -> @props.project.stopListening @_boundForceUpdate componentWillReceiveProps: (nextProps) -> unless nextProps.project is @props.project @props.project.stopListening @_boundForceUpdate nextProps.project.listen @_boundForceUpdate @fetchProjectModalFor nextProps.project fetchProjectModalFor: (project) -> @setState loading: true error: null projectModal: null apiClient.type(@props.type).get project_id: project.id .then ([projectModal]) => @setState {projectModal} @fetchMediaFor projectModal .catch (error) => @setState {error} .then => @setState loading: false fetchMediaFor: (projectModal) -> if projectModal? projectModal.get 'attached_images', {} # Prevent caching. .catch => [] # We get an an error if there're no attached images. .then (mediaResources) => media = {} for mediaResource in mediaResources media[mediaResource.id] = mediaResource @setState {media} else @setState media: {} render: -> if @state.loading <p>Loading...</p> else if @state.error? <p>{@state.error.toString()}</p> else if @state.projectModal? window?.editingProjectModal = @state.projectModal <ProjectModalEditorController project={@props.project} projectModal={@state.projectModal} media={@state.media} type={@props.type} onChangeMedia={@handleChangeToMedia} onDelete={@handleProjectModalCreateOrDelete} /> else <ProjectModalCreator project={@props.project} type={@props.type} onCreate={@handleProjectModalCreateOrDelete} /> handleChangeToMedia: -> @fetchMediaFor @state.projectModal handleProjectModalCreateOrDelete: -> @fetchProjectModalFor @props.project module.exports = ProjectModalEditorFetcher
true
React = require 'react' apiClient = require 'panoptes-client/lib/api-client' putFile = require '../lib/put-file' FileButton = require '../components/file-button' {MarkdownEditor} = require 'markdownz' debounce = require 'debounce' ProjectModalStepEditor = React.createClass getDefaultProps: -> step: null media: null onChange: -> console.log 'ProjectModalStepEditor onChange', arguments onMediaSelect: -> console.log 'ProjectModalStepEditor onMediaSelect', arguments onMediaClear: -> console.log 'ProjectModalStepEditor onMediaClear', arguments onRemove: -> console.log 'ProjectModalStepEditor onRemove', arguments render: -> <div className="project-modal-step-editor"> <header> <button type="button" className="secret-button" title="Remove step" aria-label="Remove step" onClick={@props.onRemove}> <i className="fa fa-times fa-fw"></i> </button> </header> <p> {if @props.media? <span> <img className="project-modal-step-editor-media" src={@props.media.src} />{' '} <button type="button" className="minor-button" onClick={@props.onMediaClear}>Clear</button> </span>}{' '} <FileButton className="standard-button" onSelect={@handleMediaChange}>Select media</FileButton> </p> <div> <MarkdownEditor className="full" value={@props.step.content} onChange={@handleContentChange} /> </div> </div> handleMediaChange: (e) -> @props.onMediaSelect e.target.files[0], arguments... handleContentChange: (e) -> @props.onChange 'content', e.target.value, arguments... ProjectModalEditor = React.createClass getDefaultProps: -> projectModal: null media: null type: null onStepAdd: -> console.log 'ProjectModalEditor onStepAdd', arguments onStepRemove: -> console.log 'ProjectModalEditor onStepRemove', arguments onMediaSelect: -> console.log 'ProjectModalEditor onMediaSelect', arguments onStepChange: -> console.log 'ProjectModalEditor onChange', arguments render: -> <div style={maxWidth: '50ch'}> {if @props.projectModal.steps.length is 0 <p>This tutorial has no steps.</p> else for step, i in @props.projectModal.steps step._key ?= PI:KEY:<KEY>END_PI() <ProjectModalStepEditor key={step._key} step={step} media={@props.media?[step.media]} onMediaSelect={@props.onMediaSelect.bind null, i} onMediaClear={@props.onMediaClear.bind null, i} onChange={@props.onStepChange.bind null, i} onRemove={@props.onStepRemove.bind null, i} />} <div> <button type="button" onClick={@props.onStepAdd}>Add a step</button> </div> </div> ProjectModalEditorController = React.createClass getDefaultProps: -> project: null projectModal: null media: {} delayBeforeSave: 5000 type: null onChangeMedia: -> console.log 'ProjectModalEditorController onChangeMedia', arguments onDelete: -> console.log 'ProjectModalEditorController onDelete', arguments componentDidMount: -> @_boundForceUpdate = @forceUpdate.bind this @props.projectModal.listen @_boundForceUpdate componentWillUnmount: -> @props.projectModal.stopListening @_boundForceUpdate render: -> <ProjectModalEditor projectModal={@props.projectModal} media={@props.media} type={@props.type} onStepAdd={@handleStepAdd} onStepRemove={@handleStepRemove} onMediaSelect={@handleStepMediaChange} onMediaClear={@handleStepMediaClear} onStepChange={@handleStepChange} /> handleStepAdd: -> @props.projectModal.steps.push media: '' content: '' @props.projectModal.update 'steps' @props.projectModal.save() handleStepRemove: (index) -> @handleStepMediaClear index changes = {} changes["steps.#{index}"] = undefined @props.projectModal.update changes if @props.projectModal.steps.length is 0 @props.projectModal.delete() .then => @props.onDelete() else @props.projectModal.save() handleStepMediaChange: (index, file) -> @handleStepMediaClear index payload = media: content_type: file.type metadata: filename: file.name apiClient.post @props.projectModal._getURL('attached_images'), payload .then (media) => media = [].concat(media)[0] putFile media.src, file, {'Content-Type': file.type} .then => changes = {} changes["steps.#{index}.media"] = media.id @props.projectModal.update changes @props.projectModal.save() .then => @props.onChangeMedia() .catch (error) => console.error error handleStepMediaClear: (index) -> @props.media[@props.projectModal.steps[index].media]?.delete() changes = {} changes["steps.#{index}.media"] = undefined @props.projectModal.update changes @props.projectModal.save() handleStepChange: (index, key, value) -> changes = {} changes["steps.#{index}.#{key}"] = value @props.projectModal.update changes @saveProjectModal() saveProjectModal: -> unless @_debouncedSaveProjectModal? boundProjectModalSave = @props.projectModal.save.bind @props.projectModal @_debouncedSaveProjectModal = debounce boundProjectModalSave, @props.delayBeforeSave @_debouncedSaveProjectModal arguments... ProjectModalCreator = React.createClass getDefaultProps: -> project: null type: null onCreate: -> console.log 'ProjectModalCreator onCreate', arguments getInitialState: -> error: null render: -> <div> <p>This project doesn’t have a tutorial.</p> {if @state.error? <p>{@state.error.toString()}</p>} <p> <button type="button" onClick={@handleCreateClick}>Build one</button> </p> </div> handleCreateClick: -> projectModalType = @props.type projectModalData = steps: [] language: 'en' links: project: @props.project.id @setState error: null apiClient.type(projectModalType).create(projectModalData).save() .then (createdProjectModal) => @props.onCreate createdProjectModal .catch (error) => @setState {error} ProjectModalEditorFetcher = React.createClass getDefaultProps: -> project: null type: null getInitialState: -> loading: false error: null projectModal: null media: {} componentDidMount: -> @_boundForceUpdate = @forceUpdate.bind this @props.project.listen @_boundForceUpdate @fetchProjectModalFor @props.project componentWillUnmount: -> @props.project.stopListening @_boundForceUpdate componentWillReceiveProps: (nextProps) -> unless nextProps.project is @props.project @props.project.stopListening @_boundForceUpdate nextProps.project.listen @_boundForceUpdate @fetchProjectModalFor nextProps.project fetchProjectModalFor: (project) -> @setState loading: true error: null projectModal: null apiClient.type(@props.type).get project_id: project.id .then ([projectModal]) => @setState {projectModal} @fetchMediaFor projectModal .catch (error) => @setState {error} .then => @setState loading: false fetchMediaFor: (projectModal) -> if projectModal? projectModal.get 'attached_images', {} # Prevent caching. .catch => [] # We get an an error if there're no attached images. .then (mediaResources) => media = {} for mediaResource in mediaResources media[mediaResource.id] = mediaResource @setState {media} else @setState media: {} render: -> if @state.loading <p>Loading...</p> else if @state.error? <p>{@state.error.toString()}</p> else if @state.projectModal? window?.editingProjectModal = @state.projectModal <ProjectModalEditorController project={@props.project} projectModal={@state.projectModal} media={@state.media} type={@props.type} onChangeMedia={@handleChangeToMedia} onDelete={@handleProjectModalCreateOrDelete} /> else <ProjectModalCreator project={@props.project} type={@props.type} onCreate={@handleProjectModalCreateOrDelete} /> handleChangeToMedia: -> @fetchMediaFor @state.projectModal handleProjectModalCreateOrDelete: -> @fetchProjectModalFor @props.project module.exports = ProjectModalEditorFetcher
[ { "context": "exports.glyphs['caronSlovak'] =\n\tglyphName: 'caron slovak'\n\tcharacterName: 'CARON SLOVAK'\n\tanchors:\n\t\t0:\n\t\t", "end": 57, "score": 0.9991868138313293, "start": 45, "tag": "NAME", "value": "caron slovak" }, { "context": "k'] =\n\tglyphName: 'caron slovak'\n\tc...
src/glyphs/components/caronSlovak.coffee
byte-foundry/antique.ptf
0
exports.glyphs['caronSlovak'] = glyphName: 'caron slovak' characterName: 'CARON SLOVAK' anchors: 0: x: parentAnchors[0].x y: parentAnchors[0].y tags: [ 'component', 'diacritic' ] contours: 0: skeleton: true closed: false nodes: 0: x: anchors[0].x + ( 28 / 54 ) * thickness * 0.25 y: contours[0].nodes[1].y - 97 typeOut: 'line' expand: Object({ width: ( 28 / 54 ) * thickness angle: 180 + 'deg' distr: 0.75 }) 1: x: contours[0].nodes[0].x + 20 - ( 28 / 54 ) * thickness * 0.25 y: anchors[0].y typeIn: 'line' expand: Object({ width: 50 / 54 * thickness angle: 180 + 'deg' distr: 1 })
110498
exports.glyphs['caronSlovak'] = glyphName: '<NAME>' characterName: '<NAME>' anchors: 0: x: parentAnchors[0].x y: parentAnchors[0].y tags: [ 'component', 'diacritic' ] contours: 0: skeleton: true closed: false nodes: 0: x: anchors[0].x + ( 28 / 54 ) * thickness * 0.25 y: contours[0].nodes[1].y - 97 typeOut: 'line' expand: Object({ width: ( 28 / 54 ) * thickness angle: 180 + 'deg' distr: 0.75 }) 1: x: contours[0].nodes[0].x + 20 - ( 28 / 54 ) * thickness * 0.25 y: anchors[0].y typeIn: 'line' expand: Object({ width: 50 / 54 * thickness angle: 180 + 'deg' distr: 1 })
true
exports.glyphs['caronSlovak'] = glyphName: 'PI:NAME:<NAME>END_PI' characterName: 'PI:NAME:<NAME>END_PI' anchors: 0: x: parentAnchors[0].x y: parentAnchors[0].y tags: [ 'component', 'diacritic' ] contours: 0: skeleton: true closed: false nodes: 0: x: anchors[0].x + ( 28 / 54 ) * thickness * 0.25 y: contours[0].nodes[1].y - 97 typeOut: 'line' expand: Object({ width: ( 28 / 54 ) * thickness angle: 180 + 'deg' distr: 0.75 }) 1: x: contours[0].nodes[0].x + 20 - ( 28 / 54 ) * thickness * 0.25 y: anchors[0].y typeIn: 'line' expand: Object({ width: 50 / 54 * thickness angle: 180 + 'deg' distr: 1 })
[ { "context": "ArtworkAuctionView.__set__\n CURRENT_USER: 'existy'\n AUCTION:\n artwork_id: 'peter-al", "end": 2224, "score": 0.9851125478744507, "start": 2218, "tag": "USERNAME", "value": "existy" }, { "context": ".accounting = accounting\n @view.data.user...
src/desktop/apps/artwork/components/auction/test/view.coffee
kierangillen/force
0
accounting = require 'accounting' benv = require 'benv' moment = require 'moment' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' _ = require 'underscore' describe 'auction', -> before (done) -> sinon.stub global, 'setTimeout' benv.setup -> benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery'), analytics: track: sinon.stub() Backbone.$ = $ location.assign = sinon.stub() done() after -> benv.teardown() global.setTimeout.restore() beforeEach -> @ArtworkAuctionView = benv.requireWithJadeify( require.resolve('../view.coffee'), ['template'] ) @data = user: true me: bidders: [{ qualified_for_bidding: true }] artwork: id: 'peter-alexander-wedge-with-puff' is_in_auction: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: true is_preview: false is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' reserve_status: 'reserve_met' reserve_message: 'Reserve met' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 19 symbol: '$' bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 @view = new @ArtworkAuctionView data: @data describe '#parseBid', -> it 'Handles prices with cents', -> @view.parseBid '123.00' .should.equal 12300 it 'Handles prices w/ cents > 0', -> @view.parseBid '123.45' .should.equal 12345 it 'Handles commas', -> @view.parseBid '1,023.45' .should.equal 102345 it 'Handles dollar signs', -> @view.parseBid '$1,023.45' .should.equal 102345 it 'Handles numbers', -> @view.parseBid 1000 .should.equal 100000 describe '#submit', -> before -> @ArtworkAuctionView.__set__ CURRENT_USER: 'existy' AUCTION: artwork_id: 'peter-alexander-wedge-with-puff' minimum_next_bid: amount: '$60,000' cents: 6000000 after -> @ArtworkAuctionView.__set__ CURRENT_USER: null AUCTION: null beforeEach -> sinon.stub @ArtworkAuctionView::, 'redirectTo' @view.data.accounting = accounting @view.data.user = 'existy' @view.render() afterEach -> @view.redirectTo.restore() xit 'submits the bid by redirecting to the confirmation page', -> @view.$('[name="bid"]').replaceWith '<input name="bid" value="60,000">' @view.$('button').click() @view.redirectTo.args[0][0] .should.equal '/auction/los-angeles-modern-auctions-march-2015/bid/peter-alexander-wedge-with-puff?bid=6000000' describe '#render', -> describe 'open auction', -> it 'renders correctly', -> @view.data.accounting = accounting @view.render() @view.$el.html() .should.containEql '(19 bids, Reserve met)' @view.$('.artwork-auction__bid-form__button') .should.have.lengthOf 1 @view.$('.artwork-auction__buy-now') .should.have.lengthOf 0 @view.$('.js-artwork-auction-bid').attr('action') .should.equal "/auction/#{@view.data.artwork.sale.id}/bid/#{@view.data.artwork.id}" describe 'bid qualification', -> it 'renders a disabled "Registration Pending" button', -> @data.accounting = accounting @data.me = { bidders: [{ qualified_for_bidding: false }] } view = new @ArtworkAuctionView data: @data view.render() view.$('.artwork-auction__bid-form__button').text() .should.containEql 'Registration Pending' view.$('.js-artwork-auction-bid').attr('action') .should.equal "/artwork/#{@data.artwork.id}" it 'renders a disabled "Registration Closed" button', -> @data.accounting = accounting @data.artwork.sale.is_registration_closed = true @data.me = {} view = new @ArtworkAuctionView data: @data view.render() view.$('.artwork-auction__bid-form__button').text() .should.containEql 'Registration Closed' view.$('.js-artwork-auction-bid').attr('action') .should.equal "/artwork/#{@data.artwork.id}" it 'renders a auction registration button', -> @data.accounting = accounting @data.artwork.sale.require_bidder_approval = true @data.me = {} view = new @ArtworkAuctionView data: @data view.render() view.$('a.artwork-auction__bid-form__button').length.should.equal 1 view.$('a.artwork-auction__bid-form__button').attr('href') .should.equal "/auction-registration/#{@data.artwork.sale.id}" view.$('.js-artwork-auction-bid').attr('action') .should.equal "/artwork/#{@data.artwork.id}" it 'renders an open registration bid button', -> @data.accounting = accounting @data.me = {} view = new @ArtworkAuctionView data: @data view.render() view.$('a.artwork-auction__bid-form__button').length.should.equal 1 view.$('a.artwork-auction__bid-form__button').attr('href') .should.equal "/auction/#{@data.artwork.sale.id}/bid/#{@data.artwork.id}" view.$('.js-artwork-auction-bid').attr('action') .should.equal "/artwork/#{@data.artwork.id}" it 'renders a bid amount dropdown', -> @data.accounting = accounting @data.me = {} view = new @ArtworkAuctionView data: @data view.render() view.$('.artwork-auction__bid-form__max-bid').length.should.equal 1 view.$('.artwork-auction__bid-form__select').length.should.equal 1 view.$('.js-artwork-auction-max-bid').length.should.equal 1 describe 'post-bid messages', -> beforeEach -> @data = Object.assign(@data, { user: 'existy', accounting: accounting }) describe 'leading bidder & reserve met', -> it 'gives a winning message', -> @data.artwork.sale_artwork.reserve_status = 'reserve_met' @data.me = Object.assign @data.me, { lot_standing: is_leading_bidder: true most_recent_bid: max_bid: cents: 5500000 } view = new @ArtworkAuctionView data: @data view.render() view.$('.bid-status').text() .should.containEql 'Highest Bidder' view.$('.bid-status__is-winning').length.should.equal 1 describe 'leading bidder & reserve not met', -> it 'gives a reserve not met message', -> @data.artwork.sale_artwork.reserve_status = 'reserve_not_met' @data.me = Object.assign @data.me, { lot_standing: is_leading_bidder: true most_recent_bid: max_bid: cents: 5500000 } view = new @ArtworkAuctionView data: @data view.render() view.$('.bid-status').text() .should.containEql 'Highest bidder, Reserve not met' view.$('.bid-status__increase-bid').text() .should.equal 'Increase your max bid to win the lot' describe 'not leading bidder & reserve not met', -> it 'gives an outbid message', -> @data.artwork.sale_artwork.reserve_status = 'reserve_not_met' @data.me = Object.assign @data.me, { lot_standing: is_leading_bidder: false most_recent_bid: max_bid: cents: 5500000 } view = new @ArtworkAuctionView data: @data view.render() view.$('.bid-status').text() .should.containEql 'Outbid' view.$('.bid-status__increase-bid').text() .should.equal 'Increase your max bid to win the lot' describe 'not leading bidder & reserve met', -> it 'gives an outbid message', -> @data.artwork.sale_artwork.reserve_status = 'reserve_met' @data.me = Object.assign @data.me, { lot_standing: is_leading_bidder: false most_recent_bid: max_bid: cents: 5500000 } view = new @ArtworkAuctionView data: @data view.render() view.$('.bid-status').text() .should.containEql 'Outbid' view.$('.bid-status__increase-bid').text() .should.equal 'Increase your max bid to win the lot' describe 'preview auction', -> it 'renders correctly', -> data = accounting: accounting artwork: id: 'peter-alexander-wedge-with-puff' is_in_auction: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: false is_preview: true is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 0 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 view = new @ArtworkAuctionView data: data view.render() view.$('.artwork-auction__bid-status__bid').text() .should.equal 'Starting Bid' view.$('.artwork-auction__bid-form__button') .should.have.lengthOf 0 describe 'closed auction', -> it 'renders correctly', -> data = artwork: id: 'peter-alexander-wedge-with-puff' is_in_auction: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: false is_preview: false is_closed: true is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' reserve_message: 'Reserve met' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 19 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 view = new @ArtworkAuctionView data: data view.render() view.$el.html() .should.equal '<div class="artwork-auction__bid-status"><div class="artwork-auction__bid-status__closed">Bidding Closed</div></div>' describe 'buy now work', -> it 'renders correctly', -> data = accounting: accounting artwork: id: 'peter-alexander-wedge-with-puff' is_in_auction: true is_buy_nowable: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: true is_preview: false is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 0 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 view = new @ArtworkAuctionView data: data view.render() view.$('.artwork-auction__bid-form__button') .should.have.lengthOf 1 view.$('.artwork-auction__buy-now') .should.have.lengthOf 1 describe 'is sold', -> it 'renders correctly', -> data = accounting: accounting artwork: id: 'peter-alexander-wedge-with-puff' is_in_auction: true is_buy_nowable: true is_sold: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: true is_preview: false is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 0 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 view = new @ArtworkAuctionView data: data view.render() view.$('.artwork-auction__bid-form__button') .should.have.lengthOf 0 view.$('.artwork-auction__bid-status__closed') .should.have.lengthOf 1 describe '#acquire', -> stub = {} data = accounting: accounting artwork: id: 'peter-alexander-wedge-with-puff' is_in_auction: true is_buy_nowable: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: true is_preview: false is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 0 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 fakeEvent = preventDefault: -> null currentTarget: null it 'should show an auth modal if the user is not logged in', -> createOrderStub = sinon.stub() mediatorStub = trigger: sinon.stub() @ArtworkAuctionView.__set__ AUCTION: data mediator: mediatorStub createOrder: createOrderStub view = new @ArtworkAuctionView data: data view.acquire(fakeEvent) createOrderStub.callCount.should.equal(0) mediatorStub.trigger.args[0][0].should.equal 'open:auth' mediatorStub.trigger.args[0][1].mode.should.equal 'login' it 'should create a new order', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: order: id: "1234")) @ArtworkAuctionView.__set__ AUCTION: data createOrder: createOrderStub CurrentUser: orNull: -> { id: 'userid' } view = new @ArtworkAuctionView data: data view.acquire(fakeEvent).then -> createOrderStub.callCount.should.equal(1) location.assign.args[0][0].should.containEql("/orders/1234/shipping") it 'should show an error modal when buy now flag enabled but mutation fails', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: error: code: "1234")) errorModalMock = { render: sinon.spy(), renderBuyNowError: sinon.spy() } console.error = sinon.stub() @ArtworkAuctionView.__set__ errorModal: errorModalMock AUCTION: data createOrder: createOrderStub CurrentUser: orNull: -> { id: 'userid' } view = new @ArtworkAuctionView data: data view.acquire(fakeEvent).then -> createOrderStub.callCount.should.equal(1) errorModalMock.renderBuyNowError.calledOnce.should.be.ok()
153918
accounting = require 'accounting' benv = require 'benv' moment = require 'moment' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' _ = require 'underscore' describe 'auction', -> before (done) -> sinon.stub global, 'setTimeout' benv.setup -> benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery'), analytics: track: sinon.stub() Backbone.$ = $ location.assign = sinon.stub() done() after -> benv.teardown() global.setTimeout.restore() beforeEach -> @ArtworkAuctionView = benv.requireWithJadeify( require.resolve('../view.coffee'), ['template'] ) @data = user: true me: bidders: [{ qualified_for_bidding: true }] artwork: id: 'peter-alexander-wedge-with-puff' is_in_auction: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: true is_preview: false is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' reserve_status: 'reserve_met' reserve_message: 'Reserve met' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 19 symbol: '$' bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 @view = new @ArtworkAuctionView data: @data describe '#parseBid', -> it 'Handles prices with cents', -> @view.parseBid '123.00' .should.equal 12300 it 'Handles prices w/ cents > 0', -> @view.parseBid '123.45' .should.equal 12345 it 'Handles commas', -> @view.parseBid '1,023.45' .should.equal 102345 it 'Handles dollar signs', -> @view.parseBid '$1,023.45' .should.equal 102345 it 'Handles numbers', -> @view.parseBid 1000 .should.equal 100000 describe '#submit', -> before -> @ArtworkAuctionView.__set__ CURRENT_USER: 'existy' AUCTION: artwork_id: 'peter-alexander-wedge-with-puff' minimum_next_bid: amount: '$60,000' cents: 6000000 after -> @ArtworkAuctionView.__set__ CURRENT_USER: null AUCTION: null beforeEach -> sinon.stub @ArtworkAuctionView::, 'redirectTo' @view.data.accounting = accounting @view.data.user = 'existy' @view.render() afterEach -> @view.redirectTo.restore() xit 'submits the bid by redirecting to the confirmation page', -> @view.$('[name="bid"]').replaceWith '<input name="bid" value="60,000">' @view.$('button').click() @view.redirectTo.args[0][0] .should.equal '/auction/los-angeles-modern-auctions-march-2015/bid/peter-alexander-wedge-with-puff?bid=6000000' describe '#render', -> describe 'open auction', -> it 'renders correctly', -> @view.data.accounting = accounting @view.render() @view.$el.html() .should.containEql '(19 bids, Reserve met)' @view.$('.artwork-auction__bid-form__button') .should.have.lengthOf 1 @view.$('.artwork-auction__buy-now') .should.have.lengthOf 0 @view.$('.js-artwork-auction-bid').attr('action') .should.equal "/auction/#{@view.data.artwork.sale.id}/bid/#{@view.data.artwork.id}" describe 'bid qualification', -> it 'renders a disabled "Registration Pending" button', -> @data.accounting = accounting @data.me = { bidders: [{ qualified_for_bidding: false }] } view = new @ArtworkAuctionView data: @data view.render() view.$('.artwork-auction__bid-form__button').text() .should.containEql 'Registration Pending' view.$('.js-artwork-auction-bid').attr('action') .should.equal "/artwork/#{@data.artwork.id}" it 'renders a disabled "Registration Closed" button', -> @data.accounting = accounting @data.artwork.sale.is_registration_closed = true @data.me = {} view = new @ArtworkAuctionView data: @data view.render() view.$('.artwork-auction__bid-form__button').text() .should.containEql 'Registration Closed' view.$('.js-artwork-auction-bid').attr('action') .should.equal "/artwork/#{@data.artwork.id}" it 'renders a auction registration button', -> @data.accounting = accounting @data.artwork.sale.require_bidder_approval = true @data.me = {} view = new @ArtworkAuctionView data: @data view.render() view.$('a.artwork-auction__bid-form__button').length.should.equal 1 view.$('a.artwork-auction__bid-form__button').attr('href') .should.equal "/auction-registration/#{@data.artwork.sale.id}" view.$('.js-artwork-auction-bid').attr('action') .should.equal "/artwork/#{@data.artwork.id}" it 'renders an open registration bid button', -> @data.accounting = accounting @data.me = {} view = new @ArtworkAuctionView data: @data view.render() view.$('a.artwork-auction__bid-form__button').length.should.equal 1 view.$('a.artwork-auction__bid-form__button').attr('href') .should.equal "/auction/#{@data.artwork.sale.id}/bid/#{@data.artwork.id}" view.$('.js-artwork-auction-bid').attr('action') .should.equal "/artwork/#{@data.artwork.id}" it 'renders a bid amount dropdown', -> @data.accounting = accounting @data.me = {} view = new @ArtworkAuctionView data: @data view.render() view.$('.artwork-auction__bid-form__max-bid').length.should.equal 1 view.$('.artwork-auction__bid-form__select').length.should.equal 1 view.$('.js-artwork-auction-max-bid').length.should.equal 1 describe 'post-bid messages', -> beforeEach -> @data = Object.assign(@data, { user: 'existy', accounting: accounting }) describe 'leading bidder & reserve met', -> it 'gives a winning message', -> @data.artwork.sale_artwork.reserve_status = 'reserve_met' @data.me = Object.assign @data.me, { lot_standing: is_leading_bidder: true most_recent_bid: max_bid: cents: 5500000 } view = new @ArtworkAuctionView data: @data view.render() view.$('.bid-status').text() .should.containEql 'Highest Bidder' view.$('.bid-status__is-winning').length.should.equal 1 describe 'leading bidder & reserve not met', -> it 'gives a reserve not met message', -> @data.artwork.sale_artwork.reserve_status = 'reserve_not_met' @data.me = Object.assign @data.me, { lot_standing: is_leading_bidder: true most_recent_bid: max_bid: cents: 5500000 } view = new @ArtworkAuctionView data: @data view.render() view.$('.bid-status').text() .should.containEql 'Highest bidder, Reserve not met' view.$('.bid-status__increase-bid').text() .should.equal 'Increase your max bid to win the lot' describe 'not leading bidder & reserve not met', -> it 'gives an outbid message', -> @data.artwork.sale_artwork.reserve_status = 'reserve_not_met' @data.me = Object.assign @data.me, { lot_standing: is_leading_bidder: false most_recent_bid: max_bid: cents: 5500000 } view = new @ArtworkAuctionView data: @data view.render() view.$('.bid-status').text() .should.containEql 'Outbid' view.$('.bid-status__increase-bid').text() .should.equal 'Increase your max bid to win the lot' describe 'not leading bidder & reserve met', -> it 'gives an outbid message', -> @data.artwork.sale_artwork.reserve_status = 'reserve_met' @data.me = Object.assign @data.me, { lot_standing: is_leading_bidder: false most_recent_bid: max_bid: cents: 5500000 } view = new @ArtworkAuctionView data: @data view.render() view.$('.bid-status').text() .should.containEql 'Outbid' view.$('.bid-status__increase-bid').text() .should.equal 'Increase your max bid to win the lot' describe 'preview auction', -> it 'renders correctly', -> data = accounting: accounting artwork: id: 'peter-alexander-wedge-with-puff' is_in_auction: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: false is_preview: true is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 0 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 view = new @ArtworkAuctionView data: data view.render() view.$('.artwork-auction__bid-status__bid').text() .should.equal 'Starting Bid' view.$('.artwork-auction__bid-form__button') .should.have.lengthOf 0 describe 'closed auction', -> it 'renders correctly', -> data = artwork: id: 'peter-alexander-wedge-with-puff' is_in_auction: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: false is_preview: false is_closed: true is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' reserve_message: 'Reserve met' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 19 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 view = new @ArtworkAuctionView data: data view.render() view.$el.html() .should.equal '<div class="artwork-auction__bid-status"><div class="artwork-auction__bid-status__closed">Bidding Closed</div></div>' describe 'buy now work', -> it 'renders correctly', -> data = accounting: accounting artwork: id: '<NAME>-<NAME>ander-wedge-with-puff' is_in_auction: true is_buy_nowable: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: true is_preview: false is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: '<NAME>ter-alexander-wedge-with-puff' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 0 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 view = new @ArtworkAuctionView data: data view.render() view.$('.artwork-auction__bid-form__button') .should.have.lengthOf 1 view.$('.artwork-auction__buy-now') .should.have.lengthOf 1 describe 'is sold', -> it 'renders correctly', -> data = accounting: accounting artwork: id: '<NAME>-<NAME>-wedge-with-puff' is_in_auction: true is_buy_nowable: true is_sold: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: true is_preview: false is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 0 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 view = new @ArtworkAuctionView data: data view.render() view.$('.artwork-auction__bid-form__button') .should.have.lengthOf 0 view.$('.artwork-auction__bid-status__closed') .should.have.lengthOf 1 describe '#acquire', -> stub = {} data = accounting: accounting artwork: id: 'pe<NAME>-alexander-wedge-with-puff' is_in_auction: true is_buy_nowable: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: true is_preview: false is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 0 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 fakeEvent = preventDefault: -> null currentTarget: null it 'should show an auth modal if the user is not logged in', -> createOrderStub = sinon.stub() mediatorStub = trigger: sinon.stub() @ArtworkAuctionView.__set__ AUCTION: data mediator: mediatorStub createOrder: createOrderStub view = new @ArtworkAuctionView data: data view.acquire(fakeEvent) createOrderStub.callCount.should.equal(0) mediatorStub.trigger.args[0][0].should.equal 'open:auth' mediatorStub.trigger.args[0][1].mode.should.equal 'login' it 'should create a new order', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: order: id: "1234")) @ArtworkAuctionView.__set__ AUCTION: data createOrder: createOrderStub CurrentUser: orNull: -> { id: 'userid' } view = new @ArtworkAuctionView data: data view.acquire(fakeEvent).then -> createOrderStub.callCount.should.equal(1) location.assign.args[0][0].should.containEql("/orders/1234/shipping") it 'should show an error modal when buy now flag enabled but mutation fails', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: error: code: "1234")) errorModalMock = { render: sinon.spy(), renderBuyNowError: sinon.spy() } console.error = sinon.stub() @ArtworkAuctionView.__set__ errorModal: errorModalMock AUCTION: data createOrder: createOrderStub CurrentUser: orNull: -> { id: 'userid' } view = new @ArtworkAuctionView data: data view.acquire(fakeEvent).then -> createOrderStub.callCount.should.equal(1) errorModalMock.renderBuyNowError.calledOnce.should.be.ok()
true
accounting = require 'accounting' benv = require 'benv' moment = require 'moment' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' _ = require 'underscore' describe 'auction', -> before (done) -> sinon.stub global, 'setTimeout' benv.setup -> benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery'), analytics: track: sinon.stub() Backbone.$ = $ location.assign = sinon.stub() done() after -> benv.teardown() global.setTimeout.restore() beforeEach -> @ArtworkAuctionView = benv.requireWithJadeify( require.resolve('../view.coffee'), ['template'] ) @data = user: true me: bidders: [{ qualified_for_bidding: true }] artwork: id: 'peter-alexander-wedge-with-puff' is_in_auction: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: true is_preview: false is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' reserve_status: 'reserve_met' reserve_message: 'Reserve met' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 19 symbol: '$' bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 @view = new @ArtworkAuctionView data: @data describe '#parseBid', -> it 'Handles prices with cents', -> @view.parseBid '123.00' .should.equal 12300 it 'Handles prices w/ cents > 0', -> @view.parseBid '123.45' .should.equal 12345 it 'Handles commas', -> @view.parseBid '1,023.45' .should.equal 102345 it 'Handles dollar signs', -> @view.parseBid '$1,023.45' .should.equal 102345 it 'Handles numbers', -> @view.parseBid 1000 .should.equal 100000 describe '#submit', -> before -> @ArtworkAuctionView.__set__ CURRENT_USER: 'existy' AUCTION: artwork_id: 'peter-alexander-wedge-with-puff' minimum_next_bid: amount: '$60,000' cents: 6000000 after -> @ArtworkAuctionView.__set__ CURRENT_USER: null AUCTION: null beforeEach -> sinon.stub @ArtworkAuctionView::, 'redirectTo' @view.data.accounting = accounting @view.data.user = 'existy' @view.render() afterEach -> @view.redirectTo.restore() xit 'submits the bid by redirecting to the confirmation page', -> @view.$('[name="bid"]').replaceWith '<input name="bid" value="60,000">' @view.$('button').click() @view.redirectTo.args[0][0] .should.equal '/auction/los-angeles-modern-auctions-march-2015/bid/peter-alexander-wedge-with-puff?bid=6000000' describe '#render', -> describe 'open auction', -> it 'renders correctly', -> @view.data.accounting = accounting @view.render() @view.$el.html() .should.containEql '(19 bids, Reserve met)' @view.$('.artwork-auction__bid-form__button') .should.have.lengthOf 1 @view.$('.artwork-auction__buy-now') .should.have.lengthOf 0 @view.$('.js-artwork-auction-bid').attr('action') .should.equal "/auction/#{@view.data.artwork.sale.id}/bid/#{@view.data.artwork.id}" describe 'bid qualification', -> it 'renders a disabled "Registration Pending" button', -> @data.accounting = accounting @data.me = { bidders: [{ qualified_for_bidding: false }] } view = new @ArtworkAuctionView data: @data view.render() view.$('.artwork-auction__bid-form__button').text() .should.containEql 'Registration Pending' view.$('.js-artwork-auction-bid').attr('action') .should.equal "/artwork/#{@data.artwork.id}" it 'renders a disabled "Registration Closed" button', -> @data.accounting = accounting @data.artwork.sale.is_registration_closed = true @data.me = {} view = new @ArtworkAuctionView data: @data view.render() view.$('.artwork-auction__bid-form__button').text() .should.containEql 'Registration Closed' view.$('.js-artwork-auction-bid').attr('action') .should.equal "/artwork/#{@data.artwork.id}" it 'renders a auction registration button', -> @data.accounting = accounting @data.artwork.sale.require_bidder_approval = true @data.me = {} view = new @ArtworkAuctionView data: @data view.render() view.$('a.artwork-auction__bid-form__button').length.should.equal 1 view.$('a.artwork-auction__bid-form__button').attr('href') .should.equal "/auction-registration/#{@data.artwork.sale.id}" view.$('.js-artwork-auction-bid').attr('action') .should.equal "/artwork/#{@data.artwork.id}" it 'renders an open registration bid button', -> @data.accounting = accounting @data.me = {} view = new @ArtworkAuctionView data: @data view.render() view.$('a.artwork-auction__bid-form__button').length.should.equal 1 view.$('a.artwork-auction__bid-form__button').attr('href') .should.equal "/auction/#{@data.artwork.sale.id}/bid/#{@data.artwork.id}" view.$('.js-artwork-auction-bid').attr('action') .should.equal "/artwork/#{@data.artwork.id}" it 'renders a bid amount dropdown', -> @data.accounting = accounting @data.me = {} view = new @ArtworkAuctionView data: @data view.render() view.$('.artwork-auction__bid-form__max-bid').length.should.equal 1 view.$('.artwork-auction__bid-form__select').length.should.equal 1 view.$('.js-artwork-auction-max-bid').length.should.equal 1 describe 'post-bid messages', -> beforeEach -> @data = Object.assign(@data, { user: 'existy', accounting: accounting }) describe 'leading bidder & reserve met', -> it 'gives a winning message', -> @data.artwork.sale_artwork.reserve_status = 'reserve_met' @data.me = Object.assign @data.me, { lot_standing: is_leading_bidder: true most_recent_bid: max_bid: cents: 5500000 } view = new @ArtworkAuctionView data: @data view.render() view.$('.bid-status').text() .should.containEql 'Highest Bidder' view.$('.bid-status__is-winning').length.should.equal 1 describe 'leading bidder & reserve not met', -> it 'gives a reserve not met message', -> @data.artwork.sale_artwork.reserve_status = 'reserve_not_met' @data.me = Object.assign @data.me, { lot_standing: is_leading_bidder: true most_recent_bid: max_bid: cents: 5500000 } view = new @ArtworkAuctionView data: @data view.render() view.$('.bid-status').text() .should.containEql 'Highest bidder, Reserve not met' view.$('.bid-status__increase-bid').text() .should.equal 'Increase your max bid to win the lot' describe 'not leading bidder & reserve not met', -> it 'gives an outbid message', -> @data.artwork.sale_artwork.reserve_status = 'reserve_not_met' @data.me = Object.assign @data.me, { lot_standing: is_leading_bidder: false most_recent_bid: max_bid: cents: 5500000 } view = new @ArtworkAuctionView data: @data view.render() view.$('.bid-status').text() .should.containEql 'Outbid' view.$('.bid-status__increase-bid').text() .should.equal 'Increase your max bid to win the lot' describe 'not leading bidder & reserve met', -> it 'gives an outbid message', -> @data.artwork.sale_artwork.reserve_status = 'reserve_met' @data.me = Object.assign @data.me, { lot_standing: is_leading_bidder: false most_recent_bid: max_bid: cents: 5500000 } view = new @ArtworkAuctionView data: @data view.render() view.$('.bid-status').text() .should.containEql 'Outbid' view.$('.bid-status__increase-bid').text() .should.equal 'Increase your max bid to win the lot' describe 'preview auction', -> it 'renders correctly', -> data = accounting: accounting artwork: id: 'peter-alexander-wedge-with-puff' is_in_auction: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: false is_preview: true is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 0 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 view = new @ArtworkAuctionView data: data view.render() view.$('.artwork-auction__bid-status__bid').text() .should.equal 'Starting Bid' view.$('.artwork-auction__bid-form__button') .should.have.lengthOf 0 describe 'closed auction', -> it 'renders correctly', -> data = artwork: id: 'peter-alexander-wedge-with-puff' is_in_auction: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: false is_preview: false is_closed: true is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' reserve_message: 'Reserve met' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 19 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 view = new @ArtworkAuctionView data: data view.render() view.$el.html() .should.equal '<div class="artwork-auction__bid-status"><div class="artwork-auction__bid-status__closed">Bidding Closed</div></div>' describe 'buy now work', -> it 'renders correctly', -> data = accounting: accounting artwork: id: 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PIander-wedge-with-puff' is_in_auction: true is_buy_nowable: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: true is_preview: false is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'PI:NAME:<NAME>END_PIter-alexander-wedge-with-puff' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 0 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 view = new @ArtworkAuctionView data: data view.render() view.$('.artwork-auction__bid-form__button') .should.have.lengthOf 1 view.$('.artwork-auction__buy-now') .should.have.lengthOf 1 describe 'is sold', -> it 'renders correctly', -> data = accounting: accounting artwork: id: 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI-wedge-with-puff' is_in_auction: true is_buy_nowable: true is_sold: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: true is_preview: false is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 0 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 view = new @ArtworkAuctionView data: data view.render() view.$('.artwork-auction__bid-form__button') .should.have.lengthOf 0 view.$('.artwork-auction__bid-status__closed') .should.have.lengthOf 1 describe '#acquire', -> stub = {} data = accounting: accounting artwork: id: 'pePI:NAME:<NAME>END_PI-alexander-wedge-with-puff' is_in_auction: true is_buy_nowable: true sale: id: 'los-angeles-modern-auctions-march-2015' name: 'Los Angeles Modern Auctions - March 2015' is_open: true is_preview: false is_closed: false is_auction: true is_auction_promo: false is_with_buyers_premium: true sale_artwork: id: 'peter-alexander-wedge-with-puff' estimate: '$7,000–$9,000' current_bid: amount: '$55,000' counts: bidder_positions: 0 bid_increments: [100, 200] minimum_next_bid: amount: '$60,000' cents: 6000000 fakeEvent = preventDefault: -> null currentTarget: null it 'should show an auth modal if the user is not logged in', -> createOrderStub = sinon.stub() mediatorStub = trigger: sinon.stub() @ArtworkAuctionView.__set__ AUCTION: data mediator: mediatorStub createOrder: createOrderStub view = new @ArtworkAuctionView data: data view.acquire(fakeEvent) createOrderStub.callCount.should.equal(0) mediatorStub.trigger.args[0][0].should.equal 'open:auth' mediatorStub.trigger.args[0][1].mode.should.equal 'login' it 'should create a new order', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: order: id: "1234")) @ArtworkAuctionView.__set__ AUCTION: data createOrder: createOrderStub CurrentUser: orNull: -> { id: 'userid' } view = new @ArtworkAuctionView data: data view.acquire(fakeEvent).then -> createOrderStub.callCount.should.equal(1) location.assign.args[0][0].should.containEql("/orders/1234/shipping") it 'should show an error modal when buy now flag enabled but mutation fails', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: error: code: "1234")) errorModalMock = { render: sinon.spy(), renderBuyNowError: sinon.spy() } console.error = sinon.stub() @ArtworkAuctionView.__set__ errorModal: errorModalMock AUCTION: data createOrder: createOrderStub CurrentUser: orNull: -> { id: 'userid' } view = new @ArtworkAuctionView data: data view.acquire(fakeEvent).then -> createOrderStub.callCount.should.equal(1) errorModalMock.renderBuyNowError.calledOnce.should.be.ok()
[ { "context": "u a useful user story to implement\n#\n# Author:\n# KevinTraver\n#\n\nscreen_name = \"GoatUserStories\"\n_ = requ", "end": 455, "score": 0.8862618207931519, "start": 450, "tag": "NAME", "value": "Kevin" }, { "context": "eful user story to implement\n#\n# Author:\n# ...
scripts/userstory.coffee
adewinter/hubot-ralph
4
# Description: # gets random tweet from @GoatUserStory # based on https://github.com/github/hubot-scripts/blob/master/src/scripts/twitter.coffee # # Dependencies: # "twit", "underscore" # # Configuration: # HUBOT_TWITTER_CONSUMER_KEY # HUBOT_TWITTER_CONSUMER_SECRET # HUBOT_TWITTER_ACCESS_TOKEN # HUBOT_TWITTER_ACCESS_TOKEN_SECRET # # Commands: # hubot <ticket|user story> - Gives you a useful user story to implement # # Author: # KevinTraver # screen_name = "GoatUserStories" _ = require "underscore" Twit = require "twit" config = consumer_key: process.env.TWITTER_CONSUMER_KEY consumer_secret: process.env.TWITTER_CONSUMER_SECRET access_token: process.env.TWITTER_ACCESS_TOKEN_KEY access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET module.exports = (robot) -> twit = undefined robot.respond /ticket|user story/i, (msg) -> unless config.consumer_key msg.reply "Please set the TWITTER_CONSUMER_KEY environment variable." return unless config.consumer_secret msg.reply "Please set the TWITTER_CONSUMER_SECRET environment variable." return unless config.access_token msg.reply "Please set the TWITTER_ACCESS_TOKEN environment variable." return unless config.access_token_secret msg.reply "Please set the TWITTER_ACCESS_TOKEN_SECRET environment variable." return unless twit twit = new Twit config twit.get "statuses/user_timeline", screen_name: screen_name count: Math.floor(Math.random() * 150) + 1 include_rts: false exclude_replies: true , (err, reply) -> return msg.reply "Error" if err return msg.reply "https://twitter.com/#{screen_name}/status/#{_.last(reply)['id_str']}" if reply[0]['id_str']
179772
# Description: # gets random tweet from @GoatUserStory # based on https://github.com/github/hubot-scripts/blob/master/src/scripts/twitter.coffee # # Dependencies: # "twit", "underscore" # # Configuration: # HUBOT_TWITTER_CONSUMER_KEY # HUBOT_TWITTER_CONSUMER_SECRET # HUBOT_TWITTER_ACCESS_TOKEN # HUBOT_TWITTER_ACCESS_TOKEN_SECRET # # Commands: # hubot <ticket|user story> - Gives you a useful user story to implement # # Author: # <NAME>Tra<NAME> # screen_name = "GoatUserStories" _ = require "underscore" Twit = require "twit" config = consumer_key: process.env.TWITTER_CONSUMER_KEY consumer_secret: process.env.TWITTER_CONSUMER_SECRET access_token: process.env.TWITTER_ACCESS_TOKEN_KEY access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET module.exports = (robot) -> twit = undefined robot.respond /ticket|user story/i, (msg) -> unless config.consumer_key msg.reply "Please set the TWITTER_CONSUMER_KEY environment variable." return unless config.consumer_secret msg.reply "Please set the TWITTER_CONSUMER_SECRET environment variable." return unless config.access_token msg.reply "Please set the TWITTER_ACCESS_TOKEN environment variable." return unless config.access_token_secret msg.reply "Please set the TWITTER_ACCESS_TOKEN_SECRET environment variable." return unless twit twit = new Twit config twit.get "statuses/user_timeline", screen_name: screen_name count: Math.floor(Math.random() * 150) + 1 include_rts: false exclude_replies: true , (err, reply) -> return msg.reply "Error" if err return msg.reply "https://twitter.com/#{screen_name}/status/#{_.last(reply)['id_str']}" if reply[0]['id_str']
true
# Description: # gets random tweet from @GoatUserStory # based on https://github.com/github/hubot-scripts/blob/master/src/scripts/twitter.coffee # # Dependencies: # "twit", "underscore" # # Configuration: # HUBOT_TWITTER_CONSUMER_KEY # HUBOT_TWITTER_CONSUMER_SECRET # HUBOT_TWITTER_ACCESS_TOKEN # HUBOT_TWITTER_ACCESS_TOKEN_SECRET # # Commands: # hubot <ticket|user story> - Gives you a useful user story to implement # # Author: # PI:NAME:<NAME>END_PITraPI:NAME:<NAME>END_PI # screen_name = "GoatUserStories" _ = require "underscore" Twit = require "twit" config = consumer_key: process.env.TWITTER_CONSUMER_KEY consumer_secret: process.env.TWITTER_CONSUMER_SECRET access_token: process.env.TWITTER_ACCESS_TOKEN_KEY access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET module.exports = (robot) -> twit = undefined robot.respond /ticket|user story/i, (msg) -> unless config.consumer_key msg.reply "Please set the TWITTER_CONSUMER_KEY environment variable." return unless config.consumer_secret msg.reply "Please set the TWITTER_CONSUMER_SECRET environment variable." return unless config.access_token msg.reply "Please set the TWITTER_ACCESS_TOKEN environment variable." return unless config.access_token_secret msg.reply "Please set the TWITTER_ACCESS_TOKEN_SECRET environment variable." return unless twit twit = new Twit config twit.get "statuses/user_timeline", screen_name: screen_name count: Math.floor(Math.random() * 150) + 1 include_rts: false exclude_replies: true , (err, reply) -> return msg.reply "Error" if err return msg.reply "https://twitter.com/#{screen_name}/status/#{_.last(reply)['id_str']}" if reply[0]['id_str']
[ { "context": "# Copyright (C) 2015, Radmon.\n# Use of this source code is governed by the MIT", "end": 28, "score": 0.8786696195602417, "start": 22, "tag": "NAME", "value": "Radmon" }, { "context": " 'open'\n\n $.fn.collapse = (option) ->\n key = 'tm.collapse'\n this.each ->\n...
coffee/collapse.coffee
radonlab/papery-theme
0
# Copyright (C) 2015, Radmon. # Use of this source code is governed by the MIT license that can be # found in the LICENSE file. module.exports = ($) -> 'use strict' target = '.collapse' class Collapse constructor: (element) -> @element = element toggle: () -> @element.toggleClass 'open' $.fn.collapse = (option) -> key = 'tm.collapse' this.each -> element = $(this) control = element.data key if not control control = new Collapse element element.data key, control control[option].call control if typeof option == 'string' FindTarget = (trigger) -> guide = trigger.attr 'data-target' if guide then $(guide) else trigger.next target $(document) .on 'click touch', '[data-trigger="collapse"]', (e) -> e.preventDefault() FindTarget $(this) .collapse 'toggle'
112973
# Copyright (C) 2015, <NAME>. # Use of this source code is governed by the MIT license that can be # found in the LICENSE file. module.exports = ($) -> 'use strict' target = '.collapse' class Collapse constructor: (element) -> @element = element toggle: () -> @element.toggleClass 'open' $.fn.collapse = (option) -> key = '<KEY>' this.each -> element = $(this) control = element.data key if not control control = new Collapse element element.data key, control control[option].call control if typeof option == 'string' FindTarget = (trigger) -> guide = trigger.attr 'data-target' if guide then $(guide) else trigger.next target $(document) .on 'click touch', '[data-trigger="collapse"]', (e) -> e.preventDefault() FindTarget $(this) .collapse 'toggle'
true
# Copyright (C) 2015, PI:NAME:<NAME>END_PI. # Use of this source code is governed by the MIT license that can be # found in the LICENSE file. module.exports = ($) -> 'use strict' target = '.collapse' class Collapse constructor: (element) -> @element = element toggle: () -> @element.toggleClass 'open' $.fn.collapse = (option) -> key = 'PI:KEY:<KEY>END_PI' this.each -> element = $(this) control = element.data key if not control control = new Collapse element element.data key, control control[option].call control if typeof option == 'string' FindTarget = (trigger) -> guide = trigger.attr 'data-target' if guide then $(guide) else trigger.next target $(document) .on 'click touch', '[data-trigger="collapse"]', (e) -> e.preventDefault() FindTarget $(this) .collapse 'toggle'
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9990760684013367, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/pummel/test-net-timeout.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # 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. common = require("../common") assert = require("assert") net = require("net") exchanges = 0 starttime = null timeouttime = null timeout = 1000 echo_server = net.createServer((socket) -> socket.setTimeout timeout socket.on "timeout", -> console.log "server timeout" timeouttime = new Date console.dir timeouttime socket.destroy() return socket.on "error", (e) -> throw new Error("Server side socket should not get error. " + "We disconnect willingly.")return socket.on "data", (d) -> console.log d socket.write d return socket.on "end", -> socket.end() return return ) echo_server.listen common.PORT, -> console.log "server listening at " + common.PORT client = net.createConnection(common.PORT) client.setEncoding "UTF8" client.setTimeout 0 # disable the timeout for client client.on "connect", -> console.log "client connected." client.write "hello\r\n" return client.on "data", (chunk) -> assert.equal "hello\r\n", chunk if exchanges++ < 5 setTimeout (-> console.log "client write \"hello\"" client.write "hello\r\n" return ), 500 if exchanges is 5 console.log "wait for timeout - should come in " + timeout + " ms" starttime = new Date console.dir starttime return client.on "timeout", -> throw new Error("client timeout - this shouldn't happen")return client.on "end", -> console.log "client end" client.end() return client.on "close", -> console.log "client disconnect" echo_server.close() return return process.on "exit", -> assert.ok starttime? assert.ok timeouttime? diff = timeouttime - starttime console.log "diff = " + diff assert.ok timeout < diff # Allow for 800 milliseconds more assert.ok diff < timeout + 800 return
225548
# Copyright <NAME>, Inc. and other Node contributors. # # 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. common = require("../common") assert = require("assert") net = require("net") exchanges = 0 starttime = null timeouttime = null timeout = 1000 echo_server = net.createServer((socket) -> socket.setTimeout timeout socket.on "timeout", -> console.log "server timeout" timeouttime = new Date console.dir timeouttime socket.destroy() return socket.on "error", (e) -> throw new Error("Server side socket should not get error. " + "We disconnect willingly.")return socket.on "data", (d) -> console.log d socket.write d return socket.on "end", -> socket.end() return return ) echo_server.listen common.PORT, -> console.log "server listening at " + common.PORT client = net.createConnection(common.PORT) client.setEncoding "UTF8" client.setTimeout 0 # disable the timeout for client client.on "connect", -> console.log "client connected." client.write "hello\r\n" return client.on "data", (chunk) -> assert.equal "hello\r\n", chunk if exchanges++ < 5 setTimeout (-> console.log "client write \"hello\"" client.write "hello\r\n" return ), 500 if exchanges is 5 console.log "wait for timeout - should come in " + timeout + " ms" starttime = new Date console.dir starttime return client.on "timeout", -> throw new Error("client timeout - this shouldn't happen")return client.on "end", -> console.log "client end" client.end() return client.on "close", -> console.log "client disconnect" echo_server.close() return return process.on "exit", -> assert.ok starttime? assert.ok timeouttime? diff = timeouttime - starttime console.log "diff = " + diff assert.ok timeout < diff # Allow for 800 milliseconds more assert.ok diff < timeout + 800 return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # 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. common = require("../common") assert = require("assert") net = require("net") exchanges = 0 starttime = null timeouttime = null timeout = 1000 echo_server = net.createServer((socket) -> socket.setTimeout timeout socket.on "timeout", -> console.log "server timeout" timeouttime = new Date console.dir timeouttime socket.destroy() return socket.on "error", (e) -> throw new Error("Server side socket should not get error. " + "We disconnect willingly.")return socket.on "data", (d) -> console.log d socket.write d return socket.on "end", -> socket.end() return return ) echo_server.listen common.PORT, -> console.log "server listening at " + common.PORT client = net.createConnection(common.PORT) client.setEncoding "UTF8" client.setTimeout 0 # disable the timeout for client client.on "connect", -> console.log "client connected." client.write "hello\r\n" return client.on "data", (chunk) -> assert.equal "hello\r\n", chunk if exchanges++ < 5 setTimeout (-> console.log "client write \"hello\"" client.write "hello\r\n" return ), 500 if exchanges is 5 console.log "wait for timeout - should come in " + timeout + " ms" starttime = new Date console.dir starttime return client.on "timeout", -> throw new Error("client timeout - this shouldn't happen")return client.on "end", -> console.log "client end" client.end() return client.on "close", -> console.log "client disconnect" echo_server.close() return return process.on "exit", -> assert.ok starttime? assert.ok timeouttime? diff = timeouttime - starttime console.log "diff = " + diff assert.ok timeout < diff # Allow for 800 milliseconds more assert.ok diff < timeout + 800 return
[ { "context": " base or= randhex(3)\n opts =\n username : \"test_#{base}\"\n password : randhex(6)\n email ", "end": 1577, "score": 0.9918482303619385, "start": 1572, "tag": "USERNAME", "value": "test_" }, { "context": "=\n username : \"test_#{base}\"\n pa...
test/lib/user.iced
substack/keybase-client
1
# # A file that wraps the creation and management of test # users, potentially with features to access test twitter # and github accounts. As such, it might need access to # a configuration file, since we don't want to push our # test twitter/github credentials to github. # {prng} = require 'crypto' {init,config} = require './config' path = require 'path' iutils = require 'iced-utils' {rm_r,mkdir_p} = iutils.fs {a_json_parse,athrow} = iutils.util {make_esc} = require 'iced-error' log = require '../../lib/log' gpgw = require 'gpg-wrapper' {AltKeyRing} = gpgw.keyring {run} = require 'iced-spawn' keypool = require './keypool' {Engine} = require 'iced-expect' {tweet_api} = require './twitter' {gist_api} = require './github' fs = require 'fs' {Rendezvous} = require('iced-coffee-script').iced #================================================================== strip = (x) -> if (m = x.match /^(\s*)([\S\s]*?)(\s*)$/) then m[2] else x #================================================================== randhex = (len) -> prng(len).toString('hex') #================================================================== assert_kb_ok = (rc) -> if rc is 0 then null else new Error "Non-ok result from keybase: #{rc}" #================================================================== exports.User = class User constructor : ({@username, @email, @password, @homedir}) -> @keyring = null @_state = { proved : {} } @_proofs = {} users().push @ #--------------- @generate : (base) -> base or= randhex(3) opts = username : "test_#{base}" password : randhex(6) email : "test+#{base}@test.keybase.io" homedir : path.join(config().scratch_dir(), "home_#{base}") new User opts #----------------- check_if_exists : (cb) -> tmpcb = (err) -> cb false esc = make_esc tmpcb, "User::check_if_exists" await fs.stat @homedir, esc defer() await fs.stat @keyring_dir(), esc defer() await fs.stat path.join(@homedir, ".keybase", "config.json"), esc defer() cb true #----------------- init : (cb) -> esc = make_esc cb, "User::init" await @make_homedir esc defer() await @make_keyring esc defer() await @grab_key esc defer() await @write_config esc defer() @_state.init = true cb null #----------------- write_config : (cb) -> esc = make_esc cb, "User::write_config" await @keybase { args : [ "config" ], quiet : true }, esc defer() args = [ "config" "--json" "server" JSON.stringify(config().server_obj()) ] await @keybase { args, quiet : true }, esc defer() cb null #----------------- make_homedir : (cb) -> await mkdir_p @homedir, null, defer err cb err #----------------- keyring_dir : () -> path.join(@homedir, ".gnupg") #----------------- _keybase_cmd : (inargs) -> inargs.args = [ "--homedir", @homedir ].concat inargs.args config().keybase_cmd inargs log.debug "Running keybase: " + JSON.stringify(inargs) return inargs #----------------- keybase : (inargs, cb) -> @_keybase_cmd inargs await run inargs, defer err, out cb err, out #----------------- keybase_expect : (args) -> inargs = { args, opts : {} } if config().debug inargs.opts = debug : { stdout : true } passthrough : { stderr : true } @_keybase_cmd inargs eng = new Engine inargs eng.run() return eng #----------------- make_keyring : (cb) -> await AltKeyRing.make @keyring_dir(), defer err, @keyring cb err #----------------- gpg : (args, cb) -> @keyring.gpg args, cb #----------------- grab_key : (cb) -> esc = make_esc cb, "User::grab_key" await keypool.grab esc defer tmp await tmp.load esc defer() @key = tmp.copy_to_keyring @keyring await @key.save esc defer() cb null #----------------- push_key : (cb) -> await @keybase { args : [ "push", "--skip-add-email", @key.fingerprint() ], quiet : true }, defer err @_state.pushed = true unless err? cb err #----------------- signup : (cb) -> eng = @keybase_expect [ "signup" ] await eng.conversation [ { expect : "Your email: "} { sendline : @email } { expect : "Invitation code \\(leave blank if you don't have one\\): " } { sendline : "202020202020202020202020" } { expect : "Your desired username: " } { sendline : @username } { expect : "Your login passphrase: " } { sendline : @password } { expect : "Repeat to confirm: " } { sendline : @password }, ], defer err unless err? await eng.wait defer rc if rc isnt 0 err = new Error "Command-line client failed with code #{rc}" else @_state.signedup = true cb err #----------------- prove : ({which, search_regex, http_action}, cb) -> esc = make_esc cb, "User::prove" eng = @keybase_expect [ "prove", which ] @twitter = {} unless (acct = config().get_dummy_account which)? await athrow (new Error "No dummy accounts available for '#{which}'"), esc defer() await eng.expect { pattern : (new RegExp "Your username on #{which}: ", "i") }, esc defer() await eng.sendline acct.username, esc defer() await eng.expect { pattern : (new RegExp "Check #{which} now\\? \\[Y/n\\] ", "i") }, esc defer data if (m = data.toString('utf8').match search_regex)? proof = m[1] else await athrow (new Error "Didn't get a #{which} text from the CLI"), esc defer() log.debug "+ Doing HTTP action #{acct.username}@#{which}" await http_action acct, proof, esc defer proof_id log.debug "- Did HTTP action, completed w/ proof_id=#{proof_id}" await eng.sendline "y", esc defer() eng.expect { repeat : true, pattern : (new RegExp "Check #{which} again now\\? \\[Y/n\\] ", "i") }, (err, data, source) => log.info "Trying #{which} again, maybe they're slow to update?" await setTimeout defer(), 1000 await eng.sendline "y", defer err log.warn "Failed to send a yes: #{err.message}" if err? await eng.wait defer rc if rc isnt 0 err = new Error "Error from keybase prove: #{rc}" else @_proofs[which] = { proof, proof_id, acct } @_state.proved[which] = true cb err #----------------- accounts : () -> unless (out = @_status?.user?.proofs)? out = {} for k,v of @_proofs out[k] = v.acct.username return out #----------------- # Load proofs in from the output of `keybase status` _load_proofs : (obj) -> if (d = obj?.user?.proofs)? for k,v of d @_proofs[k] = { acct : { username : v } } #----------------- assertions : () -> d = @accounts() out = [] for k,v of d out.push("--assert", [k, v].join(":") ) return out #----------------- prove_twitter : (cb) -> opts = which : "twitter" search_regex : /Please.*tweet.*the following:\s+(\S.*?)\n/ http_action : tweet_api await @prove opts, defer err cb err #----------------- prove_github : (cb) -> opts = which : "github" search_regex : /Please.*?post the following Gist, and name it.*?:\s+(\S[\s\S]*?)\n\nCheck GitHub now\?/i http_action : gist_api await @prove opts, defer err cb err #----------------- has_live_key : () -> @_state.pushed and @_state.signedup and not(@_state.revoked) #----------------- full_monty : (T, {twitter, github, save_pw}, gcb) -> un = @username esc = (which, lcb) -> (err, args...) -> T.waypoint "fully_monty #{un}: #{which}" T.no_error err if err? then gcb err else lcb args... await @init esc('init', defer()) await @signup esc('signup', defer()) await @push_key esc('push_key', defer()) await @list_signatures esc('list_signatures', defer()) await @prove_github esc('prove_github', defer()) if github await @prove_twitter esc('prove_twitter', defer()) if twitter await @list_signatures esc('list_signatures', defer()) await @write_pw esc('write_pw', defer()) if save_pw gcb null #----------------- check_proofs : (output, cb) -> err = null for k,v of @_proofs x = new RegExp "#{v.acct.username}.*#{k}.*https://.*#{k}\\.com/.*#{v.proof_id}" unless output.match x err = new Error "Failed to find proof for #{k} for user: #{v.acct.username}" break cb err #----------------- follow : (followee, {remote}, cb) -> esc = make_esc cb, "User::follow" un = followee.username eng = @keybase_expect [ "track", un ] eng.expect { pattern : new RegExp("Is this the #{un} you wanted\\? \\[y\\/N\\] ") }, (err, data, src) -> unless err? await followee.check_proofs eng.stderr().toString('utf8'), defer err if err? log.warn "Failed to find the correct proofs" await eng.sendline "n", defer err else await eng.sendline "y", defer err eng.expect { pattern : /Permanently track this user, and write proof to server\? \[Y\/n\] / }, (err, data, src) -> unless err? await eng.sendline (if remote then "y" else "n"), esc defer() await eng.wait defer rc err = assert_kb_ok rc cb err #----------------- id : (followee, cb) -> esc = make_esc cb, "User::id" un = followee.username eng = @keybase_expect [ "id", un ] await eng.wait defer rc err = assert_kb_ok rc await athrow err, esc defer() if err? stderr = eng.stderr().toString('utf8') await followee.check_proofs stderr, defer err if err? log.warn "Failed to find the correct proofs; got: " log.warn stderr cb err #----------------- list_signatures : (cb) -> esc = make_esc cb, "User::list_signatures" eng = @keybase_expect [ "list-signatures" ] await eng.wait defer rc err = assert_kb_ok rc cb err #----------------- unfollow : (followee, cb) -> esc = make_esc cb, "User::follow" eng = @keybase_expect [ "untrack", "--remove-key", followee.username ] await eng.wait defer rc err = assert_kb_ok rc cb err #----------------- write_pw : (cb) -> esc = make_esc cb, "User::write_pw" await @keybase { args : [ "config" ], quiet : true }, esc defer() args = [ "config" "user.passphrase" @password ] await @keybase { args, quiet : true }, esc defer() cb null #----------------- logout : (cb) -> await @keybase { args : [ "logout"], quiet : true }, defer err cb err #----------------- login : (cb) -> await @keybase { args : [ "login"], quiet : true }, defer err cb err #---------- cleanup : (cb) -> await @revoke_key defer e1 await @rm_homedir defer e2 err = e1 or e2 cb err #---------- rm_homedir : (cb) -> await rm_r @homedir, defer err cb err #----------------- revoke_key : (cb) -> err = null if config().preserve log.warn "Not deleting key / preserving due to command-line flag" else await @keybase { args : [ "revoke", "--force" ], quiet : true }, defer err @_state.revoked = true unless err? cb err #----------------- load_status : (cb) -> esc = make_esc cb, "User::load_status" await @keybase { args : [ "status"] }, esc defer out await a_json_parse out, esc defer json @_status = json cb null #================================================================== class Users constructor : () -> @_list = [] @_lookup = {} push : (u) -> @_list.push u @_lookup[u.username] = u lookup : (u) -> @_lookup[u] lookup_or_gen : (u) -> unless (ret = @_lookup[u])? @_lookup[u] = ret = User.generate u return ret get : (i) -> @_list[i] cleanup : (cb) -> err = null for u in @_list when u.has_live_key() await u.cleanup defer tmp if tmp? log.error "Error cleaning up user #{u.username}: #{tmp.message}" err = tmp cb err #================================================================== _users = new Users exports.users = users = () -> _users #==================================================================
19420
# # A file that wraps the creation and management of test # users, potentially with features to access test twitter # and github accounts. As such, it might need access to # a configuration file, since we don't want to push our # test twitter/github credentials to github. # {prng} = require 'crypto' {init,config} = require './config' path = require 'path' iutils = require 'iced-utils' {rm_r,mkdir_p} = iutils.fs {a_json_parse,athrow} = iutils.util {make_esc} = require 'iced-error' log = require '../../lib/log' gpgw = require 'gpg-wrapper' {AltKeyRing} = gpgw.keyring {run} = require 'iced-spawn' keypool = require './keypool' {Engine} = require 'iced-expect' {tweet_api} = require './twitter' {gist_api} = require './github' fs = require 'fs' {Rendezvous} = require('iced-coffee-script').iced #================================================================== strip = (x) -> if (m = x.match /^(\s*)([\S\s]*?)(\s*)$/) then m[2] else x #================================================================== randhex = (len) -> prng(len).toString('hex') #================================================================== assert_kb_ok = (rc) -> if rc is 0 then null else new Error "Non-ok result from keybase: #{rc}" #================================================================== exports.User = class User constructor : ({@username, @email, @password, @homedir}) -> @keyring = null @_state = { proved : {} } @_proofs = {} users().push @ #--------------- @generate : (base) -> base or= randhex(3) opts = username : "test_#{base}" password : <PASSWORD>) email : "<EMAIL>" homedir : path.join(config().scratch_dir(), "home_#{base}") new User opts #----------------- check_if_exists : (cb) -> tmpcb = (err) -> cb false esc = make_esc tmpcb, "User::check_if_exists" await fs.stat @homedir, esc defer() await fs.stat @keyring_dir(), esc defer() await fs.stat path.join(@homedir, ".keybase", "config.json"), esc defer() cb true #----------------- init : (cb) -> esc = make_esc cb, "User::init" await @make_homedir esc defer() await @make_keyring esc defer() await @grab_key esc defer() await @write_config esc defer() @_state.init = true cb null #----------------- write_config : (cb) -> esc = make_esc cb, "User::write_config" await @keybase { args : [ "config" ], quiet : true }, esc defer() args = [ "config" "--json" "server" JSON.stringify(config().server_obj()) ] await @keybase { args, quiet : true }, esc defer() cb null #----------------- make_homedir : (cb) -> await mkdir_p @homedir, null, defer err cb err #----------------- keyring_dir : () -> path.join(@homedir, ".gnupg") #----------------- _keybase_cmd : (inargs) -> inargs.args = [ "--homedir", @homedir ].concat inargs.args config().keybase_cmd inargs log.debug "Running keybase: " + JSON.stringify(inargs) return inargs #----------------- keybase : (inargs, cb) -> @_keybase_cmd inargs await run inargs, defer err, out cb err, out #----------------- keybase_expect : (args) -> inargs = { args, opts : {} } if config().debug inargs.opts = debug : { stdout : true } passthrough : { stderr : true } @_keybase_cmd inargs eng = new Engine inargs eng.run() return eng #----------------- make_keyring : (cb) -> await AltKeyRing.make @keyring_dir(), defer err, @keyring cb err #----------------- gpg : (args, cb) -> @keyring.gpg args, cb #----------------- grab_key : (cb) -> esc = make_esc cb, "User::grab_key" await keypool.grab esc defer tmp await tmp.load esc defer() @key = tmp.copy_to_keyring @keyring await @key.save esc defer() cb null #----------------- push_key : (cb) -> await @keybase { args : [ "push", "--skip-add-email", @key.fingerprint() ], quiet : true }, defer err @_state.pushed = true unless err? cb err #----------------- signup : (cb) -> eng = @keybase_expect [ "signup" ] await eng.conversation [ { expect : "Your email: "} { sendline : @email } { expect : "Invitation code \\(leave blank if you don't have one\\): " } { sendline : "202020202020202020202020" } { expect : "Your desired username: " } { sendline : @username } { expect : "Your login passphrase: " } { sendline : @password } { expect : "Repeat to confirm: " } { sendline : @password }, ], defer err unless err? await eng.wait defer rc if rc isnt 0 err = new Error "Command-line client failed with code #{rc}" else @_state.signedup = true cb err #----------------- prove : ({which, search_regex, http_action}, cb) -> esc = make_esc cb, "User::prove" eng = @keybase_expect [ "prove", which ] @twitter = {} unless (acct = config().get_dummy_account which)? await athrow (new Error "No dummy accounts available for '#{which}'"), esc defer() await eng.expect { pattern : (new RegExp "Your username on #{which}: ", "i") }, esc defer() await eng.sendline acct.username, esc defer() await eng.expect { pattern : (new RegExp "Check #{which} now\\? \\[Y/n\\] ", "i") }, esc defer data if (m = data.toString('utf8').match search_regex)? proof = m[1] else await athrow (new Error "Didn't get a #{which} text from the CLI"), esc defer() log.debug "+ Doing HTTP action #{acct.username}@#{which}" await http_action acct, proof, esc defer proof_id log.debug "- Did HTTP action, completed w/ proof_id=#{proof_id}" await eng.sendline "y", esc defer() eng.expect { repeat : true, pattern : (new RegExp "Check #{which} again now\\? \\[Y/n\\] ", "i") }, (err, data, source) => log.info "Trying #{which} again, maybe they're slow to update?" await setTimeout defer(), 1000 await eng.sendline "y", defer err log.warn "Failed to send a yes: #{err.message}" if err? await eng.wait defer rc if rc isnt 0 err = new Error "Error from keybase prove: #{rc}" else @_proofs[which] = { proof, proof_id, acct } @_state.proved[which] = true cb err #----------------- accounts : () -> unless (out = @_status?.user?.proofs)? out = {} for k,v of @_proofs out[k] = v.acct.username return out #----------------- # Load proofs in from the output of `keybase status` _load_proofs : (obj) -> if (d = obj?.user?.proofs)? for k,v of d @_proofs[k] = { acct : { username : v } } #----------------- assertions : () -> d = @accounts() out = [] for k,v of d out.push("--assert", [k, v].join(":") ) return out #----------------- prove_twitter : (cb) -> opts = which : "twitter" search_regex : /Please.*tweet.*the following:\s+(\S.*?)\n/ http_action : tweet_api await @prove opts, defer err cb err #----------------- prove_github : (cb) -> opts = which : "github" search_regex : /Please.*?post the following Gist, and name it.*?:\s+(\S[\s\S]*?)\n\nCheck GitHub now\?/i http_action : gist_api await @prove opts, defer err cb err #----------------- has_live_key : () -> @_state.pushed and @_state.signedup and not(@_state.revoked) #----------------- full_monty : (T, {twitter, github, save_pw}, gcb) -> un = @username esc = (which, lcb) -> (err, args...) -> T.waypoint "fully_monty #{un}: #{which}" T.no_error err if err? then gcb err else lcb args... await @init esc('init', defer()) await @signup esc('signup', defer()) await @push_key esc('push_key', defer()) await @list_signatures esc('list_signatures', defer()) await @prove_github esc('prove_github', defer()) if github await @prove_twitter esc('prove_twitter', defer()) if twitter await @list_signatures esc('list_signatures', defer()) await @write_pw esc('write_pw', defer()) if save_pw gcb null #----------------- check_proofs : (output, cb) -> err = null for k,v of @_proofs x = new RegExp "#{v.acct.username}.*#{k}.*https://.*#{k}\\.com/.*#{v.proof_id}" unless output.match x err = new Error "Failed to find proof for #{k} for user: #{v.acct.username}" break cb err #----------------- follow : (followee, {remote}, cb) -> esc = make_esc cb, "User::follow" un = followee.username eng = @keybase_expect [ "track", un ] eng.expect { pattern : new RegExp("Is this the #{un} you wanted\\? \\[y\\/N\\] ") }, (err, data, src) -> unless err? await followee.check_proofs eng.stderr().toString('utf8'), defer err if err? log.warn "Failed to find the correct proofs" await eng.sendline "n", defer err else await eng.sendline "y", defer err eng.expect { pattern : /Permanently track this user, and write proof to server\? \[Y\/n\] / }, (err, data, src) -> unless err? await eng.sendline (if remote then "y" else "n"), esc defer() await eng.wait defer rc err = assert_kb_ok rc cb err #----------------- id : (followee, cb) -> esc = make_esc cb, "User::id" un = followee.username eng = @keybase_expect [ "id", un ] await eng.wait defer rc err = assert_kb_ok rc await athrow err, esc defer() if err? stderr = eng.stderr().toString('utf8') await followee.check_proofs stderr, defer err if err? log.warn "Failed to find the correct proofs; got: " log.warn stderr cb err #----------------- list_signatures : (cb) -> esc = make_esc cb, "User::list_signatures" eng = @keybase_expect [ "list-signatures" ] await eng.wait defer rc err = assert_kb_ok rc cb err #----------------- unfollow : (followee, cb) -> esc = make_esc cb, "User::follow" eng = @keybase_expect [ "untrack", "--remove-key", followee.username ] await eng.wait defer rc err = assert_kb_ok rc cb err #----------------- write_pw : (cb) -> esc = make_esc cb, "User::write_pw" await @keybase { args : [ "config" ], quiet : true }, esc defer() args = [ "config" "user.passphrase" @password ] await @keybase { args, quiet : true }, esc defer() cb null #----------------- logout : (cb) -> await @keybase { args : [ "logout"], quiet : true }, defer err cb err #----------------- login : (cb) -> await @keybase { args : [ "login"], quiet : true }, defer err cb err #---------- cleanup : (cb) -> await @revoke_key defer e1 await @rm_homedir defer e2 err = e1 or e2 cb err #---------- rm_homedir : (cb) -> await rm_r @homedir, defer err cb err #----------------- revoke_key : (cb) -> err = null if config().preserve log.warn "Not deleting key / preserving due to command-line flag" else await @keybase { args : [ "revoke", "--force" ], quiet : true }, defer err @_state.revoked = true unless err? cb err #----------------- load_status : (cb) -> esc = make_esc cb, "User::load_status" await @keybase { args : [ "status"] }, esc defer out await a_json_parse out, esc defer json @_status = json cb null #================================================================== class Users constructor : () -> @_list = [] @_lookup = {} push : (u) -> @_list.push u @_lookup[u.username] = u lookup : (u) -> @_lookup[u] lookup_or_gen : (u) -> unless (ret = @_lookup[u])? @_lookup[u] = ret = User.generate u return ret get : (i) -> @_list[i] cleanup : (cb) -> err = null for u in @_list when u.has_live_key() await u.cleanup defer tmp if tmp? log.error "Error cleaning up user #{u.username}: #{tmp.message}" err = tmp cb err #================================================================== _users = new Users exports.users = users = () -> _users #==================================================================
true
# # A file that wraps the creation and management of test # users, potentially with features to access test twitter # and github accounts. As such, it might need access to # a configuration file, since we don't want to push our # test twitter/github credentials to github. # {prng} = require 'crypto' {init,config} = require './config' path = require 'path' iutils = require 'iced-utils' {rm_r,mkdir_p} = iutils.fs {a_json_parse,athrow} = iutils.util {make_esc} = require 'iced-error' log = require '../../lib/log' gpgw = require 'gpg-wrapper' {AltKeyRing} = gpgw.keyring {run} = require 'iced-spawn' keypool = require './keypool' {Engine} = require 'iced-expect' {tweet_api} = require './twitter' {gist_api} = require './github' fs = require 'fs' {Rendezvous} = require('iced-coffee-script').iced #================================================================== strip = (x) -> if (m = x.match /^(\s*)([\S\s]*?)(\s*)$/) then m[2] else x #================================================================== randhex = (len) -> prng(len).toString('hex') #================================================================== assert_kb_ok = (rc) -> if rc is 0 then null else new Error "Non-ok result from keybase: #{rc}" #================================================================== exports.User = class User constructor : ({@username, @email, @password, @homedir}) -> @keyring = null @_state = { proved : {} } @_proofs = {} users().push @ #--------------- @generate : (base) -> base or= randhex(3) opts = username : "test_#{base}" password : PI:PASSWORD:<PASSWORD>END_PI) email : "PI:EMAIL:<EMAIL>END_PI" homedir : path.join(config().scratch_dir(), "home_#{base}") new User opts #----------------- check_if_exists : (cb) -> tmpcb = (err) -> cb false esc = make_esc tmpcb, "User::check_if_exists" await fs.stat @homedir, esc defer() await fs.stat @keyring_dir(), esc defer() await fs.stat path.join(@homedir, ".keybase", "config.json"), esc defer() cb true #----------------- init : (cb) -> esc = make_esc cb, "User::init" await @make_homedir esc defer() await @make_keyring esc defer() await @grab_key esc defer() await @write_config esc defer() @_state.init = true cb null #----------------- write_config : (cb) -> esc = make_esc cb, "User::write_config" await @keybase { args : [ "config" ], quiet : true }, esc defer() args = [ "config" "--json" "server" JSON.stringify(config().server_obj()) ] await @keybase { args, quiet : true }, esc defer() cb null #----------------- make_homedir : (cb) -> await mkdir_p @homedir, null, defer err cb err #----------------- keyring_dir : () -> path.join(@homedir, ".gnupg") #----------------- _keybase_cmd : (inargs) -> inargs.args = [ "--homedir", @homedir ].concat inargs.args config().keybase_cmd inargs log.debug "Running keybase: " + JSON.stringify(inargs) return inargs #----------------- keybase : (inargs, cb) -> @_keybase_cmd inargs await run inargs, defer err, out cb err, out #----------------- keybase_expect : (args) -> inargs = { args, opts : {} } if config().debug inargs.opts = debug : { stdout : true } passthrough : { stderr : true } @_keybase_cmd inargs eng = new Engine inargs eng.run() return eng #----------------- make_keyring : (cb) -> await AltKeyRing.make @keyring_dir(), defer err, @keyring cb err #----------------- gpg : (args, cb) -> @keyring.gpg args, cb #----------------- grab_key : (cb) -> esc = make_esc cb, "User::grab_key" await keypool.grab esc defer tmp await tmp.load esc defer() @key = tmp.copy_to_keyring @keyring await @key.save esc defer() cb null #----------------- push_key : (cb) -> await @keybase { args : [ "push", "--skip-add-email", @key.fingerprint() ], quiet : true }, defer err @_state.pushed = true unless err? cb err #----------------- signup : (cb) -> eng = @keybase_expect [ "signup" ] await eng.conversation [ { expect : "Your email: "} { sendline : @email } { expect : "Invitation code \\(leave blank if you don't have one\\): " } { sendline : "202020202020202020202020" } { expect : "Your desired username: " } { sendline : @username } { expect : "Your login passphrase: " } { sendline : @password } { expect : "Repeat to confirm: " } { sendline : @password }, ], defer err unless err? await eng.wait defer rc if rc isnt 0 err = new Error "Command-line client failed with code #{rc}" else @_state.signedup = true cb err #----------------- prove : ({which, search_regex, http_action}, cb) -> esc = make_esc cb, "User::prove" eng = @keybase_expect [ "prove", which ] @twitter = {} unless (acct = config().get_dummy_account which)? await athrow (new Error "No dummy accounts available for '#{which}'"), esc defer() await eng.expect { pattern : (new RegExp "Your username on #{which}: ", "i") }, esc defer() await eng.sendline acct.username, esc defer() await eng.expect { pattern : (new RegExp "Check #{which} now\\? \\[Y/n\\] ", "i") }, esc defer data if (m = data.toString('utf8').match search_regex)? proof = m[1] else await athrow (new Error "Didn't get a #{which} text from the CLI"), esc defer() log.debug "+ Doing HTTP action #{acct.username}@#{which}" await http_action acct, proof, esc defer proof_id log.debug "- Did HTTP action, completed w/ proof_id=#{proof_id}" await eng.sendline "y", esc defer() eng.expect { repeat : true, pattern : (new RegExp "Check #{which} again now\\? \\[Y/n\\] ", "i") }, (err, data, source) => log.info "Trying #{which} again, maybe they're slow to update?" await setTimeout defer(), 1000 await eng.sendline "y", defer err log.warn "Failed to send a yes: #{err.message}" if err? await eng.wait defer rc if rc isnt 0 err = new Error "Error from keybase prove: #{rc}" else @_proofs[which] = { proof, proof_id, acct } @_state.proved[which] = true cb err #----------------- accounts : () -> unless (out = @_status?.user?.proofs)? out = {} for k,v of @_proofs out[k] = v.acct.username return out #----------------- # Load proofs in from the output of `keybase status` _load_proofs : (obj) -> if (d = obj?.user?.proofs)? for k,v of d @_proofs[k] = { acct : { username : v } } #----------------- assertions : () -> d = @accounts() out = [] for k,v of d out.push("--assert", [k, v].join(":") ) return out #----------------- prove_twitter : (cb) -> opts = which : "twitter" search_regex : /Please.*tweet.*the following:\s+(\S.*?)\n/ http_action : tweet_api await @prove opts, defer err cb err #----------------- prove_github : (cb) -> opts = which : "github" search_regex : /Please.*?post the following Gist, and name it.*?:\s+(\S[\s\S]*?)\n\nCheck GitHub now\?/i http_action : gist_api await @prove opts, defer err cb err #----------------- has_live_key : () -> @_state.pushed and @_state.signedup and not(@_state.revoked) #----------------- full_monty : (T, {twitter, github, save_pw}, gcb) -> un = @username esc = (which, lcb) -> (err, args...) -> T.waypoint "fully_monty #{un}: #{which}" T.no_error err if err? then gcb err else lcb args... await @init esc('init', defer()) await @signup esc('signup', defer()) await @push_key esc('push_key', defer()) await @list_signatures esc('list_signatures', defer()) await @prove_github esc('prove_github', defer()) if github await @prove_twitter esc('prove_twitter', defer()) if twitter await @list_signatures esc('list_signatures', defer()) await @write_pw esc('write_pw', defer()) if save_pw gcb null #----------------- check_proofs : (output, cb) -> err = null for k,v of @_proofs x = new RegExp "#{v.acct.username}.*#{k}.*https://.*#{k}\\.com/.*#{v.proof_id}" unless output.match x err = new Error "Failed to find proof for #{k} for user: #{v.acct.username}" break cb err #----------------- follow : (followee, {remote}, cb) -> esc = make_esc cb, "User::follow" un = followee.username eng = @keybase_expect [ "track", un ] eng.expect { pattern : new RegExp("Is this the #{un} you wanted\\? \\[y\\/N\\] ") }, (err, data, src) -> unless err? await followee.check_proofs eng.stderr().toString('utf8'), defer err if err? log.warn "Failed to find the correct proofs" await eng.sendline "n", defer err else await eng.sendline "y", defer err eng.expect { pattern : /Permanently track this user, and write proof to server\? \[Y\/n\] / }, (err, data, src) -> unless err? await eng.sendline (if remote then "y" else "n"), esc defer() await eng.wait defer rc err = assert_kb_ok rc cb err #----------------- id : (followee, cb) -> esc = make_esc cb, "User::id" un = followee.username eng = @keybase_expect [ "id", un ] await eng.wait defer rc err = assert_kb_ok rc await athrow err, esc defer() if err? stderr = eng.stderr().toString('utf8') await followee.check_proofs stderr, defer err if err? log.warn "Failed to find the correct proofs; got: " log.warn stderr cb err #----------------- list_signatures : (cb) -> esc = make_esc cb, "User::list_signatures" eng = @keybase_expect [ "list-signatures" ] await eng.wait defer rc err = assert_kb_ok rc cb err #----------------- unfollow : (followee, cb) -> esc = make_esc cb, "User::follow" eng = @keybase_expect [ "untrack", "--remove-key", followee.username ] await eng.wait defer rc err = assert_kb_ok rc cb err #----------------- write_pw : (cb) -> esc = make_esc cb, "User::write_pw" await @keybase { args : [ "config" ], quiet : true }, esc defer() args = [ "config" "user.passphrase" @password ] await @keybase { args, quiet : true }, esc defer() cb null #----------------- logout : (cb) -> await @keybase { args : [ "logout"], quiet : true }, defer err cb err #----------------- login : (cb) -> await @keybase { args : [ "login"], quiet : true }, defer err cb err #---------- cleanup : (cb) -> await @revoke_key defer e1 await @rm_homedir defer e2 err = e1 or e2 cb err #---------- rm_homedir : (cb) -> await rm_r @homedir, defer err cb err #----------------- revoke_key : (cb) -> err = null if config().preserve log.warn "Not deleting key / preserving due to command-line flag" else await @keybase { args : [ "revoke", "--force" ], quiet : true }, defer err @_state.revoked = true unless err? cb err #----------------- load_status : (cb) -> esc = make_esc cb, "User::load_status" await @keybase { args : [ "status"] }, esc defer out await a_json_parse out, esc defer json @_status = json cb null #================================================================== class Users constructor : () -> @_list = [] @_lookup = {} push : (u) -> @_list.push u @_lookup[u.username] = u lookup : (u) -> @_lookup[u] lookup_or_gen : (u) -> unless (ret = @_lookup[u])? @_lookup[u] = ret = User.generate u return ret get : (i) -> @_list[i] cleanup : (cb) -> err = null for u in @_list when u.has_live_key() await u.cleanup defer tmp if tmp? log.error "Error cleaning up user #{u.username}: #{tmp.message}" err = tmp cb err #================================================================== _users = new Users exports.users = users = () -> _users #==================================================================
[ { "context": "###*\n * 按钮\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{View} = req", "end": 28, "score": 0.9994409680366516, "start": 22, "tag": "USERNAME", "value": "vfasky" }, { "context": "###*\n * 按钮\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{Vie...
example/src/button.coffee
vfasky/mcore-weui
0
###* * 按钮 * @author vfasky <vfasky@gmail.com> ### 'use strict' {View} = require 'mcoreapp' class Button extends View run: -> @render require('../tpl/button.html') module.exports = Button module.exports.viewName = 'button'
18304
###* * 按钮 * @author vfasky <<EMAIL>> ### 'use strict' {View} = require 'mcoreapp' class Button extends View run: -> @render require('../tpl/button.html') module.exports = Button module.exports.viewName = 'button'
true
###* * 按钮 * @author vfasky <PI:EMAIL:<EMAIL>END_PI> ### 'use strict' {View} = require 'mcoreapp' class Button extends View run: -> @render require('../tpl/button.html') module.exports = Button module.exports.viewName = 'button'
[ { "context": "d4383a44a6adc\"\n vout: 1\n scriptPubKey: \"76a914e867aad8bd361f57c50adc37a0c018692b5b0c9a88ac\"\n amount: 0.4296\n confirmations: 1\n ", "end": 1252, "score": 0.9997707009315491, "start": 1202, "tag": "KEY", "value": "76a914e867aad8bd361f57c50adc37a0c018...
src/backend/coin-utils.coffee
jesstelford/payment-channels
10
_ = require 'underscore' bignum = require 'bignum' Builder = require 'bitcore/lib/TransactionBuilder' Key = require 'bitcore/lib/Key' networks = require "#{__dirname}/networks.js" # TODO: Research: What's riskier; 1) Using satoshi's and worry about overflowing # the integer type, or 2) Using BTC's and worry about Javascript's innacuracies? T1INPUT_ID_FOR_T2_T3 = 0 opts = network: networks.testnet module.exports = decodePubkey: (hexStr) -> buf = new Buffer hexStr, 'hex' return undefined if not buf key = new Key.Key() key.public = buf return key verifyTxSig: (tx, sig) -> hash = tx.serialize().toString('hex') return Key.verifySignatureSync hash, sig build2of2MultiSigTx: (pubkeyHex1, pubkeyHex2, amountSat) -> pubkeysForTransaction = 2 # Using an OP_CHECKMULTISIG transaction for 2 of 2 multisig pubkeys = [pubkeyHex1, pubkeyHex2] # TODO: where can I get these from? a bitcoind instance? API? (Let's go with # API) # TODO: Ensure that the 'amountSat' field is in satoshi's utxos = [{ address: pubkeyHex1 txid: "39c71ebda371f75f4b854a720eaf9898b237facf3c2b101b58cd4383a44a6adc" vout: 1 scriptPubKey: "76a914e867aad8bd361f57c50adc37a0c018692b5b0c9a88ac" amount: 0.4296 confirmations: 1 }] outs = [{ nreq: pubkeysForTransaction pubkeys: pubkeys amount: "0.1" }] # partially build the transaction here, and let it be signed elsewhere builder = new Builder(opts) builder.setUnspent(utxos) console.log "unspent" builder.setOutputs(outs) console.log "outs" return builder ### # @param txToRefund a bitcore transaction to refund # @param refundPubKey Public key to send the refund to # @param amountNotRefundedK2 satoshi's to pay server # @param serverPubkeyK2 server's public key # @param timeToLock Unix timestamp before which the transaction will not be accepted into a block ### buildRollingRefundTxFromMultiSigOutput: (txToRefund, totalRefund, refundPubKey, amountNotRefundedK2, serverPubkeyK2, timeToLock) -> if not amountNotRefundedK2 then amountNotRefundedK2 = 0 if amountNotRefundedK2 > totalRefund throw new Error "Cannot pay out more than the total original agreement" # txToRefundHex = txToRefund.serialize().toString('hex') txToRefundHexScriptPubkey = txToRefund.outs[0].s.toString('hex') utxos = [{ # address: "abc123", # Looking through bitcore implys we don't need this for a multisig input txid: txToRefund.getHash().toString('hex'), vout: 0, # There should only be a single output for the transactoin, so it's always vout number 0 scriptPubKey: txToRefundHexScriptPubkey, amountSat: totalRefund confirmations: 1 }] outs = [{ address: refundPubKey, amountSat: totalRefund - amountNotRefundedK2 }] # When there is an amount to actually pay to the server, deduct it from the # amount being refunded if amountNotRefundedK2 > 0 # add K2 as an output for total of amountNotRefundedK2 at output ID 1 outs.push { address: serverPubkeyK2, amountSat: amountNotRefundedK2 } builderOpts = _({}).extend opts if timeToLock > 0 builderOpts.lockTime = timeToLock # Since the previous transaction we're attempting to spend hasn't # necessarily been transmitted into the network, we need to flag that we # could be spending an unconfirmed output builderOpts.spendUnconfirmed = true builder = new Builder(builderOpts) .setUnspent(utxos) .setOutputs(outs) return { tx: builder t1InIdx: T1INPUT_ID_FOR_T2_T3 # Due to the way we constructed the transaction above, the in id will always be at index 0 }
107521
_ = require 'underscore' bignum = require 'bignum' Builder = require 'bitcore/lib/TransactionBuilder' Key = require 'bitcore/lib/Key' networks = require "#{__dirname}/networks.js" # TODO: Research: What's riskier; 1) Using satoshi's and worry about overflowing # the integer type, or 2) Using BTC's and worry about Javascript's innacuracies? T1INPUT_ID_FOR_T2_T3 = 0 opts = network: networks.testnet module.exports = decodePubkey: (hexStr) -> buf = new Buffer hexStr, 'hex' return undefined if not buf key = new Key.Key() key.public = buf return key verifyTxSig: (tx, sig) -> hash = tx.serialize().toString('hex') return Key.verifySignatureSync hash, sig build2of2MultiSigTx: (pubkeyHex1, pubkeyHex2, amountSat) -> pubkeysForTransaction = 2 # Using an OP_CHECKMULTISIG transaction for 2 of 2 multisig pubkeys = [pubkeyHex1, pubkeyHex2] # TODO: where can I get these from? a bitcoind instance? API? (Let's go with # API) # TODO: Ensure that the 'amountSat' field is in satoshi's utxos = [{ address: pubkeyHex1 txid: "39c71ebda371f75f4b854a720eaf9898b237facf3c2b101b58cd4383a44a6adc" vout: 1 scriptPubKey: "<KEY>" amount: 0.4296 confirmations: 1 }] outs = [{ nreq: pubkeysForTransaction pubkeys: pubkeys amount: "0.1" }] # partially build the transaction here, and let it be signed elsewhere builder = new Builder(opts) builder.setUnspent(utxos) console.log "unspent" builder.setOutputs(outs) console.log "outs" return builder ### # @param txToRefund a bitcore transaction to refund # @param refundPubKey Public key to send the refund to # @param amountNotRefundedK2 satoshi's to pay server # @param serverPubkeyK2 server's public key # @param timeToLock Unix timestamp before which the transaction will not be accepted into a block ### buildRollingRefundTxFromMultiSigOutput: (txToRefund, totalRefund, refundPubKey, amountNotRefundedK2, serverPubkeyK2, timeToLock) -> if not amountNotRefundedK2 then amountNotRefundedK2 = 0 if amountNotRefundedK2 > totalRefund throw new Error "Cannot pay out more than the total original agreement" # txToRefundHex = txToRefund.serialize().toString('hex') txToRefundHexScriptPubkey = txToRefund.outs[0].s.toString('hex') utxos = [{ # address: "abc123", # Looking through bitcore implys we don't need this for a multisig input txid: txToRefund.getHash().toString('hex'), vout: 0, # There should only be a single output for the transactoin, so it's always vout number 0 scriptPubKey: txToRefundHexScriptPubkey, amountSat: totalRefund confirmations: 1 }] outs = [{ address: refundPubKey, amountSat: totalRefund - amountNotRefundedK2 }] # When there is an amount to actually pay to the server, deduct it from the # amount being refunded if amountNotRefundedK2 > 0 # add K2 as an output for total of amountNotRefundedK2 at output ID 1 outs.push { address: serverPubkeyK2, amountSat: amountNotRefundedK2 } builderOpts = _({}).extend opts if timeToLock > 0 builderOpts.lockTime = timeToLock # Since the previous transaction we're attempting to spend hasn't # necessarily been transmitted into the network, we need to flag that we # could be spending an unconfirmed output builderOpts.spendUnconfirmed = true builder = new Builder(builderOpts) .setUnspent(utxos) .setOutputs(outs) return { tx: builder t1InIdx: T1INPUT_ID_FOR_T2_T3 # Due to the way we constructed the transaction above, the in id will always be at index 0 }
true
_ = require 'underscore' bignum = require 'bignum' Builder = require 'bitcore/lib/TransactionBuilder' Key = require 'bitcore/lib/Key' networks = require "#{__dirname}/networks.js" # TODO: Research: What's riskier; 1) Using satoshi's and worry about overflowing # the integer type, or 2) Using BTC's and worry about Javascript's innacuracies? T1INPUT_ID_FOR_T2_T3 = 0 opts = network: networks.testnet module.exports = decodePubkey: (hexStr) -> buf = new Buffer hexStr, 'hex' return undefined if not buf key = new Key.Key() key.public = buf return key verifyTxSig: (tx, sig) -> hash = tx.serialize().toString('hex') return Key.verifySignatureSync hash, sig build2of2MultiSigTx: (pubkeyHex1, pubkeyHex2, amountSat) -> pubkeysForTransaction = 2 # Using an OP_CHECKMULTISIG transaction for 2 of 2 multisig pubkeys = [pubkeyHex1, pubkeyHex2] # TODO: where can I get these from? a bitcoind instance? API? (Let's go with # API) # TODO: Ensure that the 'amountSat' field is in satoshi's utxos = [{ address: pubkeyHex1 txid: "39c71ebda371f75f4b854a720eaf9898b237facf3c2b101b58cd4383a44a6adc" vout: 1 scriptPubKey: "PI:KEY:<KEY>END_PI" amount: 0.4296 confirmations: 1 }] outs = [{ nreq: pubkeysForTransaction pubkeys: pubkeys amount: "0.1" }] # partially build the transaction here, and let it be signed elsewhere builder = new Builder(opts) builder.setUnspent(utxos) console.log "unspent" builder.setOutputs(outs) console.log "outs" return builder ### # @param txToRefund a bitcore transaction to refund # @param refundPubKey Public key to send the refund to # @param amountNotRefundedK2 satoshi's to pay server # @param serverPubkeyK2 server's public key # @param timeToLock Unix timestamp before which the transaction will not be accepted into a block ### buildRollingRefundTxFromMultiSigOutput: (txToRefund, totalRefund, refundPubKey, amountNotRefundedK2, serverPubkeyK2, timeToLock) -> if not amountNotRefundedK2 then amountNotRefundedK2 = 0 if amountNotRefundedK2 > totalRefund throw new Error "Cannot pay out more than the total original agreement" # txToRefundHex = txToRefund.serialize().toString('hex') txToRefundHexScriptPubkey = txToRefund.outs[0].s.toString('hex') utxos = [{ # address: "abc123", # Looking through bitcore implys we don't need this for a multisig input txid: txToRefund.getHash().toString('hex'), vout: 0, # There should only be a single output for the transactoin, so it's always vout number 0 scriptPubKey: txToRefundHexScriptPubkey, amountSat: totalRefund confirmations: 1 }] outs = [{ address: refundPubKey, amountSat: totalRefund - amountNotRefundedK2 }] # When there is an amount to actually pay to the server, deduct it from the # amount being refunded if amountNotRefundedK2 > 0 # add K2 as an output for total of amountNotRefundedK2 at output ID 1 outs.push { address: serverPubkeyK2, amountSat: amountNotRefundedK2 } builderOpts = _({}).extend opts if timeToLock > 0 builderOpts.lockTime = timeToLock # Since the previous transaction we're attempting to spend hasn't # necessarily been transmitted into the network, we need to flag that we # could be spending an unconfirmed output builderOpts.spendUnconfirmed = true builder = new Builder(builderOpts) .setUnspent(utxos) .setOutputs(outs) return { tx: builder t1InIdx: T1INPUT_ID_FOR_T2_T3 # Due to the way we constructed the transaction above, the in id will always be at index 0 }
[ { "context": "ptimal_l]\n\n # final result object\n password: password\n guesses: guesses\n guesses_log10: @log10 gu", "end": 7155, "score": 0.9994570016860962, "start": 7147, "tag": "PASSWORD", "value": "password" } ]
node_modules/zxcvbn/src/scoring.coffee
bboozzoo/mender-gui
0
adjacency_graphs = require('./adjacency_graphs') # on qwerty, 'g' has degree 6, being adjacent to 'ftyhbv'. '\' has degree 1. # this calculates the average over all keys. calc_average_degree = (graph) -> average = 0 for key, neighbors of graph average += (n for n in neighbors when n).length average /= (k for k,v of graph).length average BRUTEFORCE_CARDINALITY = 10 MIN_GUESSES_BEFORE_GROWING_SEQUENCE = 10000 MIN_SUBMATCH_GUESSES_SINGLE_CHAR = 10 MIN_SUBMATCH_GUESSES_MULTI_CHAR = 50 scoring = nCk: (n, k) -> # http://blog.plover.com/math/choose.html return 0 if k > n return 1 if k == 0 r = 1 for d in [1..k] r *= n r /= d n -= 1 r log10: (n) -> Math.log(n) / Math.log(10) # IE doesn't support Math.log10 :( log2: (n) -> Math.log(n) / Math.log(2) factorial: (n) -> # unoptimized, called only on small n return 1 if n < 2 f = 1 f *= i for i in [2..n] f # ------------------------------------------------------------------------------ # search --- most guessable match sequence ------------------------------------- # ------------------------------------------------------------------------------ # # takes a sequence of overlapping matches, returns the non-overlapping sequence with # minimum guesses. the following is a O(l_max * (n + m)) dynamic programming algorithm # for a length-n password with m candidate matches. l_max is the maximum optimal # sequence length spanning each prefix of the password. In practice it rarely exceeds 5 and the # search terminates rapidly. # # the optimal "minimum guesses" sequence is here defined to be the sequence that # minimizes the following function: # # g = l! * Product(m.guesses for m in sequence) + D^(l - 1) # # where l is the length of the sequence. # # the factorial term is the number of ways to order l patterns. # # the D^(l-1) term is another length penalty, roughly capturing the idea that an # attacker will try lower-length sequences first before trying length-l sequences. # # for example, consider a sequence that is date-repeat-dictionary. # - an attacker would need to try other date-repeat-dictionary combinations, # hence the product term. # - an attacker would need to try repeat-date-dictionary, dictionary-repeat-date, # ..., hence the factorial term. # - an attacker would also likely try length-1 (dictionary) and length-2 (dictionary-date) # sequences before length-3. assuming at minimum D guesses per pattern type, # D^(l-1) approximates Sum(D^i for i in [1..l-1] # # ------------------------------------------------------------------------------ most_guessable_match_sequence: (password, matches, _exclude_additive=false) -> n = password.length # partition matches into sublists according to ending index j matches_by_j = ([] for _ in [0...n]) for m in matches matches_by_j[m.j].push m # small detail: for deterministic output, sort each sublist by i. for lst in matches_by_j lst.sort (m1, m2) -> m1.i - m2.i optimal = # optimal.m[k][l] holds final match in the best length-l match sequence covering the # password prefix up to k, inclusive. # if there is no length-l sequence that scores better (fewer guesses) than # a shorter match sequence spanning the same prefix, optimal.m[k][l] is undefined. m: ({} for _ in [0...n]) # same structure as optimal.m -- holds the product term Prod(m.guesses for m in sequence). # optimal.pi allows for fast (non-looping) updates to the minimization function. pi: ({} for _ in [0...n]) # same structure as optimal.m -- holds the overall metric. g: ({} for _ in [0...n]) # helper: considers whether a length-l sequence ending at match m is better (fewer guesses) # than previously encountered sequences, updating state if so. update = (m, l) => k = m.j pi = @estimate_guesses m, password if l > 1 # we're considering a length-l sequence ending with match m: # obtain the product term in the minimization function by multiplying m's guesses # by the product of the length-(l-1) sequence ending just before m, at m.i - 1. pi *= optimal.pi[m.i - 1][l - 1] # calculate the minimization func g = @factorial(l) * pi unless _exclude_additive g += Math.pow(MIN_GUESSES_BEFORE_GROWING_SEQUENCE, l - 1) # update state if new best. # first see if any competing sequences covering this prefix, with l or fewer matches, # fare better than this sequence. if so, skip it and return. for competing_l, competing_g of optimal.g[k] continue if competing_l > l return if competing_g <= g # this sequence might be part of the final optimal sequence. optimal.g[k][l] = g optimal.m[k][l] = m optimal.pi[k][l] = pi # helper: evaluate bruteforce matches ending at k. bruteforce_update = (k) => # see if a single bruteforce match spanning the k-prefix is optimal. m = make_bruteforce_match(0, k) update(m, 1) for i in [1..k] # generate k bruteforce matches, spanning from (i=1, j=k) up to (i=k, j=k). # see if adding these new matches to any of the sequences in optimal[i-1] # leads to new bests. m = make_bruteforce_match(i, k) for l, last_m of optimal.m[i-1] l = parseInt(l) # corner: an optimal sequence will never have two adjacent bruteforce matches. # it is strictly better to have a single bruteforce match spanning the same region: # same contribution to the guess product with a lower length. # --> safe to skip those cases. continue if last_m.pattern == 'bruteforce' # try adding m to this length-l sequence. update(m, l + 1) # helper: make bruteforce match objects spanning i to j, inclusive. make_bruteforce_match = (i, j) => pattern: 'bruteforce' token: password[i..j] i: i j: j # helper: step backwards through optimal.m starting at the end, # constructing the final optimal match sequence. unwind = (n) => optimal_match_sequence = [] k = n - 1 # find the final best sequence length and score l = undefined g = Infinity for candidate_l, candidate_g of optimal.g[k] if candidate_g < g l = candidate_l g = candidate_g while k >= 0 m = optimal.m[k][l] optimal_match_sequence.unshift m k = m.i - 1 l-- optimal_match_sequence for k in [0...n] for m in matches_by_j[k] if m.i > 0 for l of optimal.m[m.i - 1] l = parseInt(l) update(m, l + 1) else update(m, 1) bruteforce_update(k) optimal_match_sequence = unwind(n) optimal_l = optimal_match_sequence.length # corner: empty password if password.length == 0 guesses = 1 else guesses = optimal.g[n - 1][optimal_l] # final result object password: password guesses: guesses guesses_log10: @log10 guesses sequence: optimal_match_sequence # ------------------------------------------------------------------------------ # guess estimation -- one function per match pattern --------------------------- # ------------------------------------------------------------------------------ estimate_guesses: (match, password) -> return match.guesses if match.guesses? # a match's guess estimate doesn't change. cache it. min_guesses = 1 if match.token.length < password.length min_guesses = if match.token.length == 1 MIN_SUBMATCH_GUESSES_SINGLE_CHAR else MIN_SUBMATCH_GUESSES_MULTI_CHAR estimation_functions = bruteforce: @bruteforce_guesses dictionary: @dictionary_guesses spatial: @spatial_guesses repeat: @repeat_guesses sequence: @sequence_guesses regex: @regex_guesses date: @date_guesses guesses = estimation_functions[match.pattern].call this, match match.guesses = Math.max guesses, min_guesses match.guesses_log10 = @log10 match.guesses match.guesses bruteforce_guesses: (match) -> guesses = Math.pow BRUTEFORCE_CARDINALITY, match.token.length # small detail: make bruteforce matches at minimum one guess bigger than smallest allowed # submatch guesses, such that non-bruteforce submatches over the same [i..j] take precedence. min_guesses = if match.token.length == 1 MIN_SUBMATCH_GUESSES_SINGLE_CHAR + 1 else MIN_SUBMATCH_GUESSES_MULTI_CHAR + 1 Math.max guesses, min_guesses repeat_guesses: (match) -> match.base_guesses * match.repeat_count sequence_guesses: (match) -> first_chr = match.token.charAt(0) # lower guesses for obvious starting points if first_chr in ['a', 'A', 'z', 'Z', '0', '1', '9'] base_guesses = 4 else if first_chr.match /\d/ base_guesses = 10 # digits else # could give a higher base for uppercase, # assigning 26 to both upper and lower sequences is more conservative. base_guesses = 26 if not match.ascending # need to try a descending sequence in addition to every ascending sequence -> # 2x guesses base_guesses *= 2 base_guesses * match.token.length MIN_YEAR_SPACE: 20 REFERENCE_YEAR: 2016 regex_guesses: (match) -> char_class_bases = alpha_lower: 26 alpha_upper: 26 alpha: 52 alphanumeric: 62 digits: 10 symbols: 33 if match.regex_name of char_class_bases Math.pow(char_class_bases[match.regex_name], match.token.length) else switch match.regex_name when 'recent_year' # conservative estimate of year space: num years from REFERENCE_YEAR. # if year is close to REFERENCE_YEAR, estimate a year space of MIN_YEAR_SPACE. year_space = Math.abs parseInt(match.regex_match[0]) - @REFERENCE_YEAR year_space = Math.max year_space, @MIN_YEAR_SPACE year_space date_guesses: (match) -> # base guesses: (year distance from REFERENCE_YEAR) * num_days * num_years year_space = Math.max(Math.abs(match.year - @REFERENCE_YEAR), @MIN_YEAR_SPACE) guesses = year_space * 365 # add factor of 4 for separator selection (one of ~4 choices) guesses *= 4 if match.separator guesses KEYBOARD_AVERAGE_DEGREE: calc_average_degree(adjacency_graphs.qwerty) # slightly different for keypad/mac keypad, but close enough KEYPAD_AVERAGE_DEGREE: calc_average_degree(adjacency_graphs.keypad) KEYBOARD_STARTING_POSITIONS: (k for k,v of adjacency_graphs.qwerty).length KEYPAD_STARTING_POSITIONS: (k for k,v of adjacency_graphs.keypad).length spatial_guesses: (match) -> if match.graph in ['qwerty', 'dvorak'] s = @KEYBOARD_STARTING_POSITIONS d = @KEYBOARD_AVERAGE_DEGREE else s = @KEYPAD_STARTING_POSITIONS d = @KEYPAD_AVERAGE_DEGREE guesses = 0 L = match.token.length t = match.turns # estimate the number of possible patterns w/ length L or less with t turns or less. for i in [2..L] possible_turns = Math.min(t, i - 1) for j in [1..possible_turns] guesses += @nCk(i - 1, j - 1) * s * Math.pow(d, j) # add extra guesses for shifted keys. (% instead of 5, A instead of a.) # math is similar to extra guesses of l33t substitutions in dictionary matches. if match.shifted_count S = match.shifted_count U = match.token.length - match.shifted_count # unshifted count if S == 0 or U == 0 guesses *= 2 else shifted_variations = 0 shifted_variations += @nCk(S + U, i) for i in [1..Math.min(S, U)] guesses *= shifted_variations guesses dictionary_guesses: (match) -> match.base_guesses = match.rank # keep these as properties for display purposes match.uppercase_variations = @uppercase_variations match match.l33t_variations = @l33t_variations match reversed_variations = match.reversed and 2 or 1 match.base_guesses * match.uppercase_variations * match.l33t_variations * reversed_variations START_UPPER: /^[A-Z][^A-Z]+$/ END_UPPER: /^[^A-Z]+[A-Z]$/ ALL_UPPER: /^[^a-z]+$/ ALL_LOWER: /^[^A-Z]+$/ uppercase_variations: (match) -> word = match.token return 1 if word.match(@ALL_LOWER) or word.toLowerCase() == word # a capitalized word is the most common capitalization scheme, # so it only doubles the search space (uncapitalized + capitalized). # allcaps and end-capitalized are common enough too, underestimate as 2x factor to be safe. for regex in [@START_UPPER, @END_UPPER, @ALL_UPPER] return 2 if word.match regex # otherwise calculate the number of ways to capitalize U+L uppercase+lowercase letters # with U uppercase letters or less. or, if there's more uppercase than lower (for eg. PASSwORD), # the number of ways to lowercase U+L letters with L lowercase letters or less. U = (chr for chr in word.split('') when chr.match /[A-Z]/).length L = (chr for chr in word.split('') when chr.match /[a-z]/).length variations = 0 variations += @nCk(U + L, i) for i in [1..Math.min(U, L)] variations l33t_variations: (match) -> return 1 if not match.l33t variations = 1 for subbed, unsubbed of match.sub # lower-case match.token before calculating: capitalization shouldn't affect l33t calc. chrs = match.token.toLowerCase().split('') S = (chr for chr in chrs when chr == subbed).length # num of subbed chars U = (chr for chr in chrs when chr == unsubbed).length # num of unsubbed chars if S == 0 or U == 0 # for this sub, password is either fully subbed (444) or fully unsubbed (aaa) # treat that as doubling the space (attacker needs to try fully subbed chars in addition to # unsubbed.) variations *= 2 else # this case is similar to capitalization: # with aa44a, U = 3, S = 2, attacker needs to try unsubbed + one sub + two subs p = Math.min(U, S) possibilities = 0 possibilities += @nCk(U + S, i) for i in [1..p] variations *= possibilities variations # utilities -------------------------------------------------------------------- module.exports = scoring
191401
adjacency_graphs = require('./adjacency_graphs') # on qwerty, 'g' has degree 6, being adjacent to 'ftyhbv'. '\' has degree 1. # this calculates the average over all keys. calc_average_degree = (graph) -> average = 0 for key, neighbors of graph average += (n for n in neighbors when n).length average /= (k for k,v of graph).length average BRUTEFORCE_CARDINALITY = 10 MIN_GUESSES_BEFORE_GROWING_SEQUENCE = 10000 MIN_SUBMATCH_GUESSES_SINGLE_CHAR = 10 MIN_SUBMATCH_GUESSES_MULTI_CHAR = 50 scoring = nCk: (n, k) -> # http://blog.plover.com/math/choose.html return 0 if k > n return 1 if k == 0 r = 1 for d in [1..k] r *= n r /= d n -= 1 r log10: (n) -> Math.log(n) / Math.log(10) # IE doesn't support Math.log10 :( log2: (n) -> Math.log(n) / Math.log(2) factorial: (n) -> # unoptimized, called only on small n return 1 if n < 2 f = 1 f *= i for i in [2..n] f # ------------------------------------------------------------------------------ # search --- most guessable match sequence ------------------------------------- # ------------------------------------------------------------------------------ # # takes a sequence of overlapping matches, returns the non-overlapping sequence with # minimum guesses. the following is a O(l_max * (n + m)) dynamic programming algorithm # for a length-n password with m candidate matches. l_max is the maximum optimal # sequence length spanning each prefix of the password. In practice it rarely exceeds 5 and the # search terminates rapidly. # # the optimal "minimum guesses" sequence is here defined to be the sequence that # minimizes the following function: # # g = l! * Product(m.guesses for m in sequence) + D^(l - 1) # # where l is the length of the sequence. # # the factorial term is the number of ways to order l patterns. # # the D^(l-1) term is another length penalty, roughly capturing the idea that an # attacker will try lower-length sequences first before trying length-l sequences. # # for example, consider a sequence that is date-repeat-dictionary. # - an attacker would need to try other date-repeat-dictionary combinations, # hence the product term. # - an attacker would need to try repeat-date-dictionary, dictionary-repeat-date, # ..., hence the factorial term. # - an attacker would also likely try length-1 (dictionary) and length-2 (dictionary-date) # sequences before length-3. assuming at minimum D guesses per pattern type, # D^(l-1) approximates Sum(D^i for i in [1..l-1] # # ------------------------------------------------------------------------------ most_guessable_match_sequence: (password, matches, _exclude_additive=false) -> n = password.length # partition matches into sublists according to ending index j matches_by_j = ([] for _ in [0...n]) for m in matches matches_by_j[m.j].push m # small detail: for deterministic output, sort each sublist by i. for lst in matches_by_j lst.sort (m1, m2) -> m1.i - m2.i optimal = # optimal.m[k][l] holds final match in the best length-l match sequence covering the # password prefix up to k, inclusive. # if there is no length-l sequence that scores better (fewer guesses) than # a shorter match sequence spanning the same prefix, optimal.m[k][l] is undefined. m: ({} for _ in [0...n]) # same structure as optimal.m -- holds the product term Prod(m.guesses for m in sequence). # optimal.pi allows for fast (non-looping) updates to the minimization function. pi: ({} for _ in [0...n]) # same structure as optimal.m -- holds the overall metric. g: ({} for _ in [0...n]) # helper: considers whether a length-l sequence ending at match m is better (fewer guesses) # than previously encountered sequences, updating state if so. update = (m, l) => k = m.j pi = @estimate_guesses m, password if l > 1 # we're considering a length-l sequence ending with match m: # obtain the product term in the minimization function by multiplying m's guesses # by the product of the length-(l-1) sequence ending just before m, at m.i - 1. pi *= optimal.pi[m.i - 1][l - 1] # calculate the minimization func g = @factorial(l) * pi unless _exclude_additive g += Math.pow(MIN_GUESSES_BEFORE_GROWING_SEQUENCE, l - 1) # update state if new best. # first see if any competing sequences covering this prefix, with l or fewer matches, # fare better than this sequence. if so, skip it and return. for competing_l, competing_g of optimal.g[k] continue if competing_l > l return if competing_g <= g # this sequence might be part of the final optimal sequence. optimal.g[k][l] = g optimal.m[k][l] = m optimal.pi[k][l] = pi # helper: evaluate bruteforce matches ending at k. bruteforce_update = (k) => # see if a single bruteforce match spanning the k-prefix is optimal. m = make_bruteforce_match(0, k) update(m, 1) for i in [1..k] # generate k bruteforce matches, spanning from (i=1, j=k) up to (i=k, j=k). # see if adding these new matches to any of the sequences in optimal[i-1] # leads to new bests. m = make_bruteforce_match(i, k) for l, last_m of optimal.m[i-1] l = parseInt(l) # corner: an optimal sequence will never have two adjacent bruteforce matches. # it is strictly better to have a single bruteforce match spanning the same region: # same contribution to the guess product with a lower length. # --> safe to skip those cases. continue if last_m.pattern == 'bruteforce' # try adding m to this length-l sequence. update(m, l + 1) # helper: make bruteforce match objects spanning i to j, inclusive. make_bruteforce_match = (i, j) => pattern: 'bruteforce' token: password[i..j] i: i j: j # helper: step backwards through optimal.m starting at the end, # constructing the final optimal match sequence. unwind = (n) => optimal_match_sequence = [] k = n - 1 # find the final best sequence length and score l = undefined g = Infinity for candidate_l, candidate_g of optimal.g[k] if candidate_g < g l = candidate_l g = candidate_g while k >= 0 m = optimal.m[k][l] optimal_match_sequence.unshift m k = m.i - 1 l-- optimal_match_sequence for k in [0...n] for m in matches_by_j[k] if m.i > 0 for l of optimal.m[m.i - 1] l = parseInt(l) update(m, l + 1) else update(m, 1) bruteforce_update(k) optimal_match_sequence = unwind(n) optimal_l = optimal_match_sequence.length # corner: empty password if password.length == 0 guesses = 1 else guesses = optimal.g[n - 1][optimal_l] # final result object password: <PASSWORD> guesses: guesses guesses_log10: @log10 guesses sequence: optimal_match_sequence # ------------------------------------------------------------------------------ # guess estimation -- one function per match pattern --------------------------- # ------------------------------------------------------------------------------ estimate_guesses: (match, password) -> return match.guesses if match.guesses? # a match's guess estimate doesn't change. cache it. min_guesses = 1 if match.token.length < password.length min_guesses = if match.token.length == 1 MIN_SUBMATCH_GUESSES_SINGLE_CHAR else MIN_SUBMATCH_GUESSES_MULTI_CHAR estimation_functions = bruteforce: @bruteforce_guesses dictionary: @dictionary_guesses spatial: @spatial_guesses repeat: @repeat_guesses sequence: @sequence_guesses regex: @regex_guesses date: @date_guesses guesses = estimation_functions[match.pattern].call this, match match.guesses = Math.max guesses, min_guesses match.guesses_log10 = @log10 match.guesses match.guesses bruteforce_guesses: (match) -> guesses = Math.pow BRUTEFORCE_CARDINALITY, match.token.length # small detail: make bruteforce matches at minimum one guess bigger than smallest allowed # submatch guesses, such that non-bruteforce submatches over the same [i..j] take precedence. min_guesses = if match.token.length == 1 MIN_SUBMATCH_GUESSES_SINGLE_CHAR + 1 else MIN_SUBMATCH_GUESSES_MULTI_CHAR + 1 Math.max guesses, min_guesses repeat_guesses: (match) -> match.base_guesses * match.repeat_count sequence_guesses: (match) -> first_chr = match.token.charAt(0) # lower guesses for obvious starting points if first_chr in ['a', 'A', 'z', 'Z', '0', '1', '9'] base_guesses = 4 else if first_chr.match /\d/ base_guesses = 10 # digits else # could give a higher base for uppercase, # assigning 26 to both upper and lower sequences is more conservative. base_guesses = 26 if not match.ascending # need to try a descending sequence in addition to every ascending sequence -> # 2x guesses base_guesses *= 2 base_guesses * match.token.length MIN_YEAR_SPACE: 20 REFERENCE_YEAR: 2016 regex_guesses: (match) -> char_class_bases = alpha_lower: 26 alpha_upper: 26 alpha: 52 alphanumeric: 62 digits: 10 symbols: 33 if match.regex_name of char_class_bases Math.pow(char_class_bases[match.regex_name], match.token.length) else switch match.regex_name when 'recent_year' # conservative estimate of year space: num years from REFERENCE_YEAR. # if year is close to REFERENCE_YEAR, estimate a year space of MIN_YEAR_SPACE. year_space = Math.abs parseInt(match.regex_match[0]) - @REFERENCE_YEAR year_space = Math.max year_space, @MIN_YEAR_SPACE year_space date_guesses: (match) -> # base guesses: (year distance from REFERENCE_YEAR) * num_days * num_years year_space = Math.max(Math.abs(match.year - @REFERENCE_YEAR), @MIN_YEAR_SPACE) guesses = year_space * 365 # add factor of 4 for separator selection (one of ~4 choices) guesses *= 4 if match.separator guesses KEYBOARD_AVERAGE_DEGREE: calc_average_degree(adjacency_graphs.qwerty) # slightly different for keypad/mac keypad, but close enough KEYPAD_AVERAGE_DEGREE: calc_average_degree(adjacency_graphs.keypad) KEYBOARD_STARTING_POSITIONS: (k for k,v of adjacency_graphs.qwerty).length KEYPAD_STARTING_POSITIONS: (k for k,v of adjacency_graphs.keypad).length spatial_guesses: (match) -> if match.graph in ['qwerty', 'dvorak'] s = @KEYBOARD_STARTING_POSITIONS d = @KEYBOARD_AVERAGE_DEGREE else s = @KEYPAD_STARTING_POSITIONS d = @KEYPAD_AVERAGE_DEGREE guesses = 0 L = match.token.length t = match.turns # estimate the number of possible patterns w/ length L or less with t turns or less. for i in [2..L] possible_turns = Math.min(t, i - 1) for j in [1..possible_turns] guesses += @nCk(i - 1, j - 1) * s * Math.pow(d, j) # add extra guesses for shifted keys. (% instead of 5, A instead of a.) # math is similar to extra guesses of l33t substitutions in dictionary matches. if match.shifted_count S = match.shifted_count U = match.token.length - match.shifted_count # unshifted count if S == 0 or U == 0 guesses *= 2 else shifted_variations = 0 shifted_variations += @nCk(S + U, i) for i in [1..Math.min(S, U)] guesses *= shifted_variations guesses dictionary_guesses: (match) -> match.base_guesses = match.rank # keep these as properties for display purposes match.uppercase_variations = @uppercase_variations match match.l33t_variations = @l33t_variations match reversed_variations = match.reversed and 2 or 1 match.base_guesses * match.uppercase_variations * match.l33t_variations * reversed_variations START_UPPER: /^[A-Z][^A-Z]+$/ END_UPPER: /^[^A-Z]+[A-Z]$/ ALL_UPPER: /^[^a-z]+$/ ALL_LOWER: /^[^A-Z]+$/ uppercase_variations: (match) -> word = match.token return 1 if word.match(@ALL_LOWER) or word.toLowerCase() == word # a capitalized word is the most common capitalization scheme, # so it only doubles the search space (uncapitalized + capitalized). # allcaps and end-capitalized are common enough too, underestimate as 2x factor to be safe. for regex in [@START_UPPER, @END_UPPER, @ALL_UPPER] return 2 if word.match regex # otherwise calculate the number of ways to capitalize U+L uppercase+lowercase letters # with U uppercase letters or less. or, if there's more uppercase than lower (for eg. PASSwORD), # the number of ways to lowercase U+L letters with L lowercase letters or less. U = (chr for chr in word.split('') when chr.match /[A-Z]/).length L = (chr for chr in word.split('') when chr.match /[a-z]/).length variations = 0 variations += @nCk(U + L, i) for i in [1..Math.min(U, L)] variations l33t_variations: (match) -> return 1 if not match.l33t variations = 1 for subbed, unsubbed of match.sub # lower-case match.token before calculating: capitalization shouldn't affect l33t calc. chrs = match.token.toLowerCase().split('') S = (chr for chr in chrs when chr == subbed).length # num of subbed chars U = (chr for chr in chrs when chr == unsubbed).length # num of unsubbed chars if S == 0 or U == 0 # for this sub, password is either fully subbed (444) or fully unsubbed (aaa) # treat that as doubling the space (attacker needs to try fully subbed chars in addition to # unsubbed.) variations *= 2 else # this case is similar to capitalization: # with aa44a, U = 3, S = 2, attacker needs to try unsubbed + one sub + two subs p = Math.min(U, S) possibilities = 0 possibilities += @nCk(U + S, i) for i in [1..p] variations *= possibilities variations # utilities -------------------------------------------------------------------- module.exports = scoring
true
adjacency_graphs = require('./adjacency_graphs') # on qwerty, 'g' has degree 6, being adjacent to 'ftyhbv'. '\' has degree 1. # this calculates the average over all keys. calc_average_degree = (graph) -> average = 0 for key, neighbors of graph average += (n for n in neighbors when n).length average /= (k for k,v of graph).length average BRUTEFORCE_CARDINALITY = 10 MIN_GUESSES_BEFORE_GROWING_SEQUENCE = 10000 MIN_SUBMATCH_GUESSES_SINGLE_CHAR = 10 MIN_SUBMATCH_GUESSES_MULTI_CHAR = 50 scoring = nCk: (n, k) -> # http://blog.plover.com/math/choose.html return 0 if k > n return 1 if k == 0 r = 1 for d in [1..k] r *= n r /= d n -= 1 r log10: (n) -> Math.log(n) / Math.log(10) # IE doesn't support Math.log10 :( log2: (n) -> Math.log(n) / Math.log(2) factorial: (n) -> # unoptimized, called only on small n return 1 if n < 2 f = 1 f *= i for i in [2..n] f # ------------------------------------------------------------------------------ # search --- most guessable match sequence ------------------------------------- # ------------------------------------------------------------------------------ # # takes a sequence of overlapping matches, returns the non-overlapping sequence with # minimum guesses. the following is a O(l_max * (n + m)) dynamic programming algorithm # for a length-n password with m candidate matches. l_max is the maximum optimal # sequence length spanning each prefix of the password. In practice it rarely exceeds 5 and the # search terminates rapidly. # # the optimal "minimum guesses" sequence is here defined to be the sequence that # minimizes the following function: # # g = l! * Product(m.guesses for m in sequence) + D^(l - 1) # # where l is the length of the sequence. # # the factorial term is the number of ways to order l patterns. # # the D^(l-1) term is another length penalty, roughly capturing the idea that an # attacker will try lower-length sequences first before trying length-l sequences. # # for example, consider a sequence that is date-repeat-dictionary. # - an attacker would need to try other date-repeat-dictionary combinations, # hence the product term. # - an attacker would need to try repeat-date-dictionary, dictionary-repeat-date, # ..., hence the factorial term. # - an attacker would also likely try length-1 (dictionary) and length-2 (dictionary-date) # sequences before length-3. assuming at minimum D guesses per pattern type, # D^(l-1) approximates Sum(D^i for i in [1..l-1] # # ------------------------------------------------------------------------------ most_guessable_match_sequence: (password, matches, _exclude_additive=false) -> n = password.length # partition matches into sublists according to ending index j matches_by_j = ([] for _ in [0...n]) for m in matches matches_by_j[m.j].push m # small detail: for deterministic output, sort each sublist by i. for lst in matches_by_j lst.sort (m1, m2) -> m1.i - m2.i optimal = # optimal.m[k][l] holds final match in the best length-l match sequence covering the # password prefix up to k, inclusive. # if there is no length-l sequence that scores better (fewer guesses) than # a shorter match sequence spanning the same prefix, optimal.m[k][l] is undefined. m: ({} for _ in [0...n]) # same structure as optimal.m -- holds the product term Prod(m.guesses for m in sequence). # optimal.pi allows for fast (non-looping) updates to the minimization function. pi: ({} for _ in [0...n]) # same structure as optimal.m -- holds the overall metric. g: ({} for _ in [0...n]) # helper: considers whether a length-l sequence ending at match m is better (fewer guesses) # than previously encountered sequences, updating state if so. update = (m, l) => k = m.j pi = @estimate_guesses m, password if l > 1 # we're considering a length-l sequence ending with match m: # obtain the product term in the minimization function by multiplying m's guesses # by the product of the length-(l-1) sequence ending just before m, at m.i - 1. pi *= optimal.pi[m.i - 1][l - 1] # calculate the minimization func g = @factorial(l) * pi unless _exclude_additive g += Math.pow(MIN_GUESSES_BEFORE_GROWING_SEQUENCE, l - 1) # update state if new best. # first see if any competing sequences covering this prefix, with l or fewer matches, # fare better than this sequence. if so, skip it and return. for competing_l, competing_g of optimal.g[k] continue if competing_l > l return if competing_g <= g # this sequence might be part of the final optimal sequence. optimal.g[k][l] = g optimal.m[k][l] = m optimal.pi[k][l] = pi # helper: evaluate bruteforce matches ending at k. bruteforce_update = (k) => # see if a single bruteforce match spanning the k-prefix is optimal. m = make_bruteforce_match(0, k) update(m, 1) for i in [1..k] # generate k bruteforce matches, spanning from (i=1, j=k) up to (i=k, j=k). # see if adding these new matches to any of the sequences in optimal[i-1] # leads to new bests. m = make_bruteforce_match(i, k) for l, last_m of optimal.m[i-1] l = parseInt(l) # corner: an optimal sequence will never have two adjacent bruteforce matches. # it is strictly better to have a single bruteforce match spanning the same region: # same contribution to the guess product with a lower length. # --> safe to skip those cases. continue if last_m.pattern == 'bruteforce' # try adding m to this length-l sequence. update(m, l + 1) # helper: make bruteforce match objects spanning i to j, inclusive. make_bruteforce_match = (i, j) => pattern: 'bruteforce' token: password[i..j] i: i j: j # helper: step backwards through optimal.m starting at the end, # constructing the final optimal match sequence. unwind = (n) => optimal_match_sequence = [] k = n - 1 # find the final best sequence length and score l = undefined g = Infinity for candidate_l, candidate_g of optimal.g[k] if candidate_g < g l = candidate_l g = candidate_g while k >= 0 m = optimal.m[k][l] optimal_match_sequence.unshift m k = m.i - 1 l-- optimal_match_sequence for k in [0...n] for m in matches_by_j[k] if m.i > 0 for l of optimal.m[m.i - 1] l = parseInt(l) update(m, l + 1) else update(m, 1) bruteforce_update(k) optimal_match_sequence = unwind(n) optimal_l = optimal_match_sequence.length # corner: empty password if password.length == 0 guesses = 1 else guesses = optimal.g[n - 1][optimal_l] # final result object password: PI:PASSWORD:<PASSWORD>END_PI guesses: guesses guesses_log10: @log10 guesses sequence: optimal_match_sequence # ------------------------------------------------------------------------------ # guess estimation -- one function per match pattern --------------------------- # ------------------------------------------------------------------------------ estimate_guesses: (match, password) -> return match.guesses if match.guesses? # a match's guess estimate doesn't change. cache it. min_guesses = 1 if match.token.length < password.length min_guesses = if match.token.length == 1 MIN_SUBMATCH_GUESSES_SINGLE_CHAR else MIN_SUBMATCH_GUESSES_MULTI_CHAR estimation_functions = bruteforce: @bruteforce_guesses dictionary: @dictionary_guesses spatial: @spatial_guesses repeat: @repeat_guesses sequence: @sequence_guesses regex: @regex_guesses date: @date_guesses guesses = estimation_functions[match.pattern].call this, match match.guesses = Math.max guesses, min_guesses match.guesses_log10 = @log10 match.guesses match.guesses bruteforce_guesses: (match) -> guesses = Math.pow BRUTEFORCE_CARDINALITY, match.token.length # small detail: make bruteforce matches at minimum one guess bigger than smallest allowed # submatch guesses, such that non-bruteforce submatches over the same [i..j] take precedence. min_guesses = if match.token.length == 1 MIN_SUBMATCH_GUESSES_SINGLE_CHAR + 1 else MIN_SUBMATCH_GUESSES_MULTI_CHAR + 1 Math.max guesses, min_guesses repeat_guesses: (match) -> match.base_guesses * match.repeat_count sequence_guesses: (match) -> first_chr = match.token.charAt(0) # lower guesses for obvious starting points if first_chr in ['a', 'A', 'z', 'Z', '0', '1', '9'] base_guesses = 4 else if first_chr.match /\d/ base_guesses = 10 # digits else # could give a higher base for uppercase, # assigning 26 to both upper and lower sequences is more conservative. base_guesses = 26 if not match.ascending # need to try a descending sequence in addition to every ascending sequence -> # 2x guesses base_guesses *= 2 base_guesses * match.token.length MIN_YEAR_SPACE: 20 REFERENCE_YEAR: 2016 regex_guesses: (match) -> char_class_bases = alpha_lower: 26 alpha_upper: 26 alpha: 52 alphanumeric: 62 digits: 10 symbols: 33 if match.regex_name of char_class_bases Math.pow(char_class_bases[match.regex_name], match.token.length) else switch match.regex_name when 'recent_year' # conservative estimate of year space: num years from REFERENCE_YEAR. # if year is close to REFERENCE_YEAR, estimate a year space of MIN_YEAR_SPACE. year_space = Math.abs parseInt(match.regex_match[0]) - @REFERENCE_YEAR year_space = Math.max year_space, @MIN_YEAR_SPACE year_space date_guesses: (match) -> # base guesses: (year distance from REFERENCE_YEAR) * num_days * num_years year_space = Math.max(Math.abs(match.year - @REFERENCE_YEAR), @MIN_YEAR_SPACE) guesses = year_space * 365 # add factor of 4 for separator selection (one of ~4 choices) guesses *= 4 if match.separator guesses KEYBOARD_AVERAGE_DEGREE: calc_average_degree(adjacency_graphs.qwerty) # slightly different for keypad/mac keypad, but close enough KEYPAD_AVERAGE_DEGREE: calc_average_degree(adjacency_graphs.keypad) KEYBOARD_STARTING_POSITIONS: (k for k,v of adjacency_graphs.qwerty).length KEYPAD_STARTING_POSITIONS: (k for k,v of adjacency_graphs.keypad).length spatial_guesses: (match) -> if match.graph in ['qwerty', 'dvorak'] s = @KEYBOARD_STARTING_POSITIONS d = @KEYBOARD_AVERAGE_DEGREE else s = @KEYPAD_STARTING_POSITIONS d = @KEYPAD_AVERAGE_DEGREE guesses = 0 L = match.token.length t = match.turns # estimate the number of possible patterns w/ length L or less with t turns or less. for i in [2..L] possible_turns = Math.min(t, i - 1) for j in [1..possible_turns] guesses += @nCk(i - 1, j - 1) * s * Math.pow(d, j) # add extra guesses for shifted keys. (% instead of 5, A instead of a.) # math is similar to extra guesses of l33t substitutions in dictionary matches. if match.shifted_count S = match.shifted_count U = match.token.length - match.shifted_count # unshifted count if S == 0 or U == 0 guesses *= 2 else shifted_variations = 0 shifted_variations += @nCk(S + U, i) for i in [1..Math.min(S, U)] guesses *= shifted_variations guesses dictionary_guesses: (match) -> match.base_guesses = match.rank # keep these as properties for display purposes match.uppercase_variations = @uppercase_variations match match.l33t_variations = @l33t_variations match reversed_variations = match.reversed and 2 or 1 match.base_guesses * match.uppercase_variations * match.l33t_variations * reversed_variations START_UPPER: /^[A-Z][^A-Z]+$/ END_UPPER: /^[^A-Z]+[A-Z]$/ ALL_UPPER: /^[^a-z]+$/ ALL_LOWER: /^[^A-Z]+$/ uppercase_variations: (match) -> word = match.token return 1 if word.match(@ALL_LOWER) or word.toLowerCase() == word # a capitalized word is the most common capitalization scheme, # so it only doubles the search space (uncapitalized + capitalized). # allcaps and end-capitalized are common enough too, underestimate as 2x factor to be safe. for regex in [@START_UPPER, @END_UPPER, @ALL_UPPER] return 2 if word.match regex # otherwise calculate the number of ways to capitalize U+L uppercase+lowercase letters # with U uppercase letters or less. or, if there's more uppercase than lower (for eg. PASSwORD), # the number of ways to lowercase U+L letters with L lowercase letters or less. U = (chr for chr in word.split('') when chr.match /[A-Z]/).length L = (chr for chr in word.split('') when chr.match /[a-z]/).length variations = 0 variations += @nCk(U + L, i) for i in [1..Math.min(U, L)] variations l33t_variations: (match) -> return 1 if not match.l33t variations = 1 for subbed, unsubbed of match.sub # lower-case match.token before calculating: capitalization shouldn't affect l33t calc. chrs = match.token.toLowerCase().split('') S = (chr for chr in chrs when chr == subbed).length # num of subbed chars U = (chr for chr in chrs when chr == unsubbed).length # num of unsubbed chars if S == 0 or U == 0 # for this sub, password is either fully subbed (444) or fully unsubbed (aaa) # treat that as doubling the space (attacker needs to try fully subbed chars in addition to # unsubbed.) variations *= 2 else # this case is similar to capitalization: # with aa44a, U = 3, S = 2, attacker needs to try unsubbed + one sub + two subs p = Math.min(U, S) possibilities = 0 possibilities += @nCk(U + S, i) for i in [1..p] variations *= possibilities variations # utilities -------------------------------------------------------------------- module.exports = scoring
[ { "context": "aultHeaders()\n\t\t\t\t\tbody: JSON.stringify({ email: 'user1@mail.com', password: '123456' })\n\t\t\t\t},\n\t\t\t\t(jqXHR) -> sto", "end": 2461, "score": 0.9999163150787354, "start": 2447, "tag": "EMAIL", "value": "user1@mail.com" }, { "context": "N.stringify({ email: ...
app/assets/javascripts/app.coffee
adrianhurt/play-api-rest-tester
16
define ['jquery', 'bootstrap', 'requests', 'jsonview'], ($, bootstrap, requests, jsonview) -> makeRequest = -> withApiUrl (apiUrl) -> request = $('#request').val().replace(/^\//, '') if isEmpty(request) alert 'The Request is required' else $('.response-empty, .response').addClass('hidden') $('.response-loading').removeClass('hidden') method = getMethod() data = { url: apiUrl + '/' + request method: method headers: getHeaders() body: if bodyIsRequired(method) then $('#request-body').val() else '' } console.log '\n-----------------------------\nRequest: '+data.method + ' - ' + data.url console.log '\t' + (k+': '+v for k, v of data.headers).join('\n\t') if data.body.length > 0 try console.log JSON.parse(data.body) catch e console.log e crossDomain data, (jqXHR) -> showResponse(jqXHR, request), (jqXHR) -> showResponse(jqXHR, request) showResponse = (jqXHR, request) -> data = jqXHR.responseJSON body = if (Object.prototype.toString.call(data.body) == '[object String]') then '"' + data.body + '"' else data.body console.log "\nResponse: #{data.status} #{data.statusText}" console.log '\t' + data.headers.join('\n\t') console.log body console.log '-----------------------------\n\n\n' $('#response-status').removeClass('success error').addClass(if data.status < 400 then 'success' else 'error') $('#response-status-code').text(data.status) $('#response-status-text').text(data.statusText) $('#response-headers').html(data.headers.join('<br>')) if body != undefined showJsonView $('#response-body'), body else $('#response-body').html('') $('.response-empty, .response-loading').addClass('hidden') $('.response').removeClass('hidden') switch request when 'signin' then storeToken(body.token) when 'signout' then removeToken() setPreparedRequest = (reqName) -> {secured, method, uri, body} = requests.prepared(reqName) selectMethod(method) $('#request').val(if $('#enveloped').prop('checked') then envelope(uri) else uri) $('#checkbox-token').prop('checked', secured) $('#request-body').val(JSON.stringify(body, null, 2)) signIn = -> withApiUrl (apiUrl) -> $('#signin').button('loading') crossDomain { url: apiUrl + '/signin' method: 'POST' headers: getDefaultHeaders() body: JSON.stringify({ email: 'user1@mail.com', password: '123456' }) }, (jqXHR) -> storeToken(jqXHR.responseJSON.body.token), (jqXHR) -> console.log jqXHR ; alert('Error while trying to sign in'), (jqXHR) -> $('#signin').button('reset') signOut = -> withApiUrl (apiUrl) -> headers = getDefaultHeaders(true) tokenHeader = headers['X-Auth-Token'] if tokenHeader != undefined and tokenHeader.length > 0 $('#signout').button('loading') crossDomain { url: apiUrl + '/signout' method: 'POST' headers: headers body: '' }, (jqXHR) -> removeToken(), (jqXHR) -> console.log jqXHR ; alert('Error while trying to sign out'), (jqXHR) -> $('#signout').button('reset') else removeToken() ####################################################### # UTILS isEmpty = (str) -> not str? or str.length == 0 bodyIsRequired = (method) -> !(method == 'GET' or method == 'DELETE') selectMethod = (method) -> $('#method-selector label[method='+method+']').addClass('active').siblings().removeClass('active') if bodyIsRequired(method) $('#request-body-section').removeClass('hidden') else $('#request-body-section').addClass('hidden') getMethod = -> $('#method-selector label.active').attr('method') envelopeRequest = (envelopeOrNot) -> req = $('#request').val() $('#request').val(if envelopeOrNot then envelope(req) else unenvelope(req)) unenvelope = (req) -> req.replace(/&envelope=[^&]*/ig, '').replace(/[?&]envelope=\w*$/i, '').replace(/\?envelope=\w*&/ig, '?') envelope = (req) -> unenveloped = unenvelope(req) separator = if unenveloped.indexOf('?') == -1 then '?' else '&' unenveloped + separator + 'envelope=true' withApiUrl = (f) -> apiUrl = $('#apiurl').val().replace(/\/$/, '') if isEmpty(apiUrl) alert 'The API URL is required' else f(apiUrl) getDefaultHeaders = (withToken = false) -> headers = {} for tr in $('#request-headers tr') [key, value] = [$(tr).find('td.key').text(), $(tr).find('input[type=text]').attr('value')] if withToken or key != 'X-Auth-Token' headers[key] = value headers getHeaders = -> headers = {} for tr in $('#request-headers tr') if $(tr).find('input[type=checkbox]').prop('checked') [key, value] = [$(tr).find('td.key').text(), $(tr).find('input[type=text]').val()] headers[key] = value headers crossDomain = (data, doneFunc, failFunc, alwaysFunc = (x) -> null) -> $.ajax { url: '/proxy' method: 'POST' contentType: 'application/json' data: JSON.stringify(data) } .done (data, textStatus, jqXHR) -> doneFunc(jqXHR) ; alwaysFunc(jqXHR) .fail (jqXHR, textStatus, err) -> failFunc(jqXHR) ; alwaysFunc(jqXHR) storeToken = (token) -> if token? and token.length > 0 $('#checkbox-token').prop('checked', true) $('#token').val(token).attr('value', token) removeToken = -> $('#checkbox-token').prop('checked', false) $('#token').removeAttr('value') showJsonView = ($el, js) -> $el.JSONView(js, {collapsed: !Array.isArray(js)}) ####################################################### # Document ready $ -> $('#method-selector label[method]').click -> selectMethod($(this).attr('method')) $('#test-button').click -> makeRequest() $('#request').keyup (e) -> if(e.which == 13) then makeRequest() $('#test-list a[req]').click -> setPreparedRequest($(this).attr('req')) $('#signin').click -> signIn() $('#signout').click -> signOut() $('#enveloped').change -> envelopeRequest($(this).prop('checked')) $('[data-toggle="tooltip"]').tooltip()
206567
define ['jquery', 'bootstrap', 'requests', 'jsonview'], ($, bootstrap, requests, jsonview) -> makeRequest = -> withApiUrl (apiUrl) -> request = $('#request').val().replace(/^\//, '') if isEmpty(request) alert 'The Request is required' else $('.response-empty, .response').addClass('hidden') $('.response-loading').removeClass('hidden') method = getMethod() data = { url: apiUrl + '/' + request method: method headers: getHeaders() body: if bodyIsRequired(method) then $('#request-body').val() else '' } console.log '\n-----------------------------\nRequest: '+data.method + ' - ' + data.url console.log '\t' + (k+': '+v for k, v of data.headers).join('\n\t') if data.body.length > 0 try console.log JSON.parse(data.body) catch e console.log e crossDomain data, (jqXHR) -> showResponse(jqXHR, request), (jqXHR) -> showResponse(jqXHR, request) showResponse = (jqXHR, request) -> data = jqXHR.responseJSON body = if (Object.prototype.toString.call(data.body) == '[object String]') then '"' + data.body + '"' else data.body console.log "\nResponse: #{data.status} #{data.statusText}" console.log '\t' + data.headers.join('\n\t') console.log body console.log '-----------------------------\n\n\n' $('#response-status').removeClass('success error').addClass(if data.status < 400 then 'success' else 'error') $('#response-status-code').text(data.status) $('#response-status-text').text(data.statusText) $('#response-headers').html(data.headers.join('<br>')) if body != undefined showJsonView $('#response-body'), body else $('#response-body').html('') $('.response-empty, .response-loading').addClass('hidden') $('.response').removeClass('hidden') switch request when 'signin' then storeToken(body.token) when 'signout' then removeToken() setPreparedRequest = (reqName) -> {secured, method, uri, body} = requests.prepared(reqName) selectMethod(method) $('#request').val(if $('#enveloped').prop('checked') then envelope(uri) else uri) $('#checkbox-token').prop('checked', secured) $('#request-body').val(JSON.stringify(body, null, 2)) signIn = -> withApiUrl (apiUrl) -> $('#signin').button('loading') crossDomain { url: apiUrl + '/signin' method: 'POST' headers: getDefaultHeaders() body: JSON.stringify({ email: '<EMAIL>', password: '<PASSWORD>' }) }, (jqXHR) -> storeToken(jqXHR.responseJSON.body.token), (jqXHR) -> console.log jqXHR ; alert('Error while trying to sign in'), (jqXHR) -> $('#signin').button('reset') signOut = -> withApiUrl (apiUrl) -> headers = getDefaultHeaders(true) tokenHeader = headers['X-Auth-Token'] if tokenHeader != undefined and tokenHeader.length > 0 $('#signout').button('loading') crossDomain { url: apiUrl + '/signout' method: 'POST' headers: headers body: '' }, (jqXHR) -> removeToken(), (jqXHR) -> console.log jqXHR ; alert('Error while trying to sign out'), (jqXHR) -> $('#signout').button('reset') else removeToken() ####################################################### # UTILS isEmpty = (str) -> not str? or str.length == 0 bodyIsRequired = (method) -> !(method == 'GET' or method == 'DELETE') selectMethod = (method) -> $('#method-selector label[method='+method+']').addClass('active').siblings().removeClass('active') if bodyIsRequired(method) $('#request-body-section').removeClass('hidden') else $('#request-body-section').addClass('hidden') getMethod = -> $('#method-selector label.active').attr('method') envelopeRequest = (envelopeOrNot) -> req = $('#request').val() $('#request').val(if envelopeOrNot then envelope(req) else unenvelope(req)) unenvelope = (req) -> req.replace(/&envelope=[^&]*/ig, '').replace(/[?&]envelope=\w*$/i, '').replace(/\?envelope=\w*&/ig, '?') envelope = (req) -> unenveloped = unenvelope(req) separator = if unenveloped.indexOf('?') == -1 then '?' else '&' unenveloped + separator + 'envelope=true' withApiUrl = (f) -> apiUrl = $('#apiurl').val().replace(/\/$/, '') if isEmpty(apiUrl) alert 'The API URL is required' else f(apiUrl) getDefaultHeaders = (withToken = false) -> headers = {} for tr in $('#request-headers tr') [key, value] = [$(tr).find('td.key').text(), $(tr).find('input[type=text]').attr('value')] if withToken or key != 'X-Auth-Token' headers[key] = value headers getHeaders = -> headers = {} for tr in $('#request-headers tr') if $(tr).find('input[type=checkbox]').prop('checked') [key, value] = [$(tr).find('td.key').text(), $(tr).find('input[type=text]').val()] headers[key] = value headers crossDomain = (data, doneFunc, failFunc, alwaysFunc = (x) -> null) -> $.ajax { url: '/proxy' method: 'POST' contentType: 'application/json' data: JSON.stringify(data) } .done (data, textStatus, jqXHR) -> doneFunc(jqXHR) ; alwaysFunc(jqXHR) .fail (jqXHR, textStatus, err) -> failFunc(jqXHR) ; alwaysFunc(jqXHR) storeToken = (token) -> if token? and token.length > 0 $('#checkbox-token').prop('checked', true) $('#token').val(token).attr('value', token) removeToken = -> $('#checkbox-token').prop('checked', false) $('#token').removeAttr('value') showJsonView = ($el, js) -> $el.JSONView(js, {collapsed: !Array.isArray(js)}) ####################################################### # Document ready $ -> $('#method-selector label[method]').click -> selectMethod($(this).attr('method')) $('#test-button').click -> makeRequest() $('#request').keyup (e) -> if(e.which == 13) then makeRequest() $('#test-list a[req]').click -> setPreparedRequest($(this).attr('req')) $('#signin').click -> signIn() $('#signout').click -> signOut() $('#enveloped').change -> envelopeRequest($(this).prop('checked')) $('[data-toggle="tooltip"]').tooltip()
true
define ['jquery', 'bootstrap', 'requests', 'jsonview'], ($, bootstrap, requests, jsonview) -> makeRequest = -> withApiUrl (apiUrl) -> request = $('#request').val().replace(/^\//, '') if isEmpty(request) alert 'The Request is required' else $('.response-empty, .response').addClass('hidden') $('.response-loading').removeClass('hidden') method = getMethod() data = { url: apiUrl + '/' + request method: method headers: getHeaders() body: if bodyIsRequired(method) then $('#request-body').val() else '' } console.log '\n-----------------------------\nRequest: '+data.method + ' - ' + data.url console.log '\t' + (k+': '+v for k, v of data.headers).join('\n\t') if data.body.length > 0 try console.log JSON.parse(data.body) catch e console.log e crossDomain data, (jqXHR) -> showResponse(jqXHR, request), (jqXHR) -> showResponse(jqXHR, request) showResponse = (jqXHR, request) -> data = jqXHR.responseJSON body = if (Object.prototype.toString.call(data.body) == '[object String]') then '"' + data.body + '"' else data.body console.log "\nResponse: #{data.status} #{data.statusText}" console.log '\t' + data.headers.join('\n\t') console.log body console.log '-----------------------------\n\n\n' $('#response-status').removeClass('success error').addClass(if data.status < 400 then 'success' else 'error') $('#response-status-code').text(data.status) $('#response-status-text').text(data.statusText) $('#response-headers').html(data.headers.join('<br>')) if body != undefined showJsonView $('#response-body'), body else $('#response-body').html('') $('.response-empty, .response-loading').addClass('hidden') $('.response').removeClass('hidden') switch request when 'signin' then storeToken(body.token) when 'signout' then removeToken() setPreparedRequest = (reqName) -> {secured, method, uri, body} = requests.prepared(reqName) selectMethod(method) $('#request').val(if $('#enveloped').prop('checked') then envelope(uri) else uri) $('#checkbox-token').prop('checked', secured) $('#request-body').val(JSON.stringify(body, null, 2)) signIn = -> withApiUrl (apiUrl) -> $('#signin').button('loading') crossDomain { url: apiUrl + '/signin' method: 'POST' headers: getDefaultHeaders() body: JSON.stringify({ email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' }) }, (jqXHR) -> storeToken(jqXHR.responseJSON.body.token), (jqXHR) -> console.log jqXHR ; alert('Error while trying to sign in'), (jqXHR) -> $('#signin').button('reset') signOut = -> withApiUrl (apiUrl) -> headers = getDefaultHeaders(true) tokenHeader = headers['X-Auth-Token'] if tokenHeader != undefined and tokenHeader.length > 0 $('#signout').button('loading') crossDomain { url: apiUrl + '/signout' method: 'POST' headers: headers body: '' }, (jqXHR) -> removeToken(), (jqXHR) -> console.log jqXHR ; alert('Error while trying to sign out'), (jqXHR) -> $('#signout').button('reset') else removeToken() ####################################################### # UTILS isEmpty = (str) -> not str? or str.length == 0 bodyIsRequired = (method) -> !(method == 'GET' or method == 'DELETE') selectMethod = (method) -> $('#method-selector label[method='+method+']').addClass('active').siblings().removeClass('active') if bodyIsRequired(method) $('#request-body-section').removeClass('hidden') else $('#request-body-section').addClass('hidden') getMethod = -> $('#method-selector label.active').attr('method') envelopeRequest = (envelopeOrNot) -> req = $('#request').val() $('#request').val(if envelopeOrNot then envelope(req) else unenvelope(req)) unenvelope = (req) -> req.replace(/&envelope=[^&]*/ig, '').replace(/[?&]envelope=\w*$/i, '').replace(/\?envelope=\w*&/ig, '?') envelope = (req) -> unenveloped = unenvelope(req) separator = if unenveloped.indexOf('?') == -1 then '?' else '&' unenveloped + separator + 'envelope=true' withApiUrl = (f) -> apiUrl = $('#apiurl').val().replace(/\/$/, '') if isEmpty(apiUrl) alert 'The API URL is required' else f(apiUrl) getDefaultHeaders = (withToken = false) -> headers = {} for tr in $('#request-headers tr') [key, value] = [$(tr).find('td.key').text(), $(tr).find('input[type=text]').attr('value')] if withToken or key != 'X-Auth-Token' headers[key] = value headers getHeaders = -> headers = {} for tr in $('#request-headers tr') if $(tr).find('input[type=checkbox]').prop('checked') [key, value] = [$(tr).find('td.key').text(), $(tr).find('input[type=text]').val()] headers[key] = value headers crossDomain = (data, doneFunc, failFunc, alwaysFunc = (x) -> null) -> $.ajax { url: '/proxy' method: 'POST' contentType: 'application/json' data: JSON.stringify(data) } .done (data, textStatus, jqXHR) -> doneFunc(jqXHR) ; alwaysFunc(jqXHR) .fail (jqXHR, textStatus, err) -> failFunc(jqXHR) ; alwaysFunc(jqXHR) storeToken = (token) -> if token? and token.length > 0 $('#checkbox-token').prop('checked', true) $('#token').val(token).attr('value', token) removeToken = -> $('#checkbox-token').prop('checked', false) $('#token').removeAttr('value') showJsonView = ($el, js) -> $el.JSONView(js, {collapsed: !Array.isArray(js)}) ####################################################### # Document ready $ -> $('#method-selector label[method]').click -> selectMethod($(this).attr('method')) $('#test-button').click -> makeRequest() $('#request').keyup (e) -> if(e.which == 13) then makeRequest() $('#test-list a[req]').click -> setPreparedRequest($(this).attr('req')) $('#signin').click -> signIn() $('#signout').click -> signOut() $('#enveloped').change -> envelopeRequest($(this).prop('checked')) $('[data-toggle="tooltip"]').tooltip()
[ { "context": "', value: 'value1'}\n # {name: 'key2', value: 'value2'}\n # {name: 'key3', value: 'value3'}\n #]\n ", "end": 619, "score": 0.6220699548721313, "start": 613, "tag": "KEY", "value": "value2" }, { "context": "le.com', 'POST', [\n # { name: 'key1', value: 'va...
wms_stepper/app/assets/javascripts/stingre.js.coffee
Windermere/stepre
0
$ -> # Define namespace window.Stingre or= {} # Create a namespace and local reference window.Stingre.Helpers = class Helpers @nonajax_submit = (action, method, values) -> form = $('<form/>', { action: action method: method }) $.each values, -> form.append $('<input/>', { type: 'hidden' name: this.name value: this.value }) form.appendTo('body').submit(); # usage: # // coffee #non_ajax_submit 'http://www.example.com', 'POST', [ # {name: 'key1', value: 'value1'} # {name: 'key2', value: 'value2'} # {name: 'key3', value: 'value3'} #] # // regular #Stingre.Helpers.non_ajax_submit('http://www.example.com', 'POST', [ # { name: 'key1', value: 'value1' }, # { name: 'key2', value: 'value2' }, # { name: 'key3', value: 'value3' }, #]); @non_ajax_submit_format= (obj) -> array = [] $.each obj, (k,v) -> array.push({name: k, value: v}) return array @populate_form = (hash) -> form = $("#" + hash.elem) if form_data_raw = form.find("[name='form_data']").val() console.log form_data_raw form_data = JSON.parse($.base64.decode(form_data_raw)) hsh = form.serializeObject() console.log hsh hsh = Stingre.Helpers.data_delete(hsh, ["utf8","authenticity_token", "form_data"]) $.each hsh, (k,v) -> base = k.replace(/\[/, "_").replace(/\]/, "") el = "#" + base key = base.replace(hash.prefix + "_", "") console.log key form.find(el).val(form_data[key]) @cas_submit = (hash) -> $("#prev_button").click (e) -> $(this).closest("form").append $('<input/>', { type: 'hidden' name: 'prev_button' value: 'true' }) $("#" + hash.elem).submit (e) -> form = $(this) e.preventDefault() hsh = form.serializeObject() utf8 = hsh.utf8 authenticity_token = hsh.authenticity_token hsh64 = $.base64.encode(JSON.stringify(Stingre.Helpers.data_delete(hsh, ["utf8","authenticity_token"]))) form.delete $.ajax url: hash.url type: "POST" data: "{\"form_data\":\"#{hsh64}\", \"utf8\":\"#{utf8}\", \"authenticity_token\":\"#{authenticity_token}\"}" dataType: "json" contentType: "application/json; charset=utf-8" success: (res, textStatus, XMLHttpRequest) -> # post to cas console.log res Stingre.Helpers.nonajax_submit XMLHttpRequest.getResponseHeader('Location'), 'POST', Stingre.Helpers.non_ajax_submit_format({form_data: res.form_data, utf8: utf8, authenticity_token: authenticity_token}) error: (res, textStatus, XMLHttpRequest) -> json1 = JSON.parse res.responseText # remove prev errors form.find(".alert").remove() form.find(".help-inline").remove() form.find(".control-group").removeClass("error") # add errors to form if json1.base form.prepend('<div class="alert alert-error">' + json1.base.join() + '</div>') delete json1.base else form.prepend('<div class="alert alert-error">Please review the problems below:</div>') $.each json1, (k,v) -> elem2 = $("#" + hash.prefix + "_" + k) elem2.closest('.control-group').removeClass('success').addClass('error') console.log elem2.parent().prop("tagName") if elem2.parent().prop("tagName") is "LABEL" elem2.parent().after('<span class="help-inline">' + v.join() + '</span>') else if elem2.closest('.control-group').find(".help-block").length elem2.closest('.control-group').append('<span class="help-inline">' + v.join() + '</span>') else elem2.after('<span class="help-inline">' + v.join(" ") + '</span>') @data_delete = (obj, keys_array) -> $.each keys_array, (i,v) -> delete obj[v] return obj @validate_mlsagent = -> url = "/api/valid/mlsagent.json?user[company_companypublickey]=" + $("#user_company_companypublickey").val() + "&[user]user_mlsid=" + $("#user_user_mlsid").val() + "&[user]user_mlsagent=" + $("#user_user_mlsagent").val() $.getJSON url, (result) -> $(".mls_info .help-inline").remove() if result.valid_mlsagent.valid $(".validate_status").show().text("valid MLS info").removeClass("label-important").addClass("label-success") $(".mls_info .control-group").removeClass("error") $(".mls_info .control-group").addClass("success") $(".account_details input").prop('disabled', false) $(".account_details select").prop('disabled', false) $("[name=commit]").prop('disabled', false) #if $("#user_user_firstname_display").val() is "" _el = $("#user_user_firstname_display") _el.attr("value", result.valid_mlsagent.firstname) _el.closest('.control-group').removeClass('error') _el.closest('.control-group').find(".help-block").remove() #if $("#user_user_lastname_display").val() is "" _el = $("#user_user_lastname_display") _el.attr("value", result.valid_mlsagent.lastname) _el.closest('.control-group').removeClass('error') _el.closest('.control-group').find(".help-block").remove() else $(".validate_status").show().text("invalid MLS info").removeClass("label-success").addClass("label-important") $(".mls_info .control-group").removeClass("success") $(".mls_info .control-group").addClass("error") $("#user_user_firstname_display").removeAttr("value") $("#user_user_lastname_display").removeAttr("value") #if !$(".account_details .control-group").hasClass("error") # $(".account_details input").prop('disabled', true) # $(".account_details select").prop('disabled', true) # $("[name=commit]").prop('disabled', true) @_init = -> #focus on first field with error $(".control-group[class*=error] input").first().focus() $("#user_user_mlsagent").keypress (event) -> # http://bugs.jquery.com/ticket/2338 event = $.event.fix(event) if event.which is 13 event.preventDefault() #RJH - possible hack - grabbing the first fieldset of data for validating mls agent data url = "/api/valid/mlsagent.json?" + $("fieldset :first").serialize() Stingre.Helpers.validate_mlsagent(url) $("#validate_mlsagent").on "click", -> #RJH - possible hack - grabbing the first fieldset of data for validating mls agent data Stingre.Helpers.validate_mlsagent() # event elem_2 = $("[id$=_user_mlsid]") elem_2.on "change", -> Stingre.Helpers.toggle_agent_mls_id($(this)) # init @toggle_agent_mls_id(elem_2) @toggle_agent_mls_id = (elem) -> # enable second after selection of first elem_1 = $("[id$=_user_mlsagent]") #elem_2 = $("[id$=_user_mlsid]") $(".mls_info .control-group").removeClass("success") $(".validate_status").hide() if elem.val() is "" elem_1.val("").attr('disabled', 'disabled') else elem_1.removeAttr('disabled') $.fn.serializeObject = -> o = {} a = this.serializeArray() $.each a, -> if o[this.name] if !o[this.name].push o[this.name] = [o[this.name]] o[this.name].push(this.value || "") else o[this.name] = this.value || "" #console.log o return o
127136
$ -> # Define namespace window.Stingre or= {} # Create a namespace and local reference window.Stingre.Helpers = class Helpers @nonajax_submit = (action, method, values) -> form = $('<form/>', { action: action method: method }) $.each values, -> form.append $('<input/>', { type: 'hidden' name: this.name value: this.value }) form.appendTo('body').submit(); # usage: # // coffee #non_ajax_submit 'http://www.example.com', 'POST', [ # {name: 'key1', value: 'value1'} # {name: 'key2', value: '<KEY>'} # {name: 'key3', value: 'value3'} #] # // regular #Stingre.Helpers.non_ajax_submit('http://www.example.com', 'POST', [ # { name: 'key1', value: '<KEY>' }, # { name: 'key2', value: '<KEY>' }, # { name: 'key3', value: '<KEY>' }, #]); @non_ajax_submit_format= (obj) -> array = [] $.each obj, (k,v) -> array.push({name: k, value: v}) return array @populate_form = (hash) -> form = $("#" + hash.elem) if form_data_raw = form.find("[name='form_data']").val() console.log form_data_raw form_data = JSON.parse($.base64.decode(form_data_raw)) hsh = form.serializeObject() console.log hsh hsh = Stingre.Helpers.data_delete(hsh, ["utf8","authenticity_token", "form_data"]) $.each hsh, (k,v) -> base = k.replace(/\[/, "_").replace(/\]/, "") el = "#" + base key = base.replace(hash.prefix + "_", "") console.log key form.find(el).val(form_data[key]) @cas_submit = (hash) -> $("#prev_button").click (e) -> $(this).closest("form").append $('<input/>', { type: 'hidden' name: 'prev_button' value: 'true' }) $("#" + hash.elem).submit (e) -> form = $(this) e.preventDefault() hsh = form.serializeObject() utf8 = hsh.utf8 authenticity_token = hsh.authenticity_token hsh64 = $.base64.encode(JSON.stringify(Stingre.Helpers.data_delete(hsh, ["utf8","authenticity_token"]))) form.delete $.ajax url: hash.url type: "POST" data: "{\"form_data\":\"#{hsh64}\", \"utf8\":\"#{utf8}\", \"authenticity_token\":\"#{authenticity_token}\"}" dataType: "json" contentType: "application/json; charset=utf-8" success: (res, textStatus, XMLHttpRequest) -> # post to cas console.log res Stingre.Helpers.nonajax_submit XMLHttpRequest.getResponseHeader('Location'), 'POST', Stingre.Helpers.non_ajax_submit_format({form_data: res.form_data, utf8: utf8, authenticity_token: authenticity_token}) error: (res, textStatus, XMLHttpRequest) -> json1 = JSON.parse res.responseText # remove prev errors form.find(".alert").remove() form.find(".help-inline").remove() form.find(".control-group").removeClass("error") # add errors to form if json1.base form.prepend('<div class="alert alert-error">' + json1.base.join() + '</div>') delete json1.base else form.prepend('<div class="alert alert-error">Please review the problems below:</div>') $.each json1, (k,v) -> elem2 = $("#" + hash.prefix + "_" + k) elem2.closest('.control-group').removeClass('success').addClass('error') console.log elem2.parent().prop("tagName") if elem2.parent().prop("tagName") is "LABEL" elem2.parent().after('<span class="help-inline">' + v.join() + '</span>') else if elem2.closest('.control-group').find(".help-block").length elem2.closest('.control-group').append('<span class="help-inline">' + v.join() + '</span>') else elem2.after('<span class="help-inline">' + v.join(" ") + '</span>') @data_delete = (obj, keys_array) -> $.each keys_array, (i,v) -> delete obj[v] return obj @validate_mlsagent = -> url = "/api/valid/mlsagent.json?user[company_companypublickey]=" + $("#user_company_companypublickey").val() + "&[user]user_mlsid=" + $("#user_user_mlsid").val() + "&[user]user_mlsagent=" + $("#user_user_mlsagent").val() $.getJSON url, (result) -> $(".mls_info .help-inline").remove() if result.valid_mlsagent.valid $(".validate_status").show().text("valid MLS info").removeClass("label-important").addClass("label-success") $(".mls_info .control-group").removeClass("error") $(".mls_info .control-group").addClass("success") $(".account_details input").prop('disabled', false) $(".account_details select").prop('disabled', false) $("[name=commit]").prop('disabled', false) #if $("#user_user_firstname_display").val() is "" _el = $("#user_user_firstname_display") _el.attr("value", result.valid_mlsagent.firstname) _el.closest('.control-group').removeClass('error') _el.closest('.control-group').find(".help-block").remove() #if $("#user_user_lastname_display").val() is "" _el = $("#user_user_lastname_display") _el.attr("value", result.valid_mlsagent.lastname) _el.closest('.control-group').removeClass('error') _el.closest('.control-group').find(".help-block").remove() else $(".validate_status").show().text("invalid MLS info").removeClass("label-success").addClass("label-important") $(".mls_info .control-group").removeClass("success") $(".mls_info .control-group").addClass("error") $("#user_user_firstname_display").removeAttr("value") $("#user_user_lastname_display").removeAttr("value") #if !$(".account_details .control-group").hasClass("error") # $(".account_details input").prop('disabled', true) # $(".account_details select").prop('disabled', true) # $("[name=commit]").prop('disabled', true) @_init = -> #focus on first field with error $(".control-group[class*=error] input").first().focus() $("#user_user_mlsagent").keypress (event) -> # http://bugs.jquery.com/ticket/2338 event = $.event.fix(event) if event.which is 13 event.preventDefault() #RJH - possible hack - grabbing the first fieldset of data for validating mls agent data url = "/api/valid/mlsagent.json?" + $("fieldset :first").serialize() Stingre.Helpers.validate_mlsagent(url) $("#validate_mlsagent").on "click", -> #RJH - possible hack - grabbing the first fieldset of data for validating mls agent data Stingre.Helpers.validate_mlsagent() # event elem_2 = $("[id$=_user_mlsid]") elem_2.on "change", -> Stingre.Helpers.toggle_agent_mls_id($(this)) # init @toggle_agent_mls_id(elem_2) @toggle_agent_mls_id = (elem) -> # enable second after selection of first elem_1 = $("[id$=_user_mlsagent]") #elem_2 = $("[id$=_user_mlsid]") $(".mls_info .control-group").removeClass("success") $(".validate_status").hide() if elem.val() is "" elem_1.val("").attr('disabled', 'disabled') else elem_1.removeAttr('disabled') $.fn.serializeObject = -> o = {} a = this.serializeArray() $.each a, -> if o[this.name] if !o[this.name].push o[this.name] = [o[this.name]] o[this.name].push(this.value || "") else o[this.name] = this.value || "" #console.log o return o
true
$ -> # Define namespace window.Stingre or= {} # Create a namespace and local reference window.Stingre.Helpers = class Helpers @nonajax_submit = (action, method, values) -> form = $('<form/>', { action: action method: method }) $.each values, -> form.append $('<input/>', { type: 'hidden' name: this.name value: this.value }) form.appendTo('body').submit(); # usage: # // coffee #non_ajax_submit 'http://www.example.com', 'POST', [ # {name: 'key1', value: 'value1'} # {name: 'key2', value: 'PI:KEY:<KEY>END_PI'} # {name: 'key3', value: 'value3'} #] # // regular #Stingre.Helpers.non_ajax_submit('http://www.example.com', 'POST', [ # { name: 'key1', value: 'PI:KEY:<KEY>END_PI' }, # { name: 'key2', value: 'PI:KEY:<KEY>END_PI' }, # { name: 'key3', value: 'PI:KEY:<KEY>END_PI' }, #]); @non_ajax_submit_format= (obj) -> array = [] $.each obj, (k,v) -> array.push({name: k, value: v}) return array @populate_form = (hash) -> form = $("#" + hash.elem) if form_data_raw = form.find("[name='form_data']").val() console.log form_data_raw form_data = JSON.parse($.base64.decode(form_data_raw)) hsh = form.serializeObject() console.log hsh hsh = Stingre.Helpers.data_delete(hsh, ["utf8","authenticity_token", "form_data"]) $.each hsh, (k,v) -> base = k.replace(/\[/, "_").replace(/\]/, "") el = "#" + base key = base.replace(hash.prefix + "_", "") console.log key form.find(el).val(form_data[key]) @cas_submit = (hash) -> $("#prev_button").click (e) -> $(this).closest("form").append $('<input/>', { type: 'hidden' name: 'prev_button' value: 'true' }) $("#" + hash.elem).submit (e) -> form = $(this) e.preventDefault() hsh = form.serializeObject() utf8 = hsh.utf8 authenticity_token = hsh.authenticity_token hsh64 = $.base64.encode(JSON.stringify(Stingre.Helpers.data_delete(hsh, ["utf8","authenticity_token"]))) form.delete $.ajax url: hash.url type: "POST" data: "{\"form_data\":\"#{hsh64}\", \"utf8\":\"#{utf8}\", \"authenticity_token\":\"#{authenticity_token}\"}" dataType: "json" contentType: "application/json; charset=utf-8" success: (res, textStatus, XMLHttpRequest) -> # post to cas console.log res Stingre.Helpers.nonajax_submit XMLHttpRequest.getResponseHeader('Location'), 'POST', Stingre.Helpers.non_ajax_submit_format({form_data: res.form_data, utf8: utf8, authenticity_token: authenticity_token}) error: (res, textStatus, XMLHttpRequest) -> json1 = JSON.parse res.responseText # remove prev errors form.find(".alert").remove() form.find(".help-inline").remove() form.find(".control-group").removeClass("error") # add errors to form if json1.base form.prepend('<div class="alert alert-error">' + json1.base.join() + '</div>') delete json1.base else form.prepend('<div class="alert alert-error">Please review the problems below:</div>') $.each json1, (k,v) -> elem2 = $("#" + hash.prefix + "_" + k) elem2.closest('.control-group').removeClass('success').addClass('error') console.log elem2.parent().prop("tagName") if elem2.parent().prop("tagName") is "LABEL" elem2.parent().after('<span class="help-inline">' + v.join() + '</span>') else if elem2.closest('.control-group').find(".help-block").length elem2.closest('.control-group').append('<span class="help-inline">' + v.join() + '</span>') else elem2.after('<span class="help-inline">' + v.join(" ") + '</span>') @data_delete = (obj, keys_array) -> $.each keys_array, (i,v) -> delete obj[v] return obj @validate_mlsagent = -> url = "/api/valid/mlsagent.json?user[company_companypublickey]=" + $("#user_company_companypublickey").val() + "&[user]user_mlsid=" + $("#user_user_mlsid").val() + "&[user]user_mlsagent=" + $("#user_user_mlsagent").val() $.getJSON url, (result) -> $(".mls_info .help-inline").remove() if result.valid_mlsagent.valid $(".validate_status").show().text("valid MLS info").removeClass("label-important").addClass("label-success") $(".mls_info .control-group").removeClass("error") $(".mls_info .control-group").addClass("success") $(".account_details input").prop('disabled', false) $(".account_details select").prop('disabled', false) $("[name=commit]").prop('disabled', false) #if $("#user_user_firstname_display").val() is "" _el = $("#user_user_firstname_display") _el.attr("value", result.valid_mlsagent.firstname) _el.closest('.control-group').removeClass('error') _el.closest('.control-group').find(".help-block").remove() #if $("#user_user_lastname_display").val() is "" _el = $("#user_user_lastname_display") _el.attr("value", result.valid_mlsagent.lastname) _el.closest('.control-group').removeClass('error') _el.closest('.control-group').find(".help-block").remove() else $(".validate_status").show().text("invalid MLS info").removeClass("label-success").addClass("label-important") $(".mls_info .control-group").removeClass("success") $(".mls_info .control-group").addClass("error") $("#user_user_firstname_display").removeAttr("value") $("#user_user_lastname_display").removeAttr("value") #if !$(".account_details .control-group").hasClass("error") # $(".account_details input").prop('disabled', true) # $(".account_details select").prop('disabled', true) # $("[name=commit]").prop('disabled', true) @_init = -> #focus on first field with error $(".control-group[class*=error] input").first().focus() $("#user_user_mlsagent").keypress (event) -> # http://bugs.jquery.com/ticket/2338 event = $.event.fix(event) if event.which is 13 event.preventDefault() #RJH - possible hack - grabbing the first fieldset of data for validating mls agent data url = "/api/valid/mlsagent.json?" + $("fieldset :first").serialize() Stingre.Helpers.validate_mlsagent(url) $("#validate_mlsagent").on "click", -> #RJH - possible hack - grabbing the first fieldset of data for validating mls agent data Stingre.Helpers.validate_mlsagent() # event elem_2 = $("[id$=_user_mlsid]") elem_2.on "change", -> Stingre.Helpers.toggle_agent_mls_id($(this)) # init @toggle_agent_mls_id(elem_2) @toggle_agent_mls_id = (elem) -> # enable second after selection of first elem_1 = $("[id$=_user_mlsagent]") #elem_2 = $("[id$=_user_mlsid]") $(".mls_info .control-group").removeClass("success") $(".validate_status").hide() if elem.val() is "" elem_1.val("").attr('disabled', 'disabled') else elem_1.removeAttr('disabled') $.fn.serializeObject = -> o = {} a = this.serializeArray() $.each a, -> if o[this.name] if !o[this.name].push o[this.name] = [o[this.name]] o[this.name].push(this.value || "") else o[this.name] = this.value || "" #console.log o return o
[ { "context": "\"Jouer\"\n community: \"Communauté\"\n editor: \"Éditeur\"\n blog: \"Blog\"\n forum: \"Forum\"\n account:", "end": 1017, "score": 0.5553150177001953, "start": 1011, "tag": "NAME", "value": "diteur" }, { "context": "opos\"\n contact: \"Contact\"\n t...
app/locale/fr.coffee
maurovanetti/codecombat
1
module.exports = nativeDescription: "français", englishDescription: "French", translation: common: loading: "Chargement..." saving: "Sauvegarde..." sending: "Envoi..." send: "Envoyer" cancel: "Annuler" save: "Sauvegarder" publish: "Publier" create: "Creer" delay_1_sec: "1 seconde" delay_3_sec: "3 secondes" delay_5_sec: "5 secondes" manual: "Manuel" fork: "Fork" play: "Jouer" retry: "Reessayer" watch: "Regarder" unwatch: "Ne plus regarder" submit_patch: "Soumettre un correctif" units: second: "seconde" seconds: "secondes" minute: "minute" minutes: "minutes" hour: "heure" hours: "heures" day: "jour" days: "jours" week: "semaine" weeks: "semaines" month: "mois" months: "mois" year: "année" years: "années" modal: close: "Fermer" okay: "Ok" not_found: page_not_found: "Page non trouvée" nav: play: "Jouer" community: "Communauté" editor: "Éditeur" blog: "Blog" forum: "Forum" account: "Compte" admin: "Admin" home: "Accueil" contribute: "Contribuer" legal: "Mentions légales" about: "À propos" contact: "Contact" twitter_follow: "Suivre" employers: "Employeurs" versions: save_version_title: "Enregistrer une nouvelle version" new_major_version: "Nouvelle version majeure" cla_prefix: "Pour enregistrer vos modifications vous devez d'abord accepter notre" cla_url: "Copyright" cla_suffix: "." cla_agree: "J'accepte" login: sign_up: "Créer un compte" log_in: "Connexion" logging_in: "Connecter" log_out: "Déconnexion" recover: "Récupérer son compte" recover: recover_account_title: "Récupérer son compte" send_password: "Envoyer le mot de passe de récupération" signup: create_account_title: "Créer un compte pour sauvegarder votre progression" description: "C'est gratuit. Simplement quelques informations et vous pourrez commencer :" email_announcements: "Recevoir les annonces par email" coppa: "13+ ou hors É-U" coppa_why: "(Pourquoi?)" creating: "Création du compte en cours..." sign_up: "S'abonner" log_in: "se connecter avec votre mot de passe" social_signup: "Ou, vous pouvez vous identifier avec Facecook ou G+:" required: "Vous devez être connecté pour voir cela" home: slogan: "Apprenez à coder tout en jouant" no_ie: "CodeCombat ne fonctionnera pas sous Internet Explorer 9 ou moins. Désolé !" no_mobile: "CodeCombat n'a pas été créé pour les plateformes mobiles donc il est possible qu'il ne fonctionne pas correctement ! " play: "Jouer" old_browser: "Oh oh, votre navigateur est trop vieux pour executer CodeCombat. Désolé!" old_browser_suffix: "Vous pouvez essayer quand même, mais celà ne marchera probablement pas." campaign: "Campagne" for_beginners: "Pour débutants" multiplayer: "Multijoueurs" for_developers: "Pour développeurs" play: choose_your_level: "Choisissez votre niveau" adventurer_prefix: "Vous pouvez passer à n'importe quel niveau ci-dessous, ou discuter des niveaux sur " adventurer_forum: "le forum de l'Aventurier" adventurer_suffix: "." campaign_beginner: "Campagne du Débutant" campaign_beginner_description: "... dans laquelle vous apprendrez la magie de la programmation." campaign_dev: "Niveaux aléatoires plus difficiles" campaign_dev_description: "... dans lesquels vous apprendrez à utiliser l'interface en faisant quelque chose d'un petit peu plus dur." campaign_multiplayer: "Campagne multi-joueurs" campaign_multiplayer_description: "... dans laquelle vous coderez en face à face contre d'autres joueurs." campaign_player_created: "Niveaux créés par les joueurs" campaign_player_created_description: "... Dans laquelle vous serez confrontés à la créativité des votres.<a href=\"/contribute#artisan\">Artisan Wizards</a>." level_difficulty: "Difficulté: " play_as: "Jouer comme " spectate: "Spectateur" contact: contact_us: "Contacter CodeCombat" welcome: "Ravi d'avoir de vos nouvelles! Utilisez ce formulaire pour nous envoyer un mail." contribute_prefix: "Si vous voulez contribuer, consultez notre " contribute_page: "page de contributions" contribute_suffix: "!" forum_prefix: "Pour tout sujet d'ordre publique, merci d'utiliser " forum_page: "notre forum" forum_suffix: " À la place." send: "Envoyer un commentaire" contact_candidate: "Contacter le candidat" recruitment_reminder: "Utilisez ce formulaire pour entrer en contact avec le candidat qui vous interesse. Souvenez-vous que CodeCombat facture 15% de la première année de salaire. Ces frais sont dues à l'embauche de l'employé, ils sont remboursable pendant 90 jours si l'employé ne reste pas employé. Les employés à temps partiel, à distance ou contractuel sont gratuits en tant que stagiaires." diplomat_suggestion: title: "Aidez à traduire CodeCombat!" sub_heading: "Nous avons besoin de vos compétences en langues." pitch_body: "Nous développons CodeCombat en Anglais, mais nous avons déjà des joueurs de partout dans le monde. Beaucoup d'entre eux veulent jouer en Français mais ne parlent pas l'anglais, donc si vous parlez aussi bien l'anglais que le français, aidez-nous en devenant traducteur et aidez à traduire aussi bien le site que tous les niveaux en français." missing_translations: "Jusqu'à ce que nous ayons tout traduit en français, vous verrez de l'anglais quand le français ne sera pas disponible." learn_more: "Apprenez en plus sur les Traducteurs" subscribe_as_diplomat: "S'inscrire en tant que traducteur" wizard_settings: title: "Paramètres du Magicien" customize_avatar: "Personnaliser votre avatar" active: "Actif" color: "Couleur" group: "Groupe" clothes: "Vêtements" trim: "Tailleur" cloud: "Nuage" team: "Equipe" spell: "Sort" boots: "Bottes" hue: "Teinte" saturation: "Saturation" lightness: "Luminosité" account_settings: title: "Préférences du compte" not_logged_in: "Connectez-vous ou créez un compte pour modifier vos préférences." autosave: "Enregistrer automatiquement les modifications" me_tab: "Moi" picture_tab: "Photos" upload_picture: "Héberger une image" wizard_tab: "Magicien" password_tab: "Mot de passe" emails_tab: "Emails" admin: "Admin" wizard_color: "Couleur des vêtements du Magicien" new_password: "Nouveau mot de passe" new_password_verify: "Vérifier" email_subscriptions: "Abonnements" email_announcements: "Annonces" email_announcements_description: "Recevoir des mails sur les dernières actualités et sur le développement de CodeCombat." email_notifications: "Notifications" email_notifications_summary: "Commandes pour personaliser les notifications automatiques d'email liées à votre activité sur CodeCombat." email_any_notes: "Toutes Notifications" email_any_notes_description: "Désactivez pour ne plus recevoir de notifications par e-mail." email_recruit_notes: "Offres d'emploi" email_recruit_notes_description: "Si vous jouez vraiment bien, nous pouvons vous contacter pour vous proposer un (meilleur) emploi." contributor_emails: "Emails des contributeurs" contribute_prefix: "Nous recherchons des personnes pour se joindre à notre groupe! Consultez la " contribute_page: "page de contributions" contribute_suffix: " pour en savoir plus." email_toggle: "Tout basculer" error_saving: "Problème d'enregistrement" saved: "Changements sauvegardés" password_mismatch: "Le mot de passe ne correspond pas." job_profile: "Profil d'emploi" job_profile_approved: "Votre profil d'emploi a été approuvé par CodeCombat. Les employeurs seront en mesure de voir votre profil jusqu'à ce que vous le marquez inactif ou qu'il n'a pas été changé pendant quatre semaines." job_profile_explanation: "Salut! Remplissez-le et nous prendrons contact pour vous trouver un emploi de développeur de logiciels." sample_profile: "Voir un exemple de profil" view_profile: "Voir votre profil" account_profile: settings: "Paramètres" edit_profile: "Editer Profil" done_editing: "Modifications effectué" profile_for_prefix: "Profil pour " profile_for_suffix: "" featured: "Complet" not_featured: "Incomplet" looking_for: "à la recherche de:" last_updated: "Dernière Mise à jour:" contact: "Contact" active: "En recherche d'offres" inactive: "Ne recherche pas d'offres" complete: "terminé" next: "Suivant" next_city: "ville ?" next_country: "choisissez votre pays." next_name: "nom ?" next_short_description: "résumez votre profil en quelques mots." next_long_description: "décrivez le travail que vous cherchez." next_skills: "listez au moins 5 compétances." next_work: "décrivez votre expérience professionnelle." next_education: "raconter votre scolarité." next_projects: "décrivez jusqu'à 3 projets sur lesquels vous avez travaillé." next_links: "ajouter des liens internet vers des sites personnels ou des réseaux sociaux." next_photo: "ajouter une photo professionelle (optionnel)." next_active: "déclarez vous ouvert aux offres pour apparaitre dans les recherches." example_blog: "Votre blog" example_personal_site: "Site Web" links_header: "Liens personnels" links_blurb: "Lien vers d'autres sites ou profils que vous souhaitez mettre en avant, comme votre GitHub, LinkedIn ou votre blog." links_name: "Nom du lien" links_name_help: "A quoi êtes vous lié ?" links_link_blurb: "Lien URL" basics_header: "Mettre à jour les information basiques" basics_active: "Ouvert aux propositions" basics_active_help: "Voulez-vous des offres maintenant ?" basics_job_title: "Titre du poste souhaité" basics_job_title_help: "Quel est le rôle que vous cherchez ?" basics_city: "Ville" basics_city_help: "Ville dans laquelle vous souhaitez travailler (ou dans laquelle vous vivez actuellement)." basics_country: "Pays" basics_country_help: "Pays dans lequel vous souhaitez travailler (ou dans lequel vous vivez actuellement)." basics_visa: "Statut de travail aux Etats-Unis" basics_visa_help: "Etes vous autorisé à travailler aux Etats-Unis ou avez vous besoin d'un parrainage pour le visa ?" basics_looking_for: "Recherche" basics_looking_for_full_time: "Temps plein" basics_looking_for_part_time: "Temps partiel" basics_looking_for_remote: "A distance" basics_looking_for_contracting: "Contrat" basics_looking_for_internship: "Stage" basics_looking_for_help: "Quel genre de poste de développeur voulez-vous ?" name_header: "Remplissez votre nom" name_anonymous: "Developpeur Anonyme" name_help: "Le nom que vous souhaitez que l'employeur voie, par exemple 'Chuck Norris'." short_description_header: "Décrivez vous en quelques mots" short_description_blurb: "Ajoutez une phrase d'accroche pour permettre à un employeur d'en savoir plus sur vous." short_description: "Description courte" short_description_help: "Qui êtes vous et que recherchez vous ? 140 caractères max." skills_header: "Compétences" skills_help: "Notez vos compétence de développement par ordre de maitrise." long_description_header: "Détaillez votre poste souhaité" long_description_blurb: "Faites savoir aux employeurs combien vous êtes génial et quel poste vous voulez." long_description: "Biographie" long_description_help: "Décrivez-vous aux potentiels employeurs. Soyez bref et direct. Nous vous recommandons de bien indiquer quel poste vous intéresse le plus. 600 caractères max." work_experience: "Experience de travail" work_header: "Présentez votre parcours professionnel" work_years: "Années d'expérience" work_years_help: "Combien d'années d'expérience professionnelle (salarié) avez-vous dans le développement logiciel ?" work_blurb: "Lister vos missions les plus pertinentes, les plus récentes en premier." work_employer: "Employeur" work_employer_help: "Nom de votre employeur." work_role: "Titre du poste" work_role_help: "Quel était l'intitulé de votre mission ou votre poste ?" work_duration: "Durée" # work_duration_help: "When did you hold this gig?" work_description: "Description" work_description_help: "Qu'est-ce que vous y avez fait ? (140 carac.; optionel)" education: "Education" education_header: "Racontez vos exploits scolaires" education_blurb: "Lister vos exploits scolaires." education_school: "Etablissement" education_school_help: "Nom de l'établissement." education_degree: "Diplôme" education_degree_help: "Quel était votre diplôme et votre domaine d'étude ?" education_duration: "Dates" education_duration_help: "Quand ?" education_description: "Description" education_description_help: "Mettez en avant ce que vous voulez à propos de votre parcours scolaire. (140 carac.; optionel)" our_notes: "Notes" # remarks: "Remarks" projects: "Projets" projects_header: "Ajoutez 3 projets" projects_header_2: "Projets (Top 3)" projects_blurb: "Mettez en avant vos projets pour épater les employeurs." project_name: "Nom du projet" project_name_help: "Comment avez-vous appelé votre projet ?" project_description: "Description" project_description_help: "Décrivez brièvement le projet." project_picture: "Image" project_picture_help: "Chargez une image de 230x115px oou plus grande pour présenter votre projet." project_link: "Lien" project_link_help: "Lien vers le projet." # player_code: "Player Code" employers: # hire_developers_not_credentials: "Hire developers, not credentials." # get_started: "Get Started" # already_screened: "We've already technically screened all our candidates" # filter_further: ", but you can also filter further:" # filter_visa: "Visa" # filter_visa_yes: "US Authorized" # filter_visa_no: "Not Authorized" # filter_education_top: "Top School" # filter_education_other: "Other" # filter_role_web_developer: "Web Developer" # filter_role_software_developer: "Software Developer" # filter_role_mobile_developer: "Mobile Developer" # filter_experience: "Experience" # filter_experience_senior: "Senior" # filter_experience_junior: "Junior" # filter_experience_recent_grad: "Recent Grad" # filter_experience_student: "College Student" # filter_results: "results" # start_hiring: "Start hiring." # reasons: "Three reasons you should hire through us:" # everyone_looking: "Everyone here is looking for their next opportunity." # everyone_looking_blurb: "Forget about 20% LinkedIn InMail response rates. Everyone that we list on this site wants to find their next position and will respond to your request for an introduction." # weeding: "Sit back; we've done the weeding for you." # weeding_blurb: "Every player that we list has been screened for technical ability. We also perform phone screens for select candidates and make notes on their profiles to save you time." # pass_screen: "They will pass your technical screen." # pass_screen_blurb: "Review each candidate's code before reaching out. One employer found that 5x as many of our devs passed their technical screen than hiring from Hacker News." # make_hiring_easier: "Make my hiring easier, please." what: "Qu'est-ce que CodeCombat?" what_blurb: "CodeCombat est un jeu de programmation multijoueur par navigateur. Les Joueurs écrivent le code pour contrôler leurs troupes dans des batailles contre d'autres développeurs. Nous prenons en charge JavaScript, Python, Lua, Clojure, CoffeeScript, et Io." # cost: "How much do we charge?" # cost_blurb: "We charge 15% of first year's salary and offer a 100% money back guarantee for 90 days. We don't charge for candidates who are already actively being interviewed at your company." candidate_name: "Nom" candidate_location: "Localisation" candidate_looking_for: "Poste pour" candidate_role: "Rôle" candidate_top_skills: "Talents/Aptitudes" candidate_years_experience: "Années d'expérience" candidate_last_updated: "Dernière mise à jour" # candidate_who: "Who" # featured_developers: "Featured Developers" # other_developers: "Other Developers" # inactive_developers: "Inactive Developers" play_level: done: "Fait" grid: "Grille" customize_wizard: "Personnaliser le magicien" home: "Accueil" guide: "Guide" multiplayer: "Multijoueur" restart: "Relancer" goals: "Objectifs" success: "Succès" incomplete: "Imcoplet" timed_out: "Plus de temps" failing: "Echec" action_timeline: "Action sur la ligne de temps" click_to_select: "Clique sur une unité pour la sélectionner." reload_title: "Recharger tout le code?" reload_really: "Êtes-vous sûr de vouloir recharger ce niveau et retourner au début?" reload_confirm: "Tout recharger" victory_title_prefix: "" victory_title_suffix: " Terminé" victory_sign_up: "Inscrivez-vous pour recevoir les mises à jour" victory_sign_up_poke: "Vous voulez recevoir les dernières actualités par mail? Créez un compte gratuitement et nous vous tiendrons informés!" victory_rate_the_level: "Notez ce niveau: " # victory_return_to_ladder: "Return to Ladder" victory_play_next_level: "Jouer au prochain niveau" victory_go_home: "Retourner à l'accueil" victory_review: "Dites-nous en plus!" victory_hour_of_code_done: "Déjà fini ?" victory_hour_of_code_done_yes: "Oui, j'ai fini mon heure de code!" multiplayer_title: "Préférences multijoueurs" multiplayer_link_description: "Partage ce lien pour que tes amis viennent jouer avec toi." multiplayer_hint_label: "Astuce:" multiplayer_hint: " Cliquez sur le lien pour tout sélectionner, puis appuyer sur Pomme-C ou Ctrl-C pour copier le lien." multiplayer_coming_soon: "Plus de fonctionnalités multijoueurs sont à venir" # multiplayer_sign_in_leaderboard: "Sign in or create an account and get your solution on the leaderboard." guide_title: "Guide" tome_minion_spells: "Les sorts de vos soldats" tome_read_only_spells: "Sorts en lecture-seule" tome_other_units: "Autres unités" tome_cast_button_castable: "Jeter le sort" tome_cast_button_casting: "Sort en court" tome_cast_button_cast: "Sort jeté" tome_autocast_delay: "Temps de recharge" tome_select_spell: "Choisissez un sort" tome_select_a_thang: "Sélectionnez une unité pour" tome_available_spells: "Sorts diponibles" hud_continue: "Continuer (appuie sur shift ou espace)" spell_saved: "Sort enregistré" skip_tutorial: "Passer (esc)" editor_config: "Config de l'éditeur" editor_config_title: "Configuration de l'éditeur" editor_config_level_language_label: "Langage pour le niveau" # editor_config_level_language_description: "Define the programming language for this particular level." editor_config_default_language_label: "Langage de Programmation par défaut" editor_config_default_language_description: "Choississez le langage de programmation que vous souhaitez dons les nouveaux niveaux" editor_config_keybindings_label: "Raccourcis clavier" editor_config_keybindings_default: "Par défault (Ace)" editor_config_keybindings_description: "Ajouter de nouveaux raccourcis connus depuis l'éditeur commun." # editor_config_livecompletion_label: "Live Autocompletion" # editor_config_livecompletion_description: "Displays autocomplete suggestions while typing." editor_config_invisibles_label: "Afficher les caractères non-imprimables" editor_config_invisibles_description: "Permet d'afficher les caractères comme les espaces et les tabulations." editor_config_indentguides_label: "Montrer les indentations" editor_config_indentguides_description: "Affiche des guides verticaux qui permettent de visualiser l'indentation." editor_config_behaviors_label: "Auto-complétion" editor_config_behaviors_description: "Ferme automatiquement les accolades, parenthèses, et chaînes de caractères." keyboard_shortcuts: "Raccourcis Clavier" loading_ready: "Pret!" tip_insert_positions: "Maj+Clic un point pour insérer les coordonnées dans l'éditeur ." tip_toggle_play: "Jouer/Pause avec Ctrl+P." # tip_scrub_shortcut: "Ctrl+[ and Ctrl+] rewind and fast-forward." # tip_guide_exists: "Click the guide at the top of the page for useful info." tip_open_source: "CodeCombat est 100% open source!" tip_beta_launch: "La beta de CodeCombat a été lancée en Octobre 2013" tip_js_beginning: "JavaScript n'est que le commencement." # tip_autocast_setting: "Adjust autocast settings by clicking the gear on the cast button." think_solution: "Reflechissez a propos de la solution et non du problème." tip_theory_practice: "En théorie, il n'y a pas de différence entre la théorie et la pratique. Mais en pratique il y en a. - Yogi Berra" # tip_error_free: "There are two ways to write error-free programs; only the third one works. - Alan Perlis" tip_debugging_program: "Si débugger est l'art de corriger les bugs, alors programmer est l'art d'en créer. . - Edsger W. Dijkstra" # tip_forums: "Head over to the forums and tell us what you think!" tip_baby_coders: "Dans le futur, même les bébés seront des archimages." # tip_morale_improves: "Loading will continue until morale improves." # tip_all_species: "We believe in equal opportunities to learn programming for all species." # tip_reticulating: "Reticulating spines." # tip_harry: "Yer a Wizard, " # tip_great_responsibility: "With great coding skill comes great debug responsibility." # tip_munchkin: "If you don't eat your vegetables, a munchkin will come after you while you're asleep." # tip_binary: "There are only 10 types of people in the world: those who understand binary, and those who don't." # tip_commitment_yoda: "A programmer must have the deepest commitment, the most serious mind. ~ Yoda" # tip_no_try: "Do. Or do not. There is no try. - Yoda" # tip_patience: "Patience you must have, young Padawan. - Yoda" # tip_documented_bug: "A documented bug is not a bug; it is a feature." # tip_impossible: "It always seems impossible until it's done. - Nelson Mandela" # tip_talk_is_cheap: "Talk is cheap. Show me the code. - Linus Torvalds" # tip_first_language: "The most disastrous thing that you can ever learn is your first programming language. - Alan Kay" # tip_hardware_problem: "Q: How many programmers does it take to change a light bulb? A: None, it's a hardware problem." time_current: "Maintenant:" time_total: "Max:" time_goto: "Allez a:" infinite_loop_try_again: "Reessayer" infinite_loop_reset_level: "Redemarrer le niveau" infinite_loop_comment_out: "Supprimez les commentaire de mon code" keyboard_shortcuts: keyboard_shortcuts: "Raccourcis Clavier" space: "Espace" enter: "Entrer" escape: "Echap" # cast_spell: "Cast current spell." # continue_script: "Continue past current script." # skip_scripts: "Skip past all skippable scripts." # toggle_playback: "Toggle play/pause." # scrub_playback: "Scrub back and forward through time." # single_scrub_playback: "Scrub back and forward through time by a single frame." # scrub_execution: "Scrub through current spell execution." # toggle_debug: "Toggle debug display." # toggle_grid: "Toggle grid overlay." # toggle_pathfinding: "Toggle pathfinding overlay." # beautify: "Beautify your code by standardizing its formatting." # move_wizard: "Move your Wizard around the level." admin: av_title: "Vues d'administrateurs" av_entities_sub_title: "Entités" av_entities_users_url: "Utilisateurs" av_entities_active_instances_url: "Instances actives" av_entities_employer_list_url: "Liste des employés" av_other_sub_title: "Autre" av_other_debug_base_url: "Base (pour debugger base.jade)" u_title: "Liste des utilisateurs" lg_title: "Dernières parties" clas: "CLAs" community: level_editor: "Editeur de niveau" main_title: "Communauté CodeCombat" facebook: "Facebook" twitter: "Twitter" gplus: "Google+" editor: main_title: "Éditeurs CodeCombat" main_description: "Créé tes propres niveaux, campagnes, unités et contenus éducatifs. Nous vous fournissons tous les outils dont vous avez besoin!" article_title: "Éditeur d'article" article_description: "Écris des articles qui donnent aux joueurs un aperçu des concepts de programmation qui peuvent être utilisés dans différents niveaux et campagnes." thang_title: "Éditeur Thang" thang_description: "Créé des unités, définis leur comportement de base, graphisme et son. Pour l'instant cette fonctionnalité ne supporte que l'importation d'images vectorielles exportées depuis Flash." level_title: "Éditeur de niveau" level_description: "Inclut les outils de script, l'upload de vidéos, et l'élaboration de logiques personnalisées pour créer toutes sortes de niveaux. Tout ce que nous utilisons nous-mêmes!" # achievement_title: "Achievement Editor" # got_questions: "Questions about using the CodeCombat editors?" contact_us: "contactez nous!" hipchat_prefix: "Vous pouvez aussi nous trouver dans notre " hipchat_url: "conversation HipChat." back: "Retour" revert: "Annuler" revert_models: "Annuler les modèles" # pick_a_terrain: "Pick A Terrain" # small: "Small" # grassy: "Grassy" fork_title: "Fork une nouvelle version" fork_creating: "Créer un Fork..." # randomize: "Randomize" more: "Plus" wiki: "Wiki" live_chat: "Chat en live" level_some_options: "Quelques options?" level_tab_thangs: "Thangs" level_tab_scripts: "Scripts" level_tab_settings: "Paramètres" level_tab_components: "Composants" level_tab_systems: "Systèmes" level_tab_thangs_title: "Thangs actuels" level_tab_thangs_all: "Tout" level_tab_thangs_conditions: "Conditions de départ" level_tab_thangs_add: "ajouter des Thangs" delete: "Supprimer" duplicate: "Dupliquer" level_settings_title: "Paramètres" level_component_tab_title: "Composants actuels" level_component_btn_new: "Créer un nouveau composant" level_systems_tab_title: "Systèmes actuels" level_systems_btn_new: "Créer un nouveau système" level_systems_btn_add: "Ajouter un système" level_components_title: "Retourner à tous les Thangs" level_components_type: "Type" level_component_edit_title: "Éditer le composant" level_component_config_schema: "Configurer le schéma" level_component_settings: "Options" level_system_edit_title: "Éditer le système" create_system_title: "Créer un nouveau système" new_component_title: "Créer un nouveau composant" new_component_field_system: "Système" new_article_title: "Créer un nouvel article" new_thang_title: "Créer un nouveau Type Thang" new_level_title: "Créer un nouveau niveau" new_article_title_login: "Connectez vous pour créer un nouvel article" # new_thang_title_login: "Log In to Create a New Thang Type" new_level_title_login: "Connectez vous pour créer un nouveau niveau" # new_achievement_title: "Create a New Achievement" # new_achievement_title_login: "Log In to Create a New Achievement" article_search_title: "Rechercher dans les articles" thang_search_title: "Rechercher dans les types Thang" level_search_title: "Rechercher dans les niveaux" # achievement_search_title: "Search Achievements" read_only_warning2: "Note: vous ne pouvez sauvegarder aucune édition, car vous n'êtes pas identifié." article: edit_btn_preview: "Prévisualiser" edit_article_title: "Éditer l'article" general: and: "et" name: "Nom" body: "Corps" version: "Version" commit_msg: "Message de mise à jour" version_history: "Historique des versions" version_history_for: "Historique des versions pour : " result: "Resultat" results: "Résultats" description: "Description" or: "ou" subject: "Sujet" email: "Email" password: "Mot de passe" message: "Message" code: "Code" ladder: "Companion" when: "Quand" opponent: "Adversaire" rank: "Rang" score: "Score" win: "Victoire" loss: "Défaite" tie: "Ex-aequo" easy: "Facile" medium: "Moyen" hard: "Difficile" player: "Joueur" about: who_is_codecombat: "Qui est CodeCombat?" why_codecombat: "Pourquoi CodeCombat?" who_description_prefix: "ont lancé CodeCombat ensemble en 2013. Nous avons aussi créé " who_description_suffix: "en 2008, l'améliorant jusqu'au rang de première application web et iOS pour apprendre à écrire les caractères chinois et japonais." who_description_ending: "Maintenant nous apprenons aux gens à coder." why_paragraph_1: "En développant Skritter, George ne savait pas programmer et était frustré de ne pas pouvoir implémenter ses idées. Ensuite, il essaya d'apprendre, mais les cours n'étaient pas assez rapides. Son colocataire, voulant se requalifier et arrêter d'apprendre, essaya Codecademy, mais \"s'ennuya.\" Chaque semaine un nouvel ami commençait Codecademy, puis abandonnait. Nous nous sommes rendus compte que nous avions résolu le même problème avec Skritter: les gens apprennant grâce à des cours lents et intensifs quand nous avons besoin d'expérience rapide et intensive. Nous savons comment remédier à ça." why_paragraph_2: "Besoin d'apprendre à développer? Vous n'avez pas besoin de cours. Vous avez besoin d'écrire beaucoup de code et de vous amuser en le faisant." why_paragraph_3_prefix: "C'est ce dont il s'agit en programmation. Ça doit être amusant. Pas amusant comme" why_paragraph_3_italic: "Génial un badge" why_paragraph_3_center: "Mais amusant comme" why_paragraph_3_italic_caps: "NAN MAMAN JE DOIS FINIR MON NIVEAU!" why_paragraph_3_suffix: "C'est pourquoi CodeCombat est un jeu multijoueur, pas un cours avec une leçon jouée. Nous n'arrêterons pas avant que vous ne puissiez plus arrêter — mais cette fois, c'est une bonne chose." why_paragraph_4: "Si vous devez devenir accro à un jeu, accrochez-vous à celui-ci et devenez un des mages de l'âge de la technologie." why_ending: "Et oh, c'est gratuit. " why_ending_url: "Commence ton apprentissage maintenant!" george_description: "PDG, homme d'affaire, web designer, game designer, et champion des programmeurs débutants." scott_description: "Programmeur extraordinaire, architecte logiciel, assistant cuisinier, et maitre de la finance. Scott est le raisonnable." nick_description: "Assistant programmeur, mage à la motivation excentrique, et bidouilleur de l'extrême. Nick peut faire n'importe quoi mais il a choisi CodeCombat." jeremy_description: "Mage de l'assistance client, testeur de maniabilité, et community manager; vous avez probablement déjà parlé avec Jeremy." michael_description: "Programmeur, administrateur réseau, et l'enfant prodige du premier cycle, Michael est la personne qui maintient nos serveurs en ligne." glen_description: "Programmeur et développeur de jeux passioné, avec la motivation pour faire de ce monde un meilleur endroit, en développant des choses qui comptent. Le mot impossible est introuvable dans son dictionnaire. Apprendre de nouveaux talents est sa joie !" legal: page_title: "Légal" opensource_intro: "CodeCombat est complètement gratuit et open source." opensource_description_prefix: "Regardez " github_url: "notre GitHub" opensource_description_center: "et aidez nous si vous voulez! CodeCombat est construit sur plusieurs projets open source, et nous les aimons. Regardez " archmage_wiki_url: "notre wiki des Archimages" opensource_description_suffix: "pour trouver la liste des logiciels qui rendent ce jeu possible." practices_title: "Bonnes pratiques" practices_description: "Ce sont les promesses que nous vous faisons à vous, le joueur, en jargon un peu juridique." privacy_title: "Vie privée" privacy_description: "Nous ne vendrons aucune de vos informations personnelles. Nous comptons faire de l'argent éventuellement avec le recrutement, mais soyez assuré que nous ne fournirons aucune de vos informations personnelles à des compagnies intéressées sans votre consentement explicite." security_title: "Sécurité" security_description: "Nous faisons tout notre possible pour conserver la confidentialité de vos informations personnelles. En tant que projet open source, notre site est ouvert à tous ceux qui souhaitent examiner et améliorer nos systèmes de sécurité." email_title: "Email" email_description_prefix: "Nous ne vous innonderons pas d'email. Grâce à" email_settings_url: "vos paramètres d'email " email_description_suffix: "ou avec des liens disponibles dans nos emails, vous pouvez changer vos préférences ou vous désinscrire à tout moment." cost_title: "Coût" cost_description: "Pour l'instant, CodeCombat est gratuit à 100%! Un de nos principaux objectifs est que ça le reste, pour qu'autant de gens possible puissent y jouer, indépendamment de leur niveau de vie. Si le ciel s'assombrit, nous devrons peut-être rendre les inscriptions payantes ou une partie du contenu, mais nous ne le souhaitons pas. Avec un peu de chance, nous serons capables de soutenir l'entreprise avec :" recruitment_title: "Recrutement" recruitment_description_prefix: "Ici chez CodeCombat, vous allez devenir un magicien puissant, pas seulement dans le jeu, mais aussi dans la vie réelle." url_hire_programmers: "Personne ne peut recruter des développeurs aussi vite" recruitment_description_suffix: "donc une fois que vous aurez aiguisé votre savoir-faire et si vous l'acceptez, nous montrerons vos meilleurs bouts de code aux milliers d'employeurs qui attendent une chance de vous recruter. Ils nous payent un peu pour ensuite vous payer" recruitment_description_italic: "beaucoup" recruitment_description_ending: "le site reste gratuit et tout le monde est content. C'est le but." copyrights_title: "Copyrights et Licences" contributor_title: "Contributor License Agreement" contributor_description_prefix: "Toute contribution, sur le site et sur le répertoire GitHub, est sujette à nos" cla_url: "CLA" contributor_description_suffix: "auxquelles vous devez vous soumettre avant de contribuer." code_title: "Code - MIT" code_description_prefix: "Tout code siglé CodeCombat ou hébergé sur codecombat.com, sur le répertoire GitHub ou dans la base de données de codecombat.com, est sous la licence" mit_license_url: "MIT" code_description_suffix: "Cela inclut le code dans Systèmes et Composants qui est rendu disponible par CodeCombat dans le but de créer des niveaux." art_title: "Art/Musique - Creative Commons " art_description_prefix: "Tout le contenu commun est sous licence" cc_license_url: "Creative Commons Attribution 4.0 International" art_description_suffix: "Le contenu commun est tout ce qui est rendu disponible par CodeCombat afin de créer des niveaux. Cela inclut :" art_music: "La musique" art_sound: "Le son" art_artwork: "Les artworks" art_sprites: "Les sprites" art_other: "Tout le reste du contenu non-code qui est rendu accessible lors de la création de niveaux." art_access: "Pour l'instant il n'y a aucun système universel et facile pour rassembler ces ressources. En général, accédez y par les URL comme le fait le site, contactez-nous pour de l'aide, ou aidez-nous à agrandir le site pour rendre ces ressources plus facilement accessibles." art_paragraph_1: "Pour l'attribution, s'il vous plait, nommez et référencez codecombat.com près de la source utilisée ou dans un endroit approprié. Par exemple:" use_list_1: "Si utilisé dans un film ou un autre jeu, incluez codecombat.com dans le générique." use_list_2: "Si utilisé sur un site web, incluez un lien près de l'utilisation, par exemple sous une image, ou sur une page d'attribution générale où vous pourrez aussi mentionner les autres travaux en Creative Commons et les logiciels open source utilisés sur votre site. Quelque chose qui fait clairement référence à CodeCombat, comme un article de blog mentionnant CodeCombat, n'a pas besoin d'attribution séparée." art_paragraph_2: "Si le contenu utilisé n'est pas créé par CodeCombat mais par un autre utilisateur de codecombat.com, attribuez le à cet utilisateur, et suivez les recommandations fournies dans la ressource de la description s'il y en a." rights_title: "Droits réservés" rights_desc: "Tous les droits sont réservés pour les niveaux eux-mêmes. Cela inclut" rights_scripts: "Les scripts" rights_unit: "La configuration unitaire" rights_description: "La description" rights_writings: "L'écriture" rights_media: "Les médias (sons, musiques) et tous les autres contenus créatifs créés spécialement pour ce niveau et non rendus généralement accessibles en créant des niveaux." rights_clarification: "Pour clarifier, tout ce qui est rendu accessible dans l'éditeur de niveaux dans le but de créer des niveaux est sous licence CC, tandis que le contenu créé avec l'éditeur de niveaux ou uploadé dans le but de créer un niveau ne l'est pas." nutshell_title: "En un mot" nutshell_description: "Chaque ressource que nous fournissons dans l'éditeur de niveau est libre d'utilisation pour créer des niveaux. Mais nous nous réservons le droit de restreindre la distribution des niveaux créés (qui sont créés sur codecombat.com) ils peuvent donc devenir payants dans le futur, si c'est ce qui doit arriver." canonical: "La version de ce document est la version définitive et canonique. En cas d'irrégularité dans les traductions, le document anglais fait foi." contribute: page_title: "Contribution" character_classes_title: "Classes du personnage" introduction_desc_intro: "Nous avons beaucoup d'espoir pour CodeCombat." introduction_desc_pref: "Nous voulons être l'endroit où les développeurs de tous horizons viennent pour apprendre et jouer ensemble, présenter les autres au monde du développement, et refléter le meilleur de la communauté. Nous ne pouvons et ne voulons pas faire ça seuls ; ce qui rend super les projets comme GitHub, Stack Overflow et Linux, est que les gens qui l'utilisent le construisent. Dans ce but, " introduction_desc_github_url: "CodeCombat est totalement open source" introduction_desc_suf: ", et nous avons pour objectif de fournir autant de manières possibles pour que vous participiez et fassiez de ce projet autant le votre que le notre." introduction_desc_ending: "Nous espérons que vous allez joindre notre aventure!" introduction_desc_signature: "- Nick, George, Scott, Michael, Jeremy et Glen" alert_account_message_intro: "Et tiens!" alert_account_message: "Pour souscrire aux e-mails, vous devez être connecté" # archmage_summary: "Interested in working on game graphics, user interface design, database and server organization, multiplayer networking, physics, sound, or game engine performance? Want to help build a game to help other people learn what you are good at? We have a lot to do and if you are an experienced programmer and want to develop for CodeCombat, this class is for you. We would love your help building the best programming game ever." archmage_introduction: "L'une des meilleures parties de la création d'un jeu est qu'il regroupe tant de choses différentes. Graphismes, sons, réseau en temps réel, réseaux sociaux, et bien sur bien d'autres aspects de la programmation, de la gestion bas niveau de base de données, et de l'administration de serveur à l'élaboration d'interfaces utilisateur. Il y a tant à faire, et si vous êtes un programmeur expérimenté avec une aspiration à vraiment plonger dans le fond de CodeCombat, cette classe est faite pour vous. Nous aimerions avoir votre aide pour le meilleur jeu de développement de tous les temps." class_attributes: "Attributs de classe" archmage_attribute_1_pref: "Connaissance en " archmage_attribute_1_suf: ", ou le désir d'apprendre. La plupart de notre code est écrit avec ce langage. Si vous êtes fan de Ruby ou Python, vous vous sentirez chez vous. C'est du JavaScript, mais avec une syntaxe plus sympatique." archmage_attribute_2: "De l'expérience en développement et en initiatives personnelles. Nous vous aiderons à vous orienter, mais nous ne pouvons pas passer plus de temps à vous entrainer." how_to_join: "Comment nous rejoindre" join_desc_1: "N'importe qui peut aider! Vous avez seulement besoin de regarder " join_desc_2: "pour commencer, et cocher la case ci-dessous pour vous marquer comme un archimage courageux et obtenir les dernières nouvelles par email. Envie de discuter de ce qu'il y a à faire ou de comment être plus impliqué? " join_desc_3: ", ou trouvez-nous dans nos " join_desc_4: "et nous partirons de là!" join_url_email: "Contactez nous" join_url_hipchat: "conversation publique HipChat" more_about_archmage: "En apprendre plus sur devenir un puissant archimage" archmage_subscribe_desc: "Recevoir un email sur les nouvelles possibilités de développement et des annonces." # artisan_summary_pref: "Want to design levels and expand CodeCombat's arsenal? People are playing through our content at a pace faster than we can build! Right now, our level editor is barebone, so be wary. Making levels will be a little challenging and buggy. If you have visions of campaigns spanning for-loops to" artisan_summary_suf: ", alors ce travail est pour vous" artisan_introduction_pref: "Nous devons créer des niveaux additionnels! Les gens veulent plus de contenu, et nous ne pouvons pas tous les créer nous-mêmes. Maintenant votre station de travail est au niveau un ; notre éditeur de niveaux est à peine utilisable même par ses créateurs, donc méfiez-vous. Si vous avez des idées sur la boucle for de" artisan_introduction_suf: ", cette classe est faite pour vous." artisan_attribute_1: "Une expérience dans la création de contenu comme celui-ci serait un plus, comme utiliser l'éditeur de niveaux de Blizzard. Mais ce n'est pas nécessaire!" artisan_attribute_2: "Vous aspirez à faire beaucoup de tests et d'itérations. Pour faire de bons niveaux, vous aurez besoin de les proposer aux autres et les regarder les jouer, et être prêt à trouver un grand nombre de choses à corriger." artisan_attribute_3: "Pour l'heure, endurance en binôme avec un Aventurier. Notre éditeur de niveaux est vraiment préliminaire et frustrant à l'utilisation. Vous êtes prévenus!" artisan_join_desc: "Utilisez le créateur de niveaux pour à peu près ces étapes :" artisan_join_step1: "Lire la documentation." artisan_join_step2: "Créé un nouveau niveau et explore les niveaux existants." artisan_join_step3: "Retrouvez nous dans notre conversation HipChat pour obtenir de l'aide." artisan_join_step4: "Postez vos niveaux dans le forum pour avoir des retours." more_about_artisan: "En apprendre plus sur comment devenir un Artisan créatif" artisan_subscribe_desc: "Recevoir un email sur les annonces et mises à jour de l'éditeur de niveaux." # adventurer_summary: "Let us be clear about your role: you are the tank. You are going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class is for you." adventurer_introduction: "Soyons clair à propos de votre rôle : vous êtes le tank. Vous allez subir beaucoup de dommages. Nous avons besoin de gens pour essayer les nouveaux niveaux et aider à identifier comment améliorer les choses. La douleur sera énorme; faire de bons jeux est une longue tâche et personne n'y arrive du premier coup. Si vous pouvez résister et avez un gros score de constitution, alors cette classe est faite pour vous." adventurer_attribute_1: "Une soif d'apprendre. Vous voulez apprendre à développer et nous voulons vous apprendre. Vous allez toutefois faire la plupart de l'apprentissage." adventurer_attribute_2: "Charismatique. Soyez doux mais exprimez-vous sur ce qui a besoin d'être amélioré, et faites des propositions sur comment l'améliorer." adventurer_join_pref: "Soit faire équipe avec (ou recruter!) un artisan et travailler avec lui, ou cocher la case ci-dessous pour recevoir un email quand il y aura de nouveaux niveaux à tester. Nous parlons aussi des niveaux à réviser sur notre réseau" adventurer_forum_url: "notre forum" adventurer_join_suf: "si vous préférez être avertis ainsi, inscrivez-vous ici!" more_about_adventurer: "En apprendre plus sur devenir un brave Aventurier" adventurer_subscribe_desc: "Recevoir un email lorsqu'il y a de nouveaux niveaux à tester." # scribe_summary_pref: "CodeCombat is not just going to be a bunch of levels. It will also be a resource of programming knowledge that players can hook into. That way, each Artisan can link to a detailed article that for the player's edification: documentation akin to what the " # scribe_summary_suf: " has built. If you enjoy explaining programming concepts, then this class is for you." scribe_introduction_pref: "CodeCombat n'est pas seulement un ensemble de niveaux. Il contiendra aussi des ressources pour la connaissance, un wiki des concepts de programmation que les niveaux pourront illustrer. Dans ce but, chaque Artisan pourra, au lieu d'avoir à décrire en détail ce qu'est un opérateur de comparaison, seulement lier son niveau à l'article qui le décrit et qui a été écrit pour aider les joueurs. Quelque chose dans le sens de ce que le " scribe_introduction_url_mozilla: "Mozilla Developer Network" scribe_introduction_suf: " a développé. Si votre définition de l'amusement passe par le format Markdown, alors cette classe est pour vous." scribe_attribute_1: "Les compétences rédactionnelles sont quasiment la seule chose dont vous aurez besoin. Pas seulement la grammaire et l'orthographe, mais être également capable de lier des idées ensembles." contact_us_url: "Contactez-nous" scribe_join_description: "parlez nous un peu de vous, de votre expérience en programmation et de quels sujets vous souhaitez traiter. Nous partirons de là!" more_about_scribe: "En apprendre plus sur comment devenir un Scribe assidu" scribe_subscribe_desc: "Recevoir un email sur les annonces d'écriture d'article." # diplomat_summary: "There is a large interest in CodeCombat in other countries that do not speak English! We are looking for translators who are willing to spend their time translating the site's corpus of words so that CodeCombat is accessible across the world as soon as possible. If you'd like to help getting CodeCombat international, then this class is for you." diplomat_introduction_pref: "Si nous avons appris quelque chose du " diplomat_launch_url: "lancement en octobre" diplomat_introduction_suf: "c'est qu'il y a un intérêt considérable pour CodeCombat dans d'autres pays, particulièrement au Brésil! Nous créons une équipe de traducteurs pour changer une liste de mots en une autre pour que CodeCombat soit le plus accessible possible à travers le monde. Si vous souhaitez avoir un aperçu des prochains contenus et avoir les niveaux dans votre langue le plus tôt possible, alors cette classe est faite pour vous." diplomat_attribute_1: "Des facilités en anglais et dans la langue que vous souhaitez traduire. Pour transmettre des idées complexes, il est important d'avoir une solide compréhension des deux!" diplomat_join_pref_github: "Trouvez le fichier de langue souhaité" diplomat_github_url: "sur GitHub" # diplomat_join_suf_github: ", edit it online, and submit a pull request. Also, check this box below to keep up-to-date on new internationalization developments!" more_about_diplomat: "En apprendre plus sur comment devenir un bon diplomate" diplomat_subscribe_desc: "Recevoir un email sur le développement i18n et les niveaux à traduire." # ambassador_summary: "We are trying to build a community, and every community needs a support team when there are troubles. We have got chats, emails, and social networks so that our users can get acquainted with the game. If you want to help people get involved, have fun, and learn some programming, then this class is for you." ambassador_introduction: "C'est la communauté que nous construisons, et vous en êtes les connexions. Nous avons des discussions via le chat Olark, emails et les réseaux sociaux avec plusieurs personnes, et l'aide vient à la fois du jeu lui-même et grâce à lui. Si vous voulez aider les gens, prendre part à l'aventure et vous amuser, avec un bon feeling de CodeCombat et ce vers quoi nous allons, alors cette classe est faite pour vous." ambassador_attribute_1: "Compétences en communication. Être capable d'identifier les problèmes que les joueurs ont et les aider à les résoudre. Mais aussi nous tenir informés de ce que les joueurs disent, ce qu'ils aiment et n'aiment pas et d'autres choses de ce genre!" ambassador_join_desc: "parlez-nous un peu de vous, de ce que vous avez fait et ce qui vous aimeriez faire. Nous partirons de ça!" ambassador_join_note_strong: "Note" ambassador_join_note_desc: "Une de nos priorités est de développer un jeu multijoueur où les joueurs qui ont du mal à réussir un niveau peuvent demander de l'aide à un joueur de plus haut niveau. Ce sera un bon moyen pour que les ambassadeurs fassent leur travail. Nous vous garderons en ligne!" more_about_ambassador: "En apprendre plus sur comment devenir un serviable Ambassadeur" ambassador_subscribe_desc: "Recevoir un email sur les mises à jour de l'aide et les développements multijoueur." # counselor_summary: "None of the above roles fit what you are interested in? Do not worry, we are on the lookout for anybody who wants a hand in the development of CodeCombat! If you are interested in teaching, game development, open source management, or anything else that you think will be relevant to us, then this class is for you." counselor_introduction_1: "Avez-vous de l'expérience dans la vie? Ou toute autre expérience qui peut nous aider à décider comment diriger CodeCombat? De tous ces rôles, ce sera probablement celui qui prend le moins de temps, mais vous ferez la différence. Nous recherchons des sages, particulièrement dans les domaines de : l'apprentissage, le développement de jeux, la gestion de projets open source, le recrutement technique, l'entreprenariat, ou la conception." counselor_introduction_2: "Ou vraiment toutes choses en rapport avec le développement de CodeCombat. Si vous avez des connaissances et que vous voulez les partager pour aider le projet à avancer, alors cette classe est faite pour vous." counselor_attribute_1: "De l'expérience, dans un des domaines ci-dessus ou quelque chose que vous pensez être utile." counselor_attribute_2: "Un peu de temps libre!" counselor_join_desc: "parlez-nous un peu de vous, de ce que vous avez fait et ce que vous aimeriez faire. Nous vous mettrons dans notre liste de contacts et ferons appel à vous quand nous aurons besoin de conseils (pas trop souvent)." more_about_counselor: "En apprendre plus sur devenir un précieux Conseiller" changes_auto_save: "Les changements sont sauvegardés automatiquement quand vous changez l'état des cases à cocher." diligent_scribes: "Nos Scribes assidus :" powerful_archmages: "Nos puissants Archimages :" creative_artisans: "Nos Artisans créatifs :" brave_adventurers: "Nos braves Aventuriers :" translating_diplomats: "Nos Diplomates traducteurs :" helpful_ambassadors: "Nos serviables Ambassadeurs :" classes: archmage_title: "Archimage" archmage_title_description: "(Développeur)" artisan_title: "Artisan" artisan_title_description: "(Créateur de niveau)" adventurer_title: "Aventurier" adventurer_title_description: "(Testeur de niveau)" scribe_title: "Scribe" scribe_title_description: "(Rédacteur d'articles)" diplomat_title: "Diplomate" diplomat_title_description: "(Traducteur)" ambassador_title: "Ambassadeur" ambassador_title_description: "(Aide)" counselor_title: "Conseiller" counselor_title_description: "(Expert/Professeur)" ladder: please_login: "Identifie toi avant de jouer à un ladder game." my_matches: "Mes Matchs" simulate: "Simuler" simulation_explanation: "En simulant une partie, tu peux classer ton rang plus rapidement!" simulate_games: "Simuler une Partie!" simulate_all: "REINITIALISER ET SIMULER DES PARTIES" games_simulated_by: "Parties que vous avez simulé :" games_simulated_for: "parties simulées pour vous :" games_simulated: "Partie simulée" games_played: "Parties jouées" ratio: "Moyenne" leaderboard: "Classement" battle_as: "Combattre comme " summary_your: "Vos " summary_matches: "Matchs - " summary_wins: " Victoires, " summary_losses: " Défaites" rank_no_code: "Nouveau Code à Classer" rank_my_game: "Classer ma Partie!" rank_submitting: "Soumission en cours..." rank_submitted: "Soumis pour le Classement" rank_failed: "Erreur lors du Classement" rank_being_ranked: "Partie en cours de Classement" rank_last_submitted: "Envoyé " help_simulate: "De l'aide pour simuler vos parties" code_being_simulated: "Votre nouveau code est en cours de simulation par les autres joueurs pour le classement. Cela va se rafraichir lors que d'autres matchs auront lieu." no_ranked_matches_pre: "Pas de match classé pour l'équipe " no_ranked_matches_post: "! Affronte d'autres compétiteurs et reviens ici pour classer ta partie." choose_opponent: "Choisir un Adversaire" # select_your_language: "Select your language!" tutorial_play: "Jouer au Tutoriel" tutorial_recommended: "Recommendé si tu n'as jamais joué avant" tutorial_skip: "Passer le Tutoriel" tutorial_not_sure: "Pas sûr de ce qu'il se passe?" tutorial_play_first: "Jouer au Tutoriel d'abord." simple_ai: "IA simple" warmup: "Préchauffe" vs: "VS" # friends_playing: "Friends Playing" log_in_for_friends: "Connectez vous pour jouer avec vos amis!" social_connect_blurb: "Connectez vous pour jouer contre vos amis!" # invite_friends_to_battle: "Invite your friends to join you in battle!" fight: "Combattez !" watch_victory: "Regardez votre victoire" # defeat_the: "Defeat the" tournament_ends: "Fin du tournoi" # tournament_ended: "Tournament ended" tournament_rules: "Règles du tournoi" # tournament_blurb: "Write code, collect gold, build armies, crush foes, win prizes, and upgrade your career in our $40,000 Greed tournament! Check out the details" tournament_blurb_blog: "Sur notre blog" # rules: "Rules" # winners: "Winners" ladder_prizes: title: "Prix du tournoi" # blurb_1: "These prizes will be awarded according to" blurb_2: "Régles du tournoi" # blurb_3: "to the top human and ogre players." # blurb_4: "Two teams means double the prizes!" # blurb_5: "(There will be two first place winners, two second-place winners, etc.)" rank: "Rang" prizes: "Prix" total_value: "Valeur totale" # in_cash: "in cash" # custom_wizard: "Custom CodeCombat Wizard" # custom_avatar: "Custom CodeCombat avatar" # heap: "for six months of \"Startup\" access" credits: "Crédits" # one_month_coupon: "coupon: choose either Rails or HTML" # one_month_discount: "discount, 30% off: choose either Rails or HTML" license: "Licence" # oreilly: "ebook of your choice" multiplayer_launch: # introducing_dungeon_arena: "Introducing Dungeon Arena" # new_way: "The new way to compete with code." # to_battle: "To Battle, Developers!" # modern_day_sorcerer: "You know how to code? That's badass. You're a modern-day sorcerer! Isn't about time that you used your magic coding powers to command your minions in epic combat? And we're not talking robots here." # arenas_are_here: "CodeCombat head-to-head multiplayer arenas are here." # ladder_explanation: "Choose your heroes, enchant your human or ogre armies, and climb your way over defeated fellow Wizards to reach the top of the ladders–then challenge your friends in our glorious, asynchronous multiplayer coding arenas. If you're feeling creative, you can even" # fork_our_arenas: "fork our arenas" create_worlds: "et créez votre monde" javascript_rusty: "JavaScript un peu rouillé? Pas de souci; il y a un" tutorial: "Tutoriel" new_to_programming: ". Débutant en programmation? Essaie la campagne débutant pour progresser." so_ready: "Je Suis Prêt Pour Ca" loading_error: could_not_load: "Erreur de chargement du serveur" connection_failure: "La connexion a échouée." unauthorized: "Vous devez être identifiée pour faire cela. Avez-vous désactivé les cookies ?" forbidden: "Vous n'avez pas la permission." not_found: "Introuvable." not_allowed: "Méthode non autorisée." timeout: "Connexion au serveur écoulée." conflict: "Conflit de Ressources." bad_input: "Données incorrectes ." server_error: "Erreur serveur." unknown: "Erreur inconnue." resources: your_sessions: "vos Sessions" level: "Niveau" # social_network_apis: "Social Network APIs" facebook_status: "Statut Facebook" facebook_friends: "Amis Facebook" # facebook_friend_sessions: "Facebook Friend Sessions" # gplus_friends: "G+ Friends" # gplus_friend_sessions: "G+ Friend Sessions" leaderboard: "Classement" # user_schema: "User Schema" # user_profile: "User Profile" patches: "Patchs" # patched_model: "Source Document" # model: "Model" system: "Système" # component: "Component" # components: "Components" # thang: "Thang" # thangs: "Thangs" # level_session: "Your Session" # opponent_session: "Opponent Session" article: "Article" user_names: "Nom d'utilisateur" # thang_names: "Thang Names" files: "Fichiers" top_simulators: "Top Simulateurs" source_document: "Document Source" document: "Document" # sprite_sheet: "Sprite Sheet" # candidate_sessions: "Candidate Sessions" # user_remark: "User Remark" # versions: "Versions" delta: added: "Ajouté" modified: "Modifié" deleted: "Supprimé" moved_index: "Index changé" text_diff: "Différence de texte" merge_conflict_with: "Fusionner les conflits avec" no_changes: "Aucuns Changements"
174168
module.exports = nativeDescription: "français", englishDescription: "French", translation: common: loading: "Chargement..." saving: "Sauvegarde..." sending: "Envoi..." send: "Envoyer" cancel: "Annuler" save: "Sauvegarder" publish: "Publier" create: "Creer" delay_1_sec: "1 seconde" delay_3_sec: "3 secondes" delay_5_sec: "5 secondes" manual: "Manuel" fork: "Fork" play: "Jouer" retry: "Reessayer" watch: "Regarder" unwatch: "Ne plus regarder" submit_patch: "Soumettre un correctif" units: second: "seconde" seconds: "secondes" minute: "minute" minutes: "minutes" hour: "heure" hours: "heures" day: "jour" days: "jours" week: "semaine" weeks: "semaines" month: "mois" months: "mois" year: "année" years: "années" modal: close: "Fermer" okay: "Ok" not_found: page_not_found: "Page non trouvée" nav: play: "Jouer" community: "Communauté" editor: "É<NAME>" blog: "Blog" forum: "Forum" account: "Compte" admin: "Admin" home: "Accueil" contribute: "Contribuer" legal: "Mentions légales" about: "À propos" contact: "Contact" twitter_follow: "Suivre" employers: "Employeurs" versions: save_version_title: "Enregistrer une nouvelle version" new_major_version: "Nouvelle version majeure" cla_prefix: "Pour enregistrer vos modifications vous devez d'abord accepter notre" cla_url: "Copyright" cla_suffix: "." cla_agree: "J'accepte" login: sign_up: "Créer un compte" log_in: "Connexion" logging_in: "Connecter" log_out: "Déconnexion" recover: "Récupérer son compte" recover: recover_account_title: "Récupérer son compte" send_password: "<PASSWORD>" signup: create_account_title: "Créer un compte pour sauvegarder votre progression" description: "C'est gratuit. Simplement quelques informations et vous pourrez commencer :" email_announcements: "Recevoir les annonces par email" coppa: "13+ ou hors É-U" coppa_why: "(Pourquoi?)" creating: "Création du compte en cours..." sign_up: "S'abonner" log_in: "se connecter avec votre mot de passe" social_signup: "Ou, vous pouvez vous identifier avec Facecook ou G+:" required: "Vous devez être connecté pour voir cela" home: slogan: "Apprenez à coder tout en jouant" no_ie: "CodeCombat ne fonctionnera pas sous Internet Explorer 9 ou moins. Désolé !" no_mobile: "CodeCombat n'a pas été créé pour les plateformes mobiles donc il est possible qu'il ne fonctionne pas correctement ! " play: "Jouer" old_browser: "Oh oh, votre navigateur est trop vieux pour executer CodeCombat. Désolé!" old_browser_suffix: "Vous pouvez essayer quand même, mais celà ne marchera probablement pas." campaign: "Campagne" for_beginners: "Pour débutants" multiplayer: "Multijoueurs" for_developers: "Pour développeurs" play: choose_your_level: "Choisissez votre niveau" adventurer_prefix: "Vous pouvez passer à n'importe quel niveau ci-dessous, ou discuter des niveaux sur " adventurer_forum: "le forum de l'Aventurier" adventurer_suffix: "." campaign_beginner: "Campagne du Débutant" campaign_beginner_description: "... dans laquelle vous apprendrez la magie de la programmation." campaign_dev: "Niveaux aléatoires plus difficiles" campaign_dev_description: "... dans lesquels vous apprendrez à utiliser l'interface en faisant quelque chose d'un petit peu plus dur." campaign_multiplayer: "Campagne multi-joueurs" campaign_multiplayer_description: "... dans laquelle vous coderez en face à face contre d'autres joueurs." campaign_player_created: "Niveaux créés par les joueurs" campaign_player_created_description: "... Dans laquelle vous serez confrontés à la créativité des votres.<a href=\"/contribute#artisan\">Artisan Wizards</a>." level_difficulty: "Difficulté: " play_as: "Jouer comme " spectate: "Spectateur" contact: contact_us: "Contacter CodeCombat" welcome: "<NAME> de vos nouvelles! Utilisez ce formulaire pour nous envoyer un mail." contribute_prefix: "Si vous voulez contribuer, consultez notre " contribute_page: "page de contributions" contribute_suffix: "!" forum_prefix: "Pour tout sujet d'ordre publique, merci d'utiliser " forum_page: "notre forum" forum_suffix: " À la place." send: "Envoyer un commentaire" contact_candidate: "Contacter le candidat" recruitment_reminder: "Utilisez ce formulaire pour entrer en contact avec le candidat qui vous interesse. Souvenez-vous que CodeCombat facture 15% de la première année de salaire. Ces frais sont dues à l'embauche de l'employé, ils sont remboursable pendant 90 jours si l'employé ne reste pas employé. Les employés à temps partiel, à distance ou contractuel sont gratuits en tant que stagiaires." diplomat_suggestion: title: "Aidez à traduire CodeCombat!" sub_heading: "Nous avons besoin de vos compétences en langues." pitch_body: "Nous développons CodeCombat en Anglais, mais nous avons déjà des joueurs de partout dans le monde. Beaucoup d'entre eux veulent jouer en Français mais ne parlent pas l'anglais, donc si vous parlez aussi bien l'anglais que le français, aidez-nous en devenant traducteur et aidez à traduire aussi bien le site que tous les niveaux en français." missing_translations: "Jusqu'à ce que nous ayons tout traduit en français, vous verrez de l'anglais quand le français ne sera pas disponible." learn_more: "Apprenez en plus sur les Traducteurs" subscribe_as_diplomat: "S'inscrire en tant que traducteur" wizard_settings: title: "Paramètres du Magicien" customize_avatar: "Personnaliser votre avatar" active: "Actif" color: "Couleur" group: "Groupe" clothes: "Vêtements" trim: "Tailleur" cloud: "Nuage" team: "Equipe" spell: "Sort" boots: "Bottes" hue: "Teinte" saturation: "Saturation" lightness: "Luminosité" account_settings: title: "Préférences du compte" not_logged_in: "Connectez-vous ou créez un compte pour modifier vos préférences." autosave: "Enregistrer automatiquement les modifications" me_tab: "Moi" picture_tab: "Photos" upload_picture: "Héberger une image" wizard_tab: "Magicien" password_tab: "Mot de passe" emails_tab: "Emails" admin: "Admin" wizard_color: "Couleur des vêtements du Magicien" new_password: "<PASSWORD> passe" new_password_verify: "<PASSWORD>" email_subscriptions: "Abonnements" email_announcements: "Annonces" email_announcements_description: "Recevoir des mails sur les dernières actualités et sur le développement de CodeCombat." email_notifications: "Notifications" email_notifications_summary: "Commandes pour personaliser les notifications automatiques d'email liées à votre activité sur CodeCombat." email_any_notes: "Toutes Notifications" email_any_notes_description: "Désactivez pour ne plus recevoir de notifications par e-mail." email_recruit_notes: "Offres d'emploi" email_recruit_notes_description: "Si vous jouez vraiment bien, nous pouvons vous contacter pour vous proposer un (meilleur) emploi." contributor_emails: "Emails des contributeurs" contribute_prefix: "Nous recherchons des personnes pour se joindre à notre groupe! Consultez la " contribute_page: "page de contributions" contribute_suffix: " pour en savoir plus." email_toggle: "Tout basculer" error_saving: "Problème d'enregistrement" saved: "Changements sauvegardés" password_mismatch: "Le mot de passe ne correspond pas." job_profile: "Profil d'emploi" job_profile_approved: "Votre profil d'emploi a été approuvé par CodeCombat. Les employeurs seront en mesure de voir votre profil jusqu'à ce que vous le marquez inactif ou qu'il n'a pas été changé pendant quatre semaines." job_profile_explanation: "Salut! Remplissez-le et nous prendrons contact pour vous trouver un emploi de développeur de logiciels." sample_profile: "Voir un exemple de profil" view_profile: "Voir votre profil" account_profile: settings: "Paramètres" edit_profile: "Editer Profil" done_editing: "Modifications effectué" profile_for_prefix: "Profil pour " profile_for_suffix: "" featured: "Complet" not_featured: "Incomplet" looking_for: "à la recherche de:" last_updated: "Dernière Mise à jour:" contact: "Contact" active: "En recherche d'offres" inactive: "Ne recherche pas d'offres" complete: "terminé" next: "Suivant" next_city: "ville ?" next_country: "choisissez votre pays." next_name: "nom ?" next_short_description: "résumez votre profil en quelques mots." next_long_description: "décrivez le travail que vous cherchez." next_skills: "listez au moins 5 compétances." next_work: "décrivez votre expérience professionnelle." next_education: "raconter votre scolarité." next_projects: "décrivez jusqu'à 3 projets sur lesquels vous avez travaillé." next_links: "ajouter des liens internet vers des sites personnels ou des réseaux sociaux." next_photo: "ajouter une photo professionelle (optionnel)." next_active: "déclarez vous ouvert aux offres pour apparaitre dans les recherches." example_blog: "Votre blog" example_personal_site: "Site Web" links_header: "Liens personnels" links_blurb: "Lien vers d'autres sites ou profils que vous souhaitez mettre en avant, comme votre GitHub, LinkedIn ou votre blog." links_name: "Nom du lien" links_name_help: "A quoi êtes vous lié ?" links_link_blurb: "Lien URL" basics_header: "Mettre à jour les information basiques" basics_active: "Ouvert aux propositions" basics_active_help: "Voulez-vous des offres maintenant ?" basics_job_title: "Titre du poste souhaité" basics_job_title_help: "Quel est le rôle que vous cherchez ?" basics_city: "Ville" basics_city_help: "Ville dans laquelle vous souhaitez travailler (ou dans laquelle vous vivez actuellement)." basics_country: "Pays" basics_country_help: "Pays dans lequel vous souhaitez travailler (ou dans lequel vous vivez actuellement)." basics_visa: "Statut de travail aux Etats-Unis" basics_visa_help: "Etes vous autorisé à travailler aux Etats-Unis ou avez vous besoin d'un parrainage pour le visa ?" basics_looking_for: "Recherche" basics_looking_for_full_time: "Temps plein" basics_looking_for_part_time: "Temps partiel" basics_looking_for_remote: "A distance" basics_looking_for_contracting: "Contrat" basics_looking_for_internship: "Stage" basics_looking_for_help: "Quel genre de poste de développeur voulez-vous ?" name_header: "Remplissez votre nom" name_anonymous: "<NAME>" name_help: "Le nom que vous souhaitez que l'employeur voie, par exemple '<NAME>'." short_description_header: "Décrivez vous en quelques mots" short_description_blurb: "Ajoutez une phrase d'accroche pour permettre à un employeur d'en savoir plus sur vous." short_description: "Description courte" short_description_help: "Qui êtes vous et que recherchez vous ? 140 caractères max." skills_header: "Compétences" skills_help: "Notez vos compétence de développement par ordre de maitrise." long_description_header: "Détaillez votre poste souhaité" long_description_blurb: "Faites savoir aux employeurs combien vous êtes génial et quel poste vous voulez." long_description: "Biographie" long_description_help: "Décrivez-vous aux potentiels employeurs. Soyez bref et direct. Nous vous recommandons de bien indiquer quel poste vous intéresse le plus. 600 caractères max." work_experience: "Experience de travail" work_header: "Présentez votre parcours professionnel" work_years: "Années d'expérience" work_years_help: "Combien d'années d'expérience professionnelle (salarié) avez-vous dans le développement logiciel ?" work_blurb: "Lister vos missions les plus pertinentes, les plus récentes en premier." work_employer: "Employeur" work_employer_help: "Nom de votre employeur." work_role: "Titre du poste" work_role_help: "Quel était l'intitulé de votre mission ou votre poste ?" work_duration: "Durée" # work_duration_help: "When did you hold this gig?" work_description: "Description" work_description_help: "Qu'est-ce que vous y avez fait ? (140 carac.; optionel)" education: "Education" education_header: "Racontez vos exploits scolaires" education_blurb: "Lister vos exploits scolaires." education_school: "Etablissement" education_school_help: "Nom de l'établissement." education_degree: "Diplôme" education_degree_help: "Quel était votre diplôme et votre domaine d'étude ?" education_duration: "Dates" education_duration_help: "Quand ?" education_description: "Description" education_description_help: "Mettez en avant ce que vous voulez à propos de votre parcours scolaire. (140 carac.; optionel)" our_notes: "Notes" # remarks: "Remarks" projects: "Projets" projects_header: "Ajoutez 3 projets" projects_header_2: "Projets (Top 3)" projects_blurb: "Mettez en avant vos projets pour épater les employeurs." project_name: "Nom du projet" project_name_help: "Comment avez-vous appelé votre projet ?" project_description: "Description" project_description_help: "Décrivez brièvement le projet." project_picture: "Image" project_picture_help: "Chargez une image de 230x115px oou plus grande pour présenter votre projet." project_link: "Lien" project_link_help: "Lien vers le projet." # player_code: "Player Code" employers: # hire_developers_not_credentials: "Hire developers, not credentials." # get_started: "Get Started" # already_screened: "We've already technically screened all our candidates" # filter_further: ", but you can also filter further:" # filter_visa: "Visa" # filter_visa_yes: "US Authorized" # filter_visa_no: "Not Authorized" # filter_education_top: "Top School" # filter_education_other: "Other" # filter_role_web_developer: "Web Developer" # filter_role_software_developer: "Software Developer" # filter_role_mobile_developer: "Mobile Developer" # filter_experience: "Experience" # filter_experience_senior: "Senior" # filter_experience_junior: "Junior" # filter_experience_recent_grad: "Recent Grad" # filter_experience_student: "College Student" # filter_results: "results" # start_hiring: "Start hiring." # reasons: "Three reasons you should hire through us:" # everyone_looking: "Everyone here is looking for their next opportunity." # everyone_looking_blurb: "Forget about 20% LinkedIn InMail response rates. Everyone that we list on this site wants to find their next position and will respond to your request for an introduction." # weeding: "Sit back; we've done the weeding for you." # weeding_blurb: "Every player that we list has been screened for technical ability. We also perform phone screens for select candidates and make notes on their profiles to save you time." # pass_screen: "They will pass your technical screen." # pass_screen_blurb: "Review each candidate's code before reaching out. One employer found that 5x as many of our devs passed their technical screen than hiring from Hacker News." # make_hiring_easier: "Make my hiring easier, please." what: "Qu'est-ce que CodeCombat?" what_blurb: "CodeCombat est un jeu de programmation multijoueur par navigateur. Les Joueurs écrivent le code pour contrôler leurs troupes dans des batailles contre d'autres développeurs. Nous prenons en charge JavaScript, Python, Lua, Clojure, CoffeeScript, et Io." # cost: "How much do we charge?" # cost_blurb: "We charge 15% of first year's salary and offer a 100% money back guarantee for 90 days. We don't charge for candidates who are already actively being interviewed at your company." candidate_name: "<NAME>" candidate_location: "Localisation" candidate_looking_for: "Poste pour" candidate_role: "Rôle" candidate_top_skills: "Talents/Aptitudes" candidate_years_experience: "Années d'expérience" candidate_last_updated: "Dernière mise à jour" # candidate_who: "Who" # featured_developers: "Featured Developers" # other_developers: "Other Developers" # inactive_developers: "Inactive Developers" play_level: done: "Fait" grid: "Grille" customize_wizard: "Personnaliser le magicien" home: "Accueil" guide: "Guide" multiplayer: "Multijoueur" restart: "Relancer" goals: "Objectifs" success: "Succès" incomplete: "Imcoplet" timed_out: "Plus de temps" failing: "Echec" action_timeline: "Action sur la ligne de temps" click_to_select: "Clique sur une unité pour la sélectionner." reload_title: "Recharger tout le code?" reload_really: "Êtes-vous sûr de vouloir recharger ce niveau et retourner au début?" reload_confirm: "Tout recharger" victory_title_prefix: "" victory_title_suffix: " Terminé" victory_sign_up: "Inscrivez-vous pour recevoir les mises à jour" victory_sign_up_poke: "Vous voulez recevoir les dernières actualités par mail? Créez un compte gratuitement et nous vous tiendrons informés!" victory_rate_the_level: "Notez ce niveau: " # victory_return_to_ladder: "Return to Ladder" victory_play_next_level: "Jouer au prochain niveau" victory_go_home: "Retourner à l'accueil" victory_review: "Dites-nous en plus!" victory_hour_of_code_done: "Déjà fini ?" victory_hour_of_code_done_yes: "Oui, j'ai fini mon heure de code!" multiplayer_title: "Préférences multijoueurs" multiplayer_link_description: "Partage ce lien pour que tes amis viennent jouer avec toi." multiplayer_hint_label: "Astuce:" multiplayer_hint: " Cliquez sur le lien pour tout sélectionner, puis appuyer sur Pomme-C ou Ctrl-C pour copier le lien." multiplayer_coming_soon: "Plus de fonctionnalités multijoueurs sont à venir" # multiplayer_sign_in_leaderboard: "Sign in or create an account and get your solution on the leaderboard." guide_title: "Guide" tome_minion_spells: "Les sorts de vos soldats" tome_read_only_spells: "Sorts en lecture-seule" tome_other_units: "Autres unités" tome_cast_button_castable: "Jeter le sort" tome_cast_button_casting: "Sort en court" tome_cast_button_cast: "Sort jeté" tome_autocast_delay: "Temps de recharge" tome_select_spell: "Choisissez un sort" tome_select_a_thang: "Sélectionnez une unité pour" tome_available_spells: "Sorts diponibles" hud_continue: "Continuer (appuie sur shift ou espace)" spell_saved: "Sort enregistré" skip_tutorial: "Passer (esc)" editor_config: "Config de l'éditeur" editor_config_title: "Configuration de l'éditeur" editor_config_level_language_label: "Langage pour le niveau" # editor_config_level_language_description: "Define the programming language for this particular level." editor_config_default_language_label: "Langage de Programmation par défaut" editor_config_default_language_description: "Choississez le langage de programmation que vous souhaitez dons les nouveaux niveaux" editor_config_keybindings_label: "Raccourcis clavier" editor_config_keybindings_default: "Par défault (Ace)" editor_config_keybindings_description: "Ajouter de nouveaux raccourcis connus depuis l'éditeur commun." # editor_config_livecompletion_label: "Live Autocompletion" # editor_config_livecompletion_description: "Displays autocomplete suggestions while typing." editor_config_invisibles_label: "Afficher les caractères non-imprimables" editor_config_invisibles_description: "Permet d'afficher les caractères comme les espaces et les tabulations." editor_config_indentguides_label: "Montrer les indentations" editor_config_indentguides_description: "Affiche des guides verticaux qui permettent de visualiser l'indentation." editor_config_behaviors_label: "Auto-complétion" editor_config_behaviors_description: "Ferme automatiquement les accolades, parenthèses, et chaînes de caractères." keyboard_shortcuts: "Raccourcis Clavier" loading_ready: "Pret!" tip_insert_positions: "Maj+Clic un point pour insérer les coordonnées dans l'éditeur ." tip_toggle_play: "Jouer/Pause avec Ctrl+P." # tip_scrub_shortcut: "Ctrl+[ and Ctrl+] rewind and fast-forward." # tip_guide_exists: "Click the guide at the top of the page for useful info." tip_open_source: "CodeCombat est 100% open source!" tip_beta_launch: "La beta de CodeCombat a été lancée en Octobre 2013" tip_js_beginning: "JavaScript n'est que le commencement." # tip_autocast_setting: "Adjust autocast settings by clicking the gear on the cast button." think_solution: "Reflechissez a propos de la solution et non du problème." tip_theory_practice: "En théorie, il n'y a pas de différence entre la théorie et la pratique. Mais en pratique il y en a. - <NAME>" # tip_error_free: "There are two ways to write error-free programs; only the third one works. - <NAME>" tip_debugging_program: "Si débugger est l'art de corriger les bugs, alors programmer est l'art d'en créer. . - <NAME>" # tip_forums: "Head over to the forums and tell us what you think!" tip_baby_coders: "Dans le futur, même les bébés seront des archimages." # tip_morale_improves: "Loading will continue until morale improves." # tip_all_species: "We believe in equal opportunities to learn programming for all species." # tip_reticulating: "Reticulating spines." # tip_harry: "Yer a Wizard, " # tip_great_responsibility: "With great coding skill comes great debug responsibility." # tip_munchkin: "If you don't eat your vegetables, a munchkin will come after you while you're asleep." # tip_binary: "There are only 10 types of people in the world: those who understand binary, and those who don't." # tip_commitment_yoda: "A programmer must have the deepest commitment, the most serious mind. ~ Yoda" # tip_no_try: "Do. Or do not. There is no try. - Yoda" # tip_patience: "Patience you must have, young Padawan. - Yoda" # tip_documented_bug: "A documented bug is not a bug; it is a feature." # tip_impossible: "It always seems impossible until it's done. - <NAME>" # tip_talk_is_cheap: "Talk is cheap. Show me the code. - <NAME>" # tip_first_language: "The most disastrous thing that you can ever learn is your first programming language. - <NAME>" # tip_hardware_problem: "Q: How many programmers does it take to change a light bulb? A: None, it's a hardware problem." time_current: "Maintenant:" time_total: "Max:" time_goto: "Allez a:" infinite_loop_try_again: "Reessayer" infinite_loop_reset_level: "Redemarrer le niveau" infinite_loop_comment_out: "Supprimez les commentaire de mon code" keyboard_shortcuts: keyboard_shortcuts: "<NAME>" space: "Espace" enter: "Entrer" escape: "Echap" # cast_spell: "Cast current spell." # continue_script: "Continue past current script." # skip_scripts: "Skip past all skippable scripts." # toggle_playback: "Toggle play/pause." # scrub_playback: "Scrub back and forward through time." # single_scrub_playback: "Scrub back and forward through time by a single frame." # scrub_execution: "Scrub through current spell execution." # toggle_debug: "Toggle debug display." # toggle_grid: "Toggle grid overlay." # toggle_pathfinding: "Toggle pathfinding overlay." # beautify: "Beautify your code by standardizing its formatting." # move_wizard: "Move your Wizard around the level." admin: av_title: "Vues d'administrateurs" av_entities_sub_title: "Entités" av_entities_users_url: "Utilisateurs" av_entities_active_instances_url: "Instances actives" av_entities_employer_list_url: "Liste des employés" av_other_sub_title: "Autre" av_other_debug_base_url: "Base (pour debugger base.jade)" u_title: "Liste des utilisateurs" lg_title: "Dernières parties" clas: "CLAs" community: level_editor: "Editeur de niveau" main_title: "Communauté CodeCombat" facebook: "Facebook" twitter: "Twitter" gplus: "Google+" editor: main_title: "Éditeurs CodeCombat" main_description: "Créé tes propres niveaux, campagnes, unités et contenus éducatifs. Nous vous fournissons tous les outils dont vous avez besoin!" article_title: "Éditeur d'article" article_description: "Écris des articles qui donnent aux joueurs un aperçu des concepts de programmation qui peuvent être utilisés dans différents niveaux et campagnes." thang_title: "Éditeur Thang" thang_description: "Créé des unités, définis leur comportement de base, graphisme et son. Pour l'instant cette fonctionnalité ne supporte que l'importation d'images vectorielles exportées depuis Flash." level_title: "Éditeur de niveau" level_description: "Inclut les outils de script, l'upload de vidéos, et l'élaboration de logiques personnalisées pour créer toutes sortes de niveaux. Tout ce que nous utilisons nous-mêmes!" # achievement_title: "Achievement Editor" # got_questions: "Questions about using the CodeCombat editors?" contact_us: "contactez nous!" hipchat_prefix: "Vous pouvez aussi nous trouver dans notre " hipchat_url: "conversation HipChat." back: "Retour" revert: "Annuler" revert_models: "Annuler les modèles" # pick_a_terrain: "Pick A Terrain" # small: "Small" # grassy: "Grassy" fork_title: "Fork une nouvelle version" fork_creating: "Créer un Fork..." # randomize: "Randomize" more: "Plus" wiki: "Wiki" live_chat: "Chat en live" level_some_options: "Quelques options?" level_tab_thangs: "Thangs" level_tab_scripts: "Scripts" level_tab_settings: "Paramètres" level_tab_components: "Composants" level_tab_systems: "Systèmes" level_tab_thangs_title: "Thangs actuels" level_tab_thangs_all: "Tout" level_tab_thangs_conditions: "Conditions de départ" level_tab_thangs_add: "ajouter des Thangs" delete: "Supprimer" duplicate: "Dupliquer" level_settings_title: "Paramètres" level_component_tab_title: "Composants actuels" level_component_btn_new: "Créer un nouveau composant" level_systems_tab_title: "Systèmes actuels" level_systems_btn_new: "Créer un nouveau système" level_systems_btn_add: "Ajouter un système" level_components_title: "Retourner à tous les Thangs" level_components_type: "Type" level_component_edit_title: "Éditer le composant" level_component_config_schema: "Configurer le schéma" level_component_settings: "Options" level_system_edit_title: "Éditer le système" create_system_title: "Créer un nouveau système" new_component_title: "Créer un nouveau composant" new_component_field_system: "Système" new_article_title: "Créer un nouvel article" new_thang_title: "Créer un nouveau Type Thang" new_level_title: "Créer un nouveau niveau" new_article_title_login: "Connectez vous pour créer un nouvel article" # new_thang_title_login: "Log In to Create a New Thang Type" new_level_title_login: "Connectez vous pour créer un nouveau niveau" # new_achievement_title: "Create a New Achievement" # new_achievement_title_login: "Log In to Create a New Achievement" article_search_title: "Rechercher dans les articles" thang_search_title: "Rechercher dans les types Thang" level_search_title: "Rechercher dans les niveaux" # achievement_search_title: "Search Achievements" read_only_warning2: "Note: vous ne pouvez sauvegarder aucune édition, car vous n'êtes pas identifié." article: edit_btn_preview: "Prévisualiser" edit_article_title: "Éditer l'article" general: and: "et" name: "Nom" body: "Corps" version: "Version" commit_msg: "Message de mise à jour" version_history: "Historique des versions" version_history_for: "Historique des versions pour : " result: "Resultat" results: "Résultats" description: "Description" or: "ou" subject: "Sujet" email: "Email" password: "<PASSWORD>" message: "Message" code: "Code" ladder: "Companion" when: "Quand" opponent: "Adversaire" rank: "Rang" score: "Score" win: "Victoire" loss: "Défaite" tie: "Ex-aequo" easy: "Facile" medium: "Moyen" hard: "Difficile" player: "Joueur" about: who_is_codecombat: "Qui est CodeCombat?" why_codecombat: "Pourquoi CodeCombat?" who_description_prefix: "ont lancé CodeCombat ensemble en 2013. Nous avons aussi créé " who_description_suffix: "en 2008, l'améliorant jusqu'au rang de première application web et iOS pour apprendre à écrire les caractères chinois et japonais." who_description_ending: "Maintenant nous apprenons aux gens à coder." why_paragraph_1: "En développant Skritter, George ne savait pas programmer et était frustré de ne pas pouvoir implémenter ses idées. Ensuite, il essaya d'apprendre, mais les cours n'étaient pas assez rapides. Son colocataire, voulant se requalifier et arrêter d'apprendre, essaya Codecademy, mais \"s'ennuya.\" Chaque semaine un nouvel ami commençait Codecademy, puis abandonnait. Nous nous sommes rendus compte que nous avions résolu le même problème avec Skritter: les gens apprennant grâce à des cours lents et intensifs quand nous avons besoin d'expérience rapide et intensive. Nous savons comment remédier à ça." why_paragraph_2: "Besoin d'apprendre à développer? Vous n'avez pas besoin de cours. Vous avez besoin d'écrire beaucoup de code et de vous amuser en le faisant." why_paragraph_3_prefix: "C'est ce dont il s'agit en programmation. Ça doit être amusant. Pas amusant comme" why_paragraph_3_italic: "Génial un badge" why_paragraph_3_center: "Mais amusant comme" why_paragraph_3_italic_caps: "NAN MAMAN JE DOIS FINIR MON NIVEAU!" why_paragraph_3_suffix: "C'est pourquoi CodeCombat est un jeu multijoueur, pas un cours avec une leçon jouée. Nous n'arrêterons pas avant que vous ne puissiez plus arrêter — mais cette fois, c'est une bonne chose." why_paragraph_4: "Si vous devez devenir accro à un jeu, accrochez-vous à celui-ci et devenez un des mages de l'âge de la technologie." why_ending: "Et oh, c'est gratuit. " why_ending_url: "Commence ton apprentissage maintenant!" george_description: "PDG, homme d'affaire, web designer, game designer, et champion des programmeurs débutants." scott_description: "Programmeur extraordinaire, architecte logiciel, assistant cuisinier, et maitre de la finance. <NAME> est le raisonnable." nick_description: "Assistant programmeur, mage à la motivation excentrique, et bidouilleur de l'extrême. <NAME> peut faire n'importe quoi mais il a choisi CodeCombat." jeremy_description: "Mage de l'assistance client, testeur de maniabilité, et community manager; vous avez probablement déjà parlé avec <NAME>." michael_description: "Programmeur, administrateur réseau, et l'enfant prodige du premier cycle, <NAME> est la personne qui maintient nos serveurs en ligne." glen_description: "Programmeur et développeur de jeux passioné, avec la motivation pour faire de ce monde un meilleur endroit, en développant des choses qui comptent. Le mot impossible est introuvable dans son dictionnaire. Apprendre de nouveaux talents est sa joie !" legal: page_title: "Légal" opensource_intro: "CodeCombat est complètement gratuit et open source." opensource_description_prefix: "Regardez " github_url: "notre GitHub" opensource_description_center: "et aidez nous si vous voulez! CodeCombat est construit sur plusieurs projets open source, et nous les aimons. Regardez " archmage_wiki_url: "notre wiki des Archimages" opensource_description_suffix: "pour trouver la liste des logiciels qui rendent ce jeu possible." practices_title: "Bonnes pratiques" practices_description: "Ce sont les promesses que nous vous faisons à vous, le joueur, en jargon un peu juridique." privacy_title: "Vie privée" privacy_description: "Nous ne vendrons aucune de vos informations personnelles. Nous comptons faire de l'argent éventuellement avec le recrutement, mais soyez assuré que nous ne fournirons aucune de vos informations personnelles à des compagnies intéressées sans votre consentement explicite." security_title: "Sécurité" security_description: "Nous faisons tout notre possible pour conserver la confidentialité de vos informations personnelles. En tant que projet open source, notre site est ouvert à tous ceux qui souhaitent examiner et améliorer nos systèmes de sécurité." email_title: "Email" email_description_prefix: "Nous ne vous innonderons pas d'email. Grâce à" email_settings_url: "vos paramètres d'email " email_description_suffix: "ou avec des liens disponibles dans nos emails, vous pouvez changer vos préférences ou vous désinscrire à tout moment." cost_title: "Coût" cost_description: "Pour l'instant, CodeCombat est gratuit à 100%! Un de nos principaux objectifs est que ça le reste, pour qu'autant de gens possible puissent y jouer, indépendamment de leur niveau de vie. Si le ciel s'assombrit, nous devrons peut-être rendre les inscriptions payantes ou une partie du contenu, mais nous ne le souhaitons pas. Avec un peu de chance, nous serons capables de soutenir l'entreprise avec :" recruitment_title: "Recrutement" recruitment_description_prefix: "Ici chez CodeCombat, vous allez devenir un magicien puissant, pas seulement dans le jeu, mais aussi dans la vie réelle." url_hire_programmers: "Personne ne peut recruter des développeurs aussi vite" recruitment_description_suffix: "donc une fois que vous aurez aiguisé votre savoir-faire et si vous l'acceptez, nous montrerons vos meilleurs bouts de code aux milliers d'employeurs qui attendent une chance de vous recruter. Ils nous payent un peu pour ensuite vous payer" recruitment_description_italic: "beaucoup" recruitment_description_ending: "le site reste gratuit et tout le monde est content. C'est le but." copyrights_title: "Copyrights et Licences" contributor_title: "Contributor License Agreement" contributor_description_prefix: "Toute contribution, sur le site et sur le répertoire GitHub, est sujette à nos" cla_url: "CLA" contributor_description_suffix: "auxquelles vous devez vous soumettre avant de contribuer." code_title: "Code - MIT" code_description_prefix: "Tout code siglé CodeCombat ou hébergé sur codecombat.com, sur le répertoire GitHub ou dans la base de données de codecombat.com, est sous la licence" mit_license_url: "MIT" code_description_suffix: "Cela inclut le code dans Systèmes et Composants qui est rendu disponible par CodeCombat dans le but de créer des niveaux." art_title: "Art/Musique - Creative Commons " art_description_prefix: "Tout le contenu commun est sous licence" cc_license_url: "Creative Commons Attribution 4.0 International" art_description_suffix: "Le contenu commun est tout ce qui est rendu disponible par CodeCombat afin de créer des niveaux. Cela inclut :" art_music: "La musique" art_sound: "Le son" art_artwork: "Les artworks" art_sprites: "Les sprites" art_other: "Tout le reste du contenu non-code qui est rendu accessible lors de la création de niveaux." art_access: "Pour l'instant il n'y a aucun système universel et facile pour rassembler ces ressources. En général, accédez y par les URL comme le fait le site, contactez-nous pour de l'aide, ou aidez-nous à agrandir le site pour rendre ces ressources plus facilement accessibles." art_paragraph_1: "Pour l'attribution, s'il vous plait, nommez et référencez codecombat.com près de la source utilisée ou dans un endroit approprié. Par exemple:" use_list_1: "Si utilisé dans un film ou un autre jeu, incluez codecombat.com dans le générique." use_list_2: "Si utilisé sur un site web, incluez un lien près de l'utilisation, par exemple sous une image, ou sur une page d'attribution générale où vous pourrez aussi mentionner les autres travaux en Creative Commons et les logiciels open source utilisés sur votre site. Quelque chose qui fait clairement référence à CodeCombat, comme un article de blog mentionnant CodeCombat, n'a pas besoin d'attribution séparée." art_paragraph_2: "Si le contenu utilisé n'est pas créé par CodeCombat mais par un autre utilisateur de codecombat.com, attribuez le à cet utilisateur, et suivez les recommandations fournies dans la ressource de la description s'il y en a." rights_title: "Droits réservés" rights_desc: "Tous les droits sont réservés pour les niveaux eux-mêmes. Cela inclut" rights_scripts: "Les scripts" rights_unit: "La configuration unitaire" rights_description: "La description" rights_writings: "L'écriture" rights_media: "Les médias (sons, musiques) et tous les autres contenus créatifs créés spécialement pour ce niveau et non rendus généralement accessibles en créant des niveaux." rights_clarification: "Pour clarifier, tout ce qui est rendu accessible dans l'éditeur de niveaux dans le but de créer des niveaux est sous licence CC, tandis que le contenu créé avec l'éditeur de niveaux ou uploadé dans le but de créer un niveau ne l'est pas." nutshell_title: "En un mot" nutshell_description: "Chaque ressource que nous fournissons dans l'éditeur de niveau est libre d'utilisation pour créer des niveaux. Mais nous nous réservons le droit de restreindre la distribution des niveaux créés (qui sont créés sur codecombat.com) ils peuvent donc devenir payants dans le futur, si c'est ce qui doit arriver." canonical: "La version de ce document est la version définitive et canonique. En cas d'irrégularité dans les traductions, le document anglais fait foi." contribute: page_title: "Contribution" character_classes_title: "Classes du personnage" introduction_desc_intro: "Nous avons beaucoup d'espoir pour CodeCombat." introduction_desc_pref: "Nous voulons être l'endroit où les développeurs de tous horizons viennent pour apprendre et jouer ensemble, présenter les autres au monde du développement, et refléter le meilleur de la communauté. Nous ne pouvons et ne voulons pas faire ça seuls ; ce qui rend super les projets comme GitHub, Stack Overflow et Linux, est que les gens qui l'utilisent le construisent. Dans ce but, " introduction_desc_github_url: "CodeCombat est totalement open source" introduction_desc_suf: ", et nous avons pour objectif de fournir autant de manières possibles pour que vous participiez et fassiez de ce projet autant le votre que le notre." introduction_desc_ending: "Nous espérons que vous allez joindre notre aventure!" introduction_desc_signature: "- <NAME>, <NAME>, <NAME>, <NAME>, <NAME> et <NAME>" alert_account_message_intro: "Et tiens!" alert_account_message: "Pour souscrire aux e-mails, vous devez être connecté" # archmage_summary: "Interested in working on game graphics, user interface design, database and server organization, multiplayer networking, physics, sound, or game engine performance? Want to help build a game to help other people learn what you are good at? We have a lot to do and if you are an experienced programmer and want to develop for CodeCombat, this class is for you. We would love your help building the best programming game ever." archmage_introduction: "L'une des meilleures parties de la création d'un jeu est qu'il regroupe tant de choses différentes. Graphismes, sons, réseau en temps réel, réseaux sociaux, et bien sur bien d'autres aspects de la programmation, de la gestion bas niveau de base de données, et de l'administration de serveur à l'élaboration d'interfaces utilisateur. Il y a tant à faire, et si vous êtes un programmeur expérimenté avec une aspiration à vraiment plonger dans le fond de CodeCombat, cette classe est faite pour vous. Nous aimerions avoir votre aide pour le meilleur jeu de développement de tous les temps." class_attributes: "Attributs de classe" archmage_attribute_1_pref: "Connaissance en " archmage_attribute_1_suf: ", ou le désir d'apprendre. La plupart de notre code est écrit avec ce langage. Si vous êtes fan de Ruby ou Python, vous vous sentirez chez vous. C'est du JavaScript, mais avec une syntaxe plus sympatique." archmage_attribute_2: "De l'expérience en développement et en initiatives personnelles. Nous vous aiderons à vous orienter, mais nous ne pouvons pas passer plus de temps à vous entrainer." how_to_join: "Comment nous rejoindre" join_desc_1: "N'importe qui peut aider! Vous avez seulement besoin de regarder " join_desc_2: "pour commencer, et cocher la case ci-dessous pour vous marquer comme un archimage courageux et obtenir les dernières nouvelles par email. Envie de discuter de ce qu'il y a à faire ou de comment être plus impliqué? " join_desc_3: ", ou trouvez-nous dans nos " join_desc_4: "et nous partirons de là!" join_url_email: "Contactez nous" join_url_hipchat: "conversation publique HipChat" more_about_archmage: "En apprendre plus sur devenir un puissant archimage" archmage_subscribe_desc: "Recevoir un email sur les nouvelles possibilités de développement et des annonces." # artisan_summary_pref: "Want to design levels and expand CodeCombat's arsenal? People are playing through our content at a pace faster than we can build! Right now, our level editor is barebone, so be wary. Making levels will be a little challenging and buggy. If you have visions of campaigns spanning for-loops to" artisan_summary_suf: ", alors ce travail est pour vous" artisan_introduction_pref: "Nous devons créer des niveaux additionnels! Les gens veulent plus de contenu, et nous ne pouvons pas tous les créer nous-mêmes. Maintenant votre station de travail est au niveau un ; notre éditeur de niveaux est à peine utilisable même par ses créateurs, donc méfiez-vous. Si vous avez des idées sur la boucle for de" artisan_introduction_suf: ", cette classe est faite pour vous." artisan_attribute_1: "Une expérience dans la création de contenu comme celui-ci serait un plus, comme utiliser l'éditeur de niveaux de Blizzard. Mais ce n'est pas nécessaire!" artisan_attribute_2: "Vous aspirez à faire beaucoup de tests et d'itérations. Pour faire de bons niveaux, vous aurez besoin de les proposer aux autres et les regarder les jouer, et être prêt à trouver un grand nombre de choses à corriger." artisan_attribute_3: "Pour l'heure, endurance en binôme avec un Aventurier. Notre éditeur de niveaux est vraiment préliminaire et frustrant à l'utilisation. Vous êtes prévenus!" artisan_join_desc: "Utilisez le créateur de niveaux pour à peu près ces étapes :" artisan_join_step1: "Lire la documentation." artisan_join_step2: "Créé un nouveau niveau et explore les niveaux existants." artisan_join_step3: "Retrouvez nous dans notre conversation HipChat pour obtenir de l'aide." artisan_join_step4: "Postez vos niveaux dans le forum pour avoir des retours." more_about_artisan: "En apprendre plus sur comment devenir un Artisan créatif" artisan_subscribe_desc: "Recevoir un email sur les annonces et mises à jour de l'éditeur de niveaux." # adventurer_summary: "Let us be clear about your role: you are the tank. You are going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class is for you." adventurer_introduction: "Soyons clair à propos de votre rôle : vous êtes le tank. Vous allez subir beaucoup de dommages. Nous avons besoin de gens pour essayer les nouveaux niveaux et aider à identifier comment améliorer les choses. La douleur sera énorme; faire de bons jeux est une longue tâche et personne n'y arrive du premier coup. Si vous pouvez résister et avez un gros score de constitution, alors cette classe est faite pour vous." adventurer_attribute_1: "Une soif d'apprendre. Vous voulez apprendre à développer et nous voulons vous apprendre. Vous allez toutefois faire la plupart de l'apprentissage." adventurer_attribute_2: "Charismatique. Soyez doux mais exprimez-vous sur ce qui a besoin d'être amélioré, et faites des propositions sur comment l'améliorer." adventurer_join_pref: "Soit faire équipe avec (ou recruter!) un artisan et travailler avec lui, ou cocher la case ci-dessous pour recevoir un email quand il y aura de nouveaux niveaux à tester. Nous parlons aussi des niveaux à réviser sur notre réseau" adventurer_forum_url: "notre forum" adventurer_join_suf: "si vous préférez être avertis ainsi, inscrivez-vous ici!" more_about_adventurer: "En apprendre plus sur devenir un brave Aventurier" adventurer_subscribe_desc: "Recevoir un email lorsqu'il y a de nouveaux niveaux à tester." # scribe_summary_pref: "CodeCombat is not just going to be a bunch of levels. It will also be a resource of programming knowledge that players can hook into. That way, each Artisan can link to a detailed article that for the player's edification: documentation akin to what the " # scribe_summary_suf: " has built. If you enjoy explaining programming concepts, then this class is for you." scribe_introduction_pref: "CodeCombat n'est pas seulement un ensemble de niveaux. Il contiendra aussi des ressources pour la connaissance, un wiki des concepts de programmation que les niveaux pourront illustrer. Dans ce but, chaque Artisan pourra, au lieu d'avoir à décrire en détail ce qu'est un opérateur de comparaison, seulement lier son niveau à l'article qui le décrit et qui a été écrit pour aider les joueurs. Quelque chose dans le sens de ce que le " scribe_introduction_url_mozilla: "Mozilla Developer Network" scribe_introduction_suf: " a développé. Si votre définition de l'amusement passe par le format Markdown, alors cette classe est pour vous." scribe_attribute_1: "Les compétences rédactionnelles sont quasiment la seule chose dont vous aurez besoin. Pas seulement la grammaire et l'orthographe, mais être également capable de lier des idées ensembles." contact_us_url: "Contactez-nous" scribe_join_description: "parlez nous un peu de vous, de votre expérience en programmation et de quels sujets vous souhaitez traiter. Nous partirons de là!" more_about_scribe: "En apprendre plus sur comment devenir un Scribe assidu" scribe_subscribe_desc: "Recevoir un email sur les annonces d'écriture d'article." # diplomat_summary: "There is a large interest in CodeCombat in other countries that do not speak English! We are looking for translators who are willing to spend their time translating the site's corpus of words so that CodeCombat is accessible across the world as soon as possible. If you'd like to help getting CodeCombat international, then this class is for you." diplomat_introduction_pref: "Si nous avons appris quelque chose du " diplomat_launch_url: "lancement en octobre" diplomat_introduction_suf: "c'est qu'il y a un intérêt considérable pour CodeCombat dans d'autres pays, particulièrement au Brésil! Nous créons une équipe de traducteurs pour changer une liste de mots en une autre pour que CodeCombat soit le plus accessible possible à travers le monde. Si vous souhaitez avoir un aperçu des prochains contenus et avoir les niveaux dans votre langue le plus tôt possible, alors cette classe est faite pour vous." diplomat_attribute_1: "Des facilités en anglais et dans la langue que vous souhaitez traduire. Pour transmettre des idées complexes, il est important d'avoir une solide compréhension des deux!" diplomat_join_pref_github: "Trouvez le fichier de langue souhaité" diplomat_github_url: "sur GitHub" # diplomat_join_suf_github: ", edit it online, and submit a pull request. Also, check this box below to keep up-to-date on new internationalization developments!" more_about_diplomat: "En apprendre plus sur comment devenir un bon diplomate" diplomat_subscribe_desc: "Recevoir un email sur le développement i18n et les niveaux à traduire." # ambassador_summary: "We are trying to build a community, and every community needs a support team when there are troubles. We have got chats, emails, and social networks so that our users can get acquainted with the game. If you want to help people get involved, have fun, and learn some programming, then this class is for you." ambassador_introduction: "C'est la communauté que nous construisons, et vous en êtes les connexions. Nous avons des discussions via le chat <NAME>, emails et les réseaux sociaux avec plusieurs personnes, et l'aide vient à la fois du jeu lui-même et grâce à lui. Si vous voulez aider les gens, prendre part à l'aventure et vous amuser, avec un bon feeling de CodeCombat et ce vers quoi nous allons, alors cette classe est faite pour vous." ambassador_attribute_1: "Compétences en communication. Être capable d'identifier les problèmes que les joueurs ont et les aider à les résoudre. Mais aussi nous tenir informés de ce que les joueurs disent, ce qu'ils aiment et n'aiment pas et d'autres choses de ce genre!" ambassador_join_desc: "parlez-nous un peu de vous, de ce que vous avez fait et ce qui vous aimeriez faire. Nous partirons de ça!" ambassador_join_note_strong: "Note" ambassador_join_note_desc: "Une de nos priorités est de développer un jeu multijoueur où les joueurs qui ont du mal à réussir un niveau peuvent demander de l'aide à un joueur de plus haut niveau. Ce sera un bon moyen pour que les ambassadeurs fassent leur travail. Nous vous garderons en ligne!" more_about_ambassador: "En apprendre plus sur comment devenir un serviable Ambassadeur" ambassador_subscribe_desc: "Recevoir un email sur les mises à jour de l'aide et les développements multijoueur." # counselor_summary: "None of the above roles fit what you are interested in? Do not worry, we are on the lookout for anybody who wants a hand in the development of CodeCombat! If you are interested in teaching, game development, open source management, or anything else that you think will be relevant to us, then this class is for you." counselor_introduction_1: "Avez-vous de l'expérience dans la vie? Ou toute autre expérience qui peut nous aider à décider comment diriger CodeCombat? De tous ces rôles, ce sera probablement celui qui prend le moins de temps, mais vous ferez la différence. Nous recherchons des sages, particulièrement dans les domaines de : l'apprentissage, le développement de jeux, la gestion de projets open source, le recrutement technique, l'entreprenariat, ou la conception." counselor_introduction_2: "Ou vraiment toutes choses en rapport avec le développement de CodeCombat. Si vous avez des connaissances et que vous voulez les partager pour aider le projet à avancer, alors cette classe est faite pour vous." counselor_attribute_1: "De l'expérience, dans un des domaines ci-dessus ou quelque chose que vous pensez être utile." counselor_attribute_2: "Un peu de temps libre!" counselor_join_desc: "parlez-nous un peu de vous, de ce que vous avez fait et ce que vous aimeriez faire. Nous vous mettrons dans notre liste de contacts et ferons appel à vous quand nous aurons besoin de conseils (pas trop souvent)." more_about_counselor: "En apprendre plus sur devenir un précieux Conseiller" changes_auto_save: "Les changements sont sauvegardés automatiquement quand vous changez l'état des cases à cocher." diligent_scribes: "Nos Scribes assidus :" powerful_archmages: "Nos puissants Archimages :" creative_artisans: "Nos Artisans créatifs :" brave_adventurers: "Nos braves Aventuriers :" translating_diplomats: "Nos Diplomates traducteurs :" helpful_ambassadors: "Nos serviables Ambassadeurs :" classes: archmage_title: "Archimage" archmage_title_description: "(Développeur)" artisan_title: "Artisan" artisan_title_description: "(Créateur de niveau)" adventurer_title: "Aventurier" adventurer_title_description: "(Testeur de niveau)" scribe_title: "Scribe" scribe_title_description: "(Rédacteur d'articles)" diplomat_title: "Diplomate" diplomat_title_description: "(Traducteur)" ambassador_title: "Ambassadeur" ambassador_title_description: "(Aide)" counselor_title: "Conseiller" counselor_title_description: "(Expert/Professeur)" ladder: please_login: "Identifie toi avant de jouer à un ladder game." my_matches: "Mes Matchs" simulate: "Simuler" simulation_explanation: "En simulant une partie, tu peux classer ton rang plus rapidement!" simulate_games: "Simuler une Partie!" simulate_all: "REINITIALISER ET SIMULER DES PARTIES" games_simulated_by: "Parties que vous avez simulé :" games_simulated_for: "parties simulées pour vous :" games_simulated: "Partie simulée" games_played: "Parties jouées" ratio: "Moyenne" leaderboard: "Classement" battle_as: "Combattre comme " summary_your: "Vos " summary_matches: "Matchs - " summary_wins: " Victoires, " summary_losses: " Défaites" rank_no_code: "Nouveau Code à Classer" rank_my_game: "Classer ma Partie!" rank_submitting: "Soumission en cours..." rank_submitted: "Soumis pour le Classement" rank_failed: "Erreur lors du Classement" rank_being_ranked: "Partie en cours de Classement" rank_last_submitted: "Envoyé " help_simulate: "De l'aide pour simuler vos parties" code_being_simulated: "Votre nouveau code est en cours de simulation par les autres joueurs pour le classement. Cela va se rafraichir lors que d'autres matchs auront lieu." no_ranked_matches_pre: "Pas de match classé pour l'équipe " no_ranked_matches_post: "! Affronte d'autres compétiteurs et reviens ici pour classer ta partie." choose_opponent: "Choisir un Adversaire" # select_your_language: "Select your language!" tutorial_play: "Jouer au Tutoriel" tutorial_recommended: "Recommendé si tu n'as jamais joué avant" tutorial_skip: "Passer le Tutoriel" tutorial_not_sure: "Pas sûr de ce qu'il se passe?" tutorial_play_first: "Jouer au Tutoriel d'abord." simple_ai: "IA simple" warmup: "Préchauff<NAME>" vs: "VS" # friends_playing: "Friends Playing" log_in_for_friends: "Connectez vous pour jouer avec vos amis!" social_connect_blurb: "Connectez vous pour jouer contre vos amis!" # invite_friends_to_battle: "Invite your friends to join you in battle!" fight: "Combattez !" watch_victory: "Regardez votre victoire" # defeat_the: "Defeat the" tournament_ends: "Fin du tournoi" # tournament_ended: "Tournament ended" tournament_rules: "Règles du tournoi" # tournament_blurb: "Write code, collect gold, build armies, crush foes, win prizes, and upgrade your career in our $40,000 Greed tournament! Check out the details" tournament_blurb_blog: "Sur notre blog" # rules: "Rules" # winners: "Winners" ladder_prizes: title: "Prix du tournoi" # blurb_1: "These prizes will be awarded according to" blurb_2: "Régles du tournoi" # blurb_3: "to the top human and ogre players." # blurb_4: "Two teams means double the prizes!" # blurb_5: "(There will be two first place winners, two second-place winners, etc.)" rank: "Rang" prizes: "Prix" total_value: "Valeur totale" # in_cash: "in cash" # custom_wizard: "Custom CodeCombat Wizard" # custom_avatar: "Custom CodeCombat avatar" # heap: "for six months of \"Startup\" access" credits: "Crédits" # one_month_coupon: "coupon: choose either Rails or HTML" # one_month_discount: "discount, 30% off: choose either Rails or HTML" license: "Licence" # oreilly: "ebook of your choice" multiplayer_launch: # introducing_dungeon_arena: "Introducing Dungeon Arena" # new_way: "The new way to compete with code." # to_battle: "To Battle, Developers!" # modern_day_sorcerer: "You know how to code? That's badass. You're a modern-day sorcerer! Isn't about time that you used your magic coding powers to command your minions in epic combat? And we're not talking robots here." # arenas_are_here: "CodeCombat head-to-head multiplayer arenas are here." # ladder_explanation: "Choose your heroes, enchant your human or ogre armies, and climb your way over defeated fellow Wizards to reach the top of the ladders–then challenge your friends in our glorious, asynchronous multiplayer coding arenas. If you're feeling creative, you can even" # fork_our_arenas: "fork our arenas" create_worlds: "et créez votre monde" javascript_rusty: "JavaScript un peu rouillé? Pas de souci; il y a un" tutorial: "Tutoriel" new_to_programming: ". Débutant en programmation? Essaie la campagne débutant pour progresser." so_ready: "Je Suis Prêt Pour Ca" loading_error: could_not_load: "Erreur de chargement du serveur" connection_failure: "La connexion a échouée." unauthorized: "Vous devez être identifiée pour faire cela. Avez-vous désactivé les cookies ?" forbidden: "Vous n'avez pas la permission." not_found: "Introuvable." not_allowed: "Méthode non autorisée." timeout: "Connexion au serveur écoulée." conflict: "Conflit de Ressources." bad_input: "Données incorrectes ." server_error: "Erreur serveur." unknown: "Erreur inconnue." resources: your_sessions: "vos Sessions" level: "Niveau" # social_network_apis: "Social Network APIs" facebook_status: "Statut Facebook" facebook_friends: "Amis Facebook" # facebook_friend_sessions: "Facebook Friend Sessions" # gplus_friends: "G+ Friends" # gplus_friend_sessions: "G+ Friend Sessions" leaderboard: "Classement" # user_schema: "User Schema" # user_profile: "User Profile" patches: "Patchs" # patched_model: "Source Document" # model: "Model" system: "Système" # component: "Component" # components: "Components" # thang: "Thang" # thangs: "Thangs" # level_session: "Your Session" # opponent_session: "Opponent Session" article: "Article" user_names: "<NAME>'<NAME>" # thang_names: "Thang Names" files: "Fichiers" top_simulators: "Top Simulateurs" source_document: "Document Source" document: "Document" # sprite_sheet: "Sprite Sheet" # candidate_sessions: "Candidate Sessions" # user_remark: "User Remark" # versions: "Versions" delta: added: "Ajouté" modified: "Modifié" deleted: "Supprimé" moved_index: "Index changé" text_diff: "Différence de texte" merge_conflict_with: "Fusionner les conflits avec" no_changes: "Aucuns Changements"
true
module.exports = nativeDescription: "français", englishDescription: "French", translation: common: loading: "Chargement..." saving: "Sauvegarde..." sending: "Envoi..." send: "Envoyer" cancel: "Annuler" save: "Sauvegarder" publish: "Publier" create: "Creer" delay_1_sec: "1 seconde" delay_3_sec: "3 secondes" delay_5_sec: "5 secondes" manual: "Manuel" fork: "Fork" play: "Jouer" retry: "Reessayer" watch: "Regarder" unwatch: "Ne plus regarder" submit_patch: "Soumettre un correctif" units: second: "seconde" seconds: "secondes" minute: "minute" minutes: "minutes" hour: "heure" hours: "heures" day: "jour" days: "jours" week: "semaine" weeks: "semaines" month: "mois" months: "mois" year: "année" years: "années" modal: close: "Fermer" okay: "Ok" not_found: page_not_found: "Page non trouvée" nav: play: "Jouer" community: "Communauté" editor: "ÉPI:NAME:<NAME>END_PI" blog: "Blog" forum: "Forum" account: "Compte" admin: "Admin" home: "Accueil" contribute: "Contribuer" legal: "Mentions légales" about: "À propos" contact: "Contact" twitter_follow: "Suivre" employers: "Employeurs" versions: save_version_title: "Enregistrer une nouvelle version" new_major_version: "Nouvelle version majeure" cla_prefix: "Pour enregistrer vos modifications vous devez d'abord accepter notre" cla_url: "Copyright" cla_suffix: "." cla_agree: "J'accepte" login: sign_up: "Créer un compte" log_in: "Connexion" logging_in: "Connecter" log_out: "Déconnexion" recover: "Récupérer son compte" recover: recover_account_title: "Récupérer son compte" send_password: "PI:PASSWORD:<PASSWORD>END_PI" signup: create_account_title: "Créer un compte pour sauvegarder votre progression" description: "C'est gratuit. Simplement quelques informations et vous pourrez commencer :" email_announcements: "Recevoir les annonces par email" coppa: "13+ ou hors É-U" coppa_why: "(Pourquoi?)" creating: "Création du compte en cours..." sign_up: "S'abonner" log_in: "se connecter avec votre mot de passe" social_signup: "Ou, vous pouvez vous identifier avec Facecook ou G+:" required: "Vous devez être connecté pour voir cela" home: slogan: "Apprenez à coder tout en jouant" no_ie: "CodeCombat ne fonctionnera pas sous Internet Explorer 9 ou moins. Désolé !" no_mobile: "CodeCombat n'a pas été créé pour les plateformes mobiles donc il est possible qu'il ne fonctionne pas correctement ! " play: "Jouer" old_browser: "Oh oh, votre navigateur est trop vieux pour executer CodeCombat. Désolé!" old_browser_suffix: "Vous pouvez essayer quand même, mais celà ne marchera probablement pas." campaign: "Campagne" for_beginners: "Pour débutants" multiplayer: "Multijoueurs" for_developers: "Pour développeurs" play: choose_your_level: "Choisissez votre niveau" adventurer_prefix: "Vous pouvez passer à n'importe quel niveau ci-dessous, ou discuter des niveaux sur " adventurer_forum: "le forum de l'Aventurier" adventurer_suffix: "." campaign_beginner: "Campagne du Débutant" campaign_beginner_description: "... dans laquelle vous apprendrez la magie de la programmation." campaign_dev: "Niveaux aléatoires plus difficiles" campaign_dev_description: "... dans lesquels vous apprendrez à utiliser l'interface en faisant quelque chose d'un petit peu plus dur." campaign_multiplayer: "Campagne multi-joueurs" campaign_multiplayer_description: "... dans laquelle vous coderez en face à face contre d'autres joueurs." campaign_player_created: "Niveaux créés par les joueurs" campaign_player_created_description: "... Dans laquelle vous serez confrontés à la créativité des votres.<a href=\"/contribute#artisan\">Artisan Wizards</a>." level_difficulty: "Difficulté: " play_as: "Jouer comme " spectate: "Spectateur" contact: contact_us: "Contacter CodeCombat" welcome: "PI:NAME:<NAME>END_PI de vos nouvelles! Utilisez ce formulaire pour nous envoyer un mail." contribute_prefix: "Si vous voulez contribuer, consultez notre " contribute_page: "page de contributions" contribute_suffix: "!" forum_prefix: "Pour tout sujet d'ordre publique, merci d'utiliser " forum_page: "notre forum" forum_suffix: " À la place." send: "Envoyer un commentaire" contact_candidate: "Contacter le candidat" recruitment_reminder: "Utilisez ce formulaire pour entrer en contact avec le candidat qui vous interesse. Souvenez-vous que CodeCombat facture 15% de la première année de salaire. Ces frais sont dues à l'embauche de l'employé, ils sont remboursable pendant 90 jours si l'employé ne reste pas employé. Les employés à temps partiel, à distance ou contractuel sont gratuits en tant que stagiaires." diplomat_suggestion: title: "Aidez à traduire CodeCombat!" sub_heading: "Nous avons besoin de vos compétences en langues." pitch_body: "Nous développons CodeCombat en Anglais, mais nous avons déjà des joueurs de partout dans le monde. Beaucoup d'entre eux veulent jouer en Français mais ne parlent pas l'anglais, donc si vous parlez aussi bien l'anglais que le français, aidez-nous en devenant traducteur et aidez à traduire aussi bien le site que tous les niveaux en français." missing_translations: "Jusqu'à ce que nous ayons tout traduit en français, vous verrez de l'anglais quand le français ne sera pas disponible." learn_more: "Apprenez en plus sur les Traducteurs" subscribe_as_diplomat: "S'inscrire en tant que traducteur" wizard_settings: title: "Paramètres du Magicien" customize_avatar: "Personnaliser votre avatar" active: "Actif" color: "Couleur" group: "Groupe" clothes: "Vêtements" trim: "Tailleur" cloud: "Nuage" team: "Equipe" spell: "Sort" boots: "Bottes" hue: "Teinte" saturation: "Saturation" lightness: "Luminosité" account_settings: title: "Préférences du compte" not_logged_in: "Connectez-vous ou créez un compte pour modifier vos préférences." autosave: "Enregistrer automatiquement les modifications" me_tab: "Moi" picture_tab: "Photos" upload_picture: "Héberger une image" wizard_tab: "Magicien" password_tab: "Mot de passe" emails_tab: "Emails" admin: "Admin" wizard_color: "Couleur des vêtements du Magicien" new_password: "PI:PASSWORD:<PASSWORD>END_PI passe" new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI" email_subscriptions: "Abonnements" email_announcements: "Annonces" email_announcements_description: "Recevoir des mails sur les dernières actualités et sur le développement de CodeCombat." email_notifications: "Notifications" email_notifications_summary: "Commandes pour personaliser les notifications automatiques d'email liées à votre activité sur CodeCombat." email_any_notes: "Toutes Notifications" email_any_notes_description: "Désactivez pour ne plus recevoir de notifications par e-mail." email_recruit_notes: "Offres d'emploi" email_recruit_notes_description: "Si vous jouez vraiment bien, nous pouvons vous contacter pour vous proposer un (meilleur) emploi." contributor_emails: "Emails des contributeurs" contribute_prefix: "Nous recherchons des personnes pour se joindre à notre groupe! Consultez la " contribute_page: "page de contributions" contribute_suffix: " pour en savoir plus." email_toggle: "Tout basculer" error_saving: "Problème d'enregistrement" saved: "Changements sauvegardés" password_mismatch: "Le mot de passe ne correspond pas." job_profile: "Profil d'emploi" job_profile_approved: "Votre profil d'emploi a été approuvé par CodeCombat. Les employeurs seront en mesure de voir votre profil jusqu'à ce que vous le marquez inactif ou qu'il n'a pas été changé pendant quatre semaines." job_profile_explanation: "Salut! Remplissez-le et nous prendrons contact pour vous trouver un emploi de développeur de logiciels." sample_profile: "Voir un exemple de profil" view_profile: "Voir votre profil" account_profile: settings: "Paramètres" edit_profile: "Editer Profil" done_editing: "Modifications effectué" profile_for_prefix: "Profil pour " profile_for_suffix: "" featured: "Complet" not_featured: "Incomplet" looking_for: "à la recherche de:" last_updated: "Dernière Mise à jour:" contact: "Contact" active: "En recherche d'offres" inactive: "Ne recherche pas d'offres" complete: "terminé" next: "Suivant" next_city: "ville ?" next_country: "choisissez votre pays." next_name: "nom ?" next_short_description: "résumez votre profil en quelques mots." next_long_description: "décrivez le travail que vous cherchez." next_skills: "listez au moins 5 compétances." next_work: "décrivez votre expérience professionnelle." next_education: "raconter votre scolarité." next_projects: "décrivez jusqu'à 3 projets sur lesquels vous avez travaillé." next_links: "ajouter des liens internet vers des sites personnels ou des réseaux sociaux." next_photo: "ajouter une photo professionelle (optionnel)." next_active: "déclarez vous ouvert aux offres pour apparaitre dans les recherches." example_blog: "Votre blog" example_personal_site: "Site Web" links_header: "Liens personnels" links_blurb: "Lien vers d'autres sites ou profils que vous souhaitez mettre en avant, comme votre GitHub, LinkedIn ou votre blog." links_name: "Nom du lien" links_name_help: "A quoi êtes vous lié ?" links_link_blurb: "Lien URL" basics_header: "Mettre à jour les information basiques" basics_active: "Ouvert aux propositions" basics_active_help: "Voulez-vous des offres maintenant ?" basics_job_title: "Titre du poste souhaité" basics_job_title_help: "Quel est le rôle que vous cherchez ?" basics_city: "Ville" basics_city_help: "Ville dans laquelle vous souhaitez travailler (ou dans laquelle vous vivez actuellement)." basics_country: "Pays" basics_country_help: "Pays dans lequel vous souhaitez travailler (ou dans lequel vous vivez actuellement)." basics_visa: "Statut de travail aux Etats-Unis" basics_visa_help: "Etes vous autorisé à travailler aux Etats-Unis ou avez vous besoin d'un parrainage pour le visa ?" basics_looking_for: "Recherche" basics_looking_for_full_time: "Temps plein" basics_looking_for_part_time: "Temps partiel" basics_looking_for_remote: "A distance" basics_looking_for_contracting: "Contrat" basics_looking_for_internship: "Stage" basics_looking_for_help: "Quel genre de poste de développeur voulez-vous ?" name_header: "Remplissez votre nom" name_anonymous: "PI:NAME:<NAME>END_PI" name_help: "Le nom que vous souhaitez que l'employeur voie, par exemple 'PI:NAME:<NAME>END_PI'." short_description_header: "Décrivez vous en quelques mots" short_description_blurb: "Ajoutez une phrase d'accroche pour permettre à un employeur d'en savoir plus sur vous." short_description: "Description courte" short_description_help: "Qui êtes vous et que recherchez vous ? 140 caractères max." skills_header: "Compétences" skills_help: "Notez vos compétence de développement par ordre de maitrise." long_description_header: "Détaillez votre poste souhaité" long_description_blurb: "Faites savoir aux employeurs combien vous êtes génial et quel poste vous voulez." long_description: "Biographie" long_description_help: "Décrivez-vous aux potentiels employeurs. Soyez bref et direct. Nous vous recommandons de bien indiquer quel poste vous intéresse le plus. 600 caractères max." work_experience: "Experience de travail" work_header: "Présentez votre parcours professionnel" work_years: "Années d'expérience" work_years_help: "Combien d'années d'expérience professionnelle (salarié) avez-vous dans le développement logiciel ?" work_blurb: "Lister vos missions les plus pertinentes, les plus récentes en premier." work_employer: "Employeur" work_employer_help: "Nom de votre employeur." work_role: "Titre du poste" work_role_help: "Quel était l'intitulé de votre mission ou votre poste ?" work_duration: "Durée" # work_duration_help: "When did you hold this gig?" work_description: "Description" work_description_help: "Qu'est-ce que vous y avez fait ? (140 carac.; optionel)" education: "Education" education_header: "Racontez vos exploits scolaires" education_blurb: "Lister vos exploits scolaires." education_school: "Etablissement" education_school_help: "Nom de l'établissement." education_degree: "Diplôme" education_degree_help: "Quel était votre diplôme et votre domaine d'étude ?" education_duration: "Dates" education_duration_help: "Quand ?" education_description: "Description" education_description_help: "Mettez en avant ce que vous voulez à propos de votre parcours scolaire. (140 carac.; optionel)" our_notes: "Notes" # remarks: "Remarks" projects: "Projets" projects_header: "Ajoutez 3 projets" projects_header_2: "Projets (Top 3)" projects_blurb: "Mettez en avant vos projets pour épater les employeurs." project_name: "Nom du projet" project_name_help: "Comment avez-vous appelé votre projet ?" project_description: "Description" project_description_help: "Décrivez brièvement le projet." project_picture: "Image" project_picture_help: "Chargez une image de 230x115px oou plus grande pour présenter votre projet." project_link: "Lien" project_link_help: "Lien vers le projet." # player_code: "Player Code" employers: # hire_developers_not_credentials: "Hire developers, not credentials." # get_started: "Get Started" # already_screened: "We've already technically screened all our candidates" # filter_further: ", but you can also filter further:" # filter_visa: "Visa" # filter_visa_yes: "US Authorized" # filter_visa_no: "Not Authorized" # filter_education_top: "Top School" # filter_education_other: "Other" # filter_role_web_developer: "Web Developer" # filter_role_software_developer: "Software Developer" # filter_role_mobile_developer: "Mobile Developer" # filter_experience: "Experience" # filter_experience_senior: "Senior" # filter_experience_junior: "Junior" # filter_experience_recent_grad: "Recent Grad" # filter_experience_student: "College Student" # filter_results: "results" # start_hiring: "Start hiring." # reasons: "Three reasons you should hire through us:" # everyone_looking: "Everyone here is looking for their next opportunity." # everyone_looking_blurb: "Forget about 20% LinkedIn InMail response rates. Everyone that we list on this site wants to find their next position and will respond to your request for an introduction." # weeding: "Sit back; we've done the weeding for you." # weeding_blurb: "Every player that we list has been screened for technical ability. We also perform phone screens for select candidates and make notes on their profiles to save you time." # pass_screen: "They will pass your technical screen." # pass_screen_blurb: "Review each candidate's code before reaching out. One employer found that 5x as many of our devs passed their technical screen than hiring from Hacker News." # make_hiring_easier: "Make my hiring easier, please." what: "Qu'est-ce que CodeCombat?" what_blurb: "CodeCombat est un jeu de programmation multijoueur par navigateur. Les Joueurs écrivent le code pour contrôler leurs troupes dans des batailles contre d'autres développeurs. Nous prenons en charge JavaScript, Python, Lua, Clojure, CoffeeScript, et Io." # cost: "How much do we charge?" # cost_blurb: "We charge 15% of first year's salary and offer a 100% money back guarantee for 90 days. We don't charge for candidates who are already actively being interviewed at your company." candidate_name: "PI:NAME:<NAME>END_PI" candidate_location: "Localisation" candidate_looking_for: "Poste pour" candidate_role: "Rôle" candidate_top_skills: "Talents/Aptitudes" candidate_years_experience: "Années d'expérience" candidate_last_updated: "Dernière mise à jour" # candidate_who: "Who" # featured_developers: "Featured Developers" # other_developers: "Other Developers" # inactive_developers: "Inactive Developers" play_level: done: "Fait" grid: "Grille" customize_wizard: "Personnaliser le magicien" home: "Accueil" guide: "Guide" multiplayer: "Multijoueur" restart: "Relancer" goals: "Objectifs" success: "Succès" incomplete: "Imcoplet" timed_out: "Plus de temps" failing: "Echec" action_timeline: "Action sur la ligne de temps" click_to_select: "Clique sur une unité pour la sélectionner." reload_title: "Recharger tout le code?" reload_really: "Êtes-vous sûr de vouloir recharger ce niveau et retourner au début?" reload_confirm: "Tout recharger" victory_title_prefix: "" victory_title_suffix: " Terminé" victory_sign_up: "Inscrivez-vous pour recevoir les mises à jour" victory_sign_up_poke: "Vous voulez recevoir les dernières actualités par mail? Créez un compte gratuitement et nous vous tiendrons informés!" victory_rate_the_level: "Notez ce niveau: " # victory_return_to_ladder: "Return to Ladder" victory_play_next_level: "Jouer au prochain niveau" victory_go_home: "Retourner à l'accueil" victory_review: "Dites-nous en plus!" victory_hour_of_code_done: "Déjà fini ?" victory_hour_of_code_done_yes: "Oui, j'ai fini mon heure de code!" multiplayer_title: "Préférences multijoueurs" multiplayer_link_description: "Partage ce lien pour que tes amis viennent jouer avec toi." multiplayer_hint_label: "Astuce:" multiplayer_hint: " Cliquez sur le lien pour tout sélectionner, puis appuyer sur Pomme-C ou Ctrl-C pour copier le lien." multiplayer_coming_soon: "Plus de fonctionnalités multijoueurs sont à venir" # multiplayer_sign_in_leaderboard: "Sign in or create an account and get your solution on the leaderboard." guide_title: "Guide" tome_minion_spells: "Les sorts de vos soldats" tome_read_only_spells: "Sorts en lecture-seule" tome_other_units: "Autres unités" tome_cast_button_castable: "Jeter le sort" tome_cast_button_casting: "Sort en court" tome_cast_button_cast: "Sort jeté" tome_autocast_delay: "Temps de recharge" tome_select_spell: "Choisissez un sort" tome_select_a_thang: "Sélectionnez une unité pour" tome_available_spells: "Sorts diponibles" hud_continue: "Continuer (appuie sur shift ou espace)" spell_saved: "Sort enregistré" skip_tutorial: "Passer (esc)" editor_config: "Config de l'éditeur" editor_config_title: "Configuration de l'éditeur" editor_config_level_language_label: "Langage pour le niveau" # editor_config_level_language_description: "Define the programming language for this particular level." editor_config_default_language_label: "Langage de Programmation par défaut" editor_config_default_language_description: "Choississez le langage de programmation que vous souhaitez dons les nouveaux niveaux" editor_config_keybindings_label: "Raccourcis clavier" editor_config_keybindings_default: "Par défault (Ace)" editor_config_keybindings_description: "Ajouter de nouveaux raccourcis connus depuis l'éditeur commun." # editor_config_livecompletion_label: "Live Autocompletion" # editor_config_livecompletion_description: "Displays autocomplete suggestions while typing." editor_config_invisibles_label: "Afficher les caractères non-imprimables" editor_config_invisibles_description: "Permet d'afficher les caractères comme les espaces et les tabulations." editor_config_indentguides_label: "Montrer les indentations" editor_config_indentguides_description: "Affiche des guides verticaux qui permettent de visualiser l'indentation." editor_config_behaviors_label: "Auto-complétion" editor_config_behaviors_description: "Ferme automatiquement les accolades, parenthèses, et chaînes de caractères." keyboard_shortcuts: "Raccourcis Clavier" loading_ready: "Pret!" tip_insert_positions: "Maj+Clic un point pour insérer les coordonnées dans l'éditeur ." tip_toggle_play: "Jouer/Pause avec Ctrl+P." # tip_scrub_shortcut: "Ctrl+[ and Ctrl+] rewind and fast-forward." # tip_guide_exists: "Click the guide at the top of the page for useful info." tip_open_source: "CodeCombat est 100% open source!" tip_beta_launch: "La beta de CodeCombat a été lancée en Octobre 2013" tip_js_beginning: "JavaScript n'est que le commencement." # tip_autocast_setting: "Adjust autocast settings by clicking the gear on the cast button." think_solution: "Reflechissez a propos de la solution et non du problème." tip_theory_practice: "En théorie, il n'y a pas de différence entre la théorie et la pratique. Mais en pratique il y en a. - PI:NAME:<NAME>END_PI" # tip_error_free: "There are two ways to write error-free programs; only the third one works. - PI:NAME:<NAME>END_PI" tip_debugging_program: "Si débugger est l'art de corriger les bugs, alors programmer est l'art d'en créer. . - PI:NAME:<NAME>END_PI" # tip_forums: "Head over to the forums and tell us what you think!" tip_baby_coders: "Dans le futur, même les bébés seront des archimages." # tip_morale_improves: "Loading will continue until morale improves." # tip_all_species: "We believe in equal opportunities to learn programming for all species." # tip_reticulating: "Reticulating spines." # tip_harry: "Yer a Wizard, " # tip_great_responsibility: "With great coding skill comes great debug responsibility." # tip_munchkin: "If you don't eat your vegetables, a munchkin will come after you while you're asleep." # tip_binary: "There are only 10 types of people in the world: those who understand binary, and those who don't." # tip_commitment_yoda: "A programmer must have the deepest commitment, the most serious mind. ~ Yoda" # tip_no_try: "Do. Or do not. There is no try. - Yoda" # tip_patience: "Patience you must have, young Padawan. - Yoda" # tip_documented_bug: "A documented bug is not a bug; it is a feature." # tip_impossible: "It always seems impossible until it's done. - PI:NAME:<NAME>END_PI" # tip_talk_is_cheap: "Talk is cheap. Show me the code. - PI:NAME:<NAME>END_PI" # tip_first_language: "The most disastrous thing that you can ever learn is your first programming language. - PI:NAME:<NAME>END_PI" # tip_hardware_problem: "Q: How many programmers does it take to change a light bulb? A: None, it's a hardware problem." time_current: "Maintenant:" time_total: "Max:" time_goto: "Allez a:" infinite_loop_try_again: "Reessayer" infinite_loop_reset_level: "Redemarrer le niveau" infinite_loop_comment_out: "Supprimez les commentaire de mon code" keyboard_shortcuts: keyboard_shortcuts: "PI:NAME:<NAME>END_PI" space: "Espace" enter: "Entrer" escape: "Echap" # cast_spell: "Cast current spell." # continue_script: "Continue past current script." # skip_scripts: "Skip past all skippable scripts." # toggle_playback: "Toggle play/pause." # scrub_playback: "Scrub back and forward through time." # single_scrub_playback: "Scrub back and forward through time by a single frame." # scrub_execution: "Scrub through current spell execution." # toggle_debug: "Toggle debug display." # toggle_grid: "Toggle grid overlay." # toggle_pathfinding: "Toggle pathfinding overlay." # beautify: "Beautify your code by standardizing its formatting." # move_wizard: "Move your Wizard around the level." admin: av_title: "Vues d'administrateurs" av_entities_sub_title: "Entités" av_entities_users_url: "Utilisateurs" av_entities_active_instances_url: "Instances actives" av_entities_employer_list_url: "Liste des employés" av_other_sub_title: "Autre" av_other_debug_base_url: "Base (pour debugger base.jade)" u_title: "Liste des utilisateurs" lg_title: "Dernières parties" clas: "CLAs" community: level_editor: "Editeur de niveau" main_title: "Communauté CodeCombat" facebook: "Facebook" twitter: "Twitter" gplus: "Google+" editor: main_title: "Éditeurs CodeCombat" main_description: "Créé tes propres niveaux, campagnes, unités et contenus éducatifs. Nous vous fournissons tous les outils dont vous avez besoin!" article_title: "Éditeur d'article" article_description: "Écris des articles qui donnent aux joueurs un aperçu des concepts de programmation qui peuvent être utilisés dans différents niveaux et campagnes." thang_title: "Éditeur Thang" thang_description: "Créé des unités, définis leur comportement de base, graphisme et son. Pour l'instant cette fonctionnalité ne supporte que l'importation d'images vectorielles exportées depuis Flash." level_title: "Éditeur de niveau" level_description: "Inclut les outils de script, l'upload de vidéos, et l'élaboration de logiques personnalisées pour créer toutes sortes de niveaux. Tout ce que nous utilisons nous-mêmes!" # achievement_title: "Achievement Editor" # got_questions: "Questions about using the CodeCombat editors?" contact_us: "contactez nous!" hipchat_prefix: "Vous pouvez aussi nous trouver dans notre " hipchat_url: "conversation HipChat." back: "Retour" revert: "Annuler" revert_models: "Annuler les modèles" # pick_a_terrain: "Pick A Terrain" # small: "Small" # grassy: "Grassy" fork_title: "Fork une nouvelle version" fork_creating: "Créer un Fork..." # randomize: "Randomize" more: "Plus" wiki: "Wiki" live_chat: "Chat en live" level_some_options: "Quelques options?" level_tab_thangs: "Thangs" level_tab_scripts: "Scripts" level_tab_settings: "Paramètres" level_tab_components: "Composants" level_tab_systems: "Systèmes" level_tab_thangs_title: "Thangs actuels" level_tab_thangs_all: "Tout" level_tab_thangs_conditions: "Conditions de départ" level_tab_thangs_add: "ajouter des Thangs" delete: "Supprimer" duplicate: "Dupliquer" level_settings_title: "Paramètres" level_component_tab_title: "Composants actuels" level_component_btn_new: "Créer un nouveau composant" level_systems_tab_title: "Systèmes actuels" level_systems_btn_new: "Créer un nouveau système" level_systems_btn_add: "Ajouter un système" level_components_title: "Retourner à tous les Thangs" level_components_type: "Type" level_component_edit_title: "Éditer le composant" level_component_config_schema: "Configurer le schéma" level_component_settings: "Options" level_system_edit_title: "Éditer le système" create_system_title: "Créer un nouveau système" new_component_title: "Créer un nouveau composant" new_component_field_system: "Système" new_article_title: "Créer un nouvel article" new_thang_title: "Créer un nouveau Type Thang" new_level_title: "Créer un nouveau niveau" new_article_title_login: "Connectez vous pour créer un nouvel article" # new_thang_title_login: "Log In to Create a New Thang Type" new_level_title_login: "Connectez vous pour créer un nouveau niveau" # new_achievement_title: "Create a New Achievement" # new_achievement_title_login: "Log In to Create a New Achievement" article_search_title: "Rechercher dans les articles" thang_search_title: "Rechercher dans les types Thang" level_search_title: "Rechercher dans les niveaux" # achievement_search_title: "Search Achievements" read_only_warning2: "Note: vous ne pouvez sauvegarder aucune édition, car vous n'êtes pas identifié." article: edit_btn_preview: "Prévisualiser" edit_article_title: "Éditer l'article" general: and: "et" name: "Nom" body: "Corps" version: "Version" commit_msg: "Message de mise à jour" version_history: "Historique des versions" version_history_for: "Historique des versions pour : " result: "Resultat" results: "Résultats" description: "Description" or: "ou" subject: "Sujet" email: "Email" password: "PI:PASSWORD:<PASSWORD>END_PI" message: "Message" code: "Code" ladder: "Companion" when: "Quand" opponent: "Adversaire" rank: "Rang" score: "Score" win: "Victoire" loss: "Défaite" tie: "Ex-aequo" easy: "Facile" medium: "Moyen" hard: "Difficile" player: "Joueur" about: who_is_codecombat: "Qui est CodeCombat?" why_codecombat: "Pourquoi CodeCombat?" who_description_prefix: "ont lancé CodeCombat ensemble en 2013. Nous avons aussi créé " who_description_suffix: "en 2008, l'améliorant jusqu'au rang de première application web et iOS pour apprendre à écrire les caractères chinois et japonais." who_description_ending: "Maintenant nous apprenons aux gens à coder." why_paragraph_1: "En développant Skritter, George ne savait pas programmer et était frustré de ne pas pouvoir implémenter ses idées. Ensuite, il essaya d'apprendre, mais les cours n'étaient pas assez rapides. Son colocataire, voulant se requalifier et arrêter d'apprendre, essaya Codecademy, mais \"s'ennuya.\" Chaque semaine un nouvel ami commençait Codecademy, puis abandonnait. Nous nous sommes rendus compte que nous avions résolu le même problème avec Skritter: les gens apprennant grâce à des cours lents et intensifs quand nous avons besoin d'expérience rapide et intensive. Nous savons comment remédier à ça." why_paragraph_2: "Besoin d'apprendre à développer? Vous n'avez pas besoin de cours. Vous avez besoin d'écrire beaucoup de code et de vous amuser en le faisant." why_paragraph_3_prefix: "C'est ce dont il s'agit en programmation. Ça doit être amusant. Pas amusant comme" why_paragraph_3_italic: "Génial un badge" why_paragraph_3_center: "Mais amusant comme" why_paragraph_3_italic_caps: "NAN MAMAN JE DOIS FINIR MON NIVEAU!" why_paragraph_3_suffix: "C'est pourquoi CodeCombat est un jeu multijoueur, pas un cours avec une leçon jouée. Nous n'arrêterons pas avant que vous ne puissiez plus arrêter — mais cette fois, c'est une bonne chose." why_paragraph_4: "Si vous devez devenir accro à un jeu, accrochez-vous à celui-ci et devenez un des mages de l'âge de la technologie." why_ending: "Et oh, c'est gratuit. " why_ending_url: "Commence ton apprentissage maintenant!" george_description: "PDG, homme d'affaire, web designer, game designer, et champion des programmeurs débutants." scott_description: "Programmeur extraordinaire, architecte logiciel, assistant cuisinier, et maitre de la finance. PI:NAME:<NAME>END_PI est le raisonnable." nick_description: "Assistant programmeur, mage à la motivation excentrique, et bidouilleur de l'extrême. PI:NAME:<NAME>END_PI peut faire n'importe quoi mais il a choisi CodeCombat." jeremy_description: "Mage de l'assistance client, testeur de maniabilité, et community manager; vous avez probablement déjà parlé avec PI:NAME:<NAME>END_PI." michael_description: "Programmeur, administrateur réseau, et l'enfant prodige du premier cycle, PI:NAME:<NAME>END_PI est la personne qui maintient nos serveurs en ligne." glen_description: "Programmeur et développeur de jeux passioné, avec la motivation pour faire de ce monde un meilleur endroit, en développant des choses qui comptent. Le mot impossible est introuvable dans son dictionnaire. Apprendre de nouveaux talents est sa joie !" legal: page_title: "Légal" opensource_intro: "CodeCombat est complètement gratuit et open source." opensource_description_prefix: "Regardez " github_url: "notre GitHub" opensource_description_center: "et aidez nous si vous voulez! CodeCombat est construit sur plusieurs projets open source, et nous les aimons. Regardez " archmage_wiki_url: "notre wiki des Archimages" opensource_description_suffix: "pour trouver la liste des logiciels qui rendent ce jeu possible." practices_title: "Bonnes pratiques" practices_description: "Ce sont les promesses que nous vous faisons à vous, le joueur, en jargon un peu juridique." privacy_title: "Vie privée" privacy_description: "Nous ne vendrons aucune de vos informations personnelles. Nous comptons faire de l'argent éventuellement avec le recrutement, mais soyez assuré que nous ne fournirons aucune de vos informations personnelles à des compagnies intéressées sans votre consentement explicite." security_title: "Sécurité" security_description: "Nous faisons tout notre possible pour conserver la confidentialité de vos informations personnelles. En tant que projet open source, notre site est ouvert à tous ceux qui souhaitent examiner et améliorer nos systèmes de sécurité." email_title: "Email" email_description_prefix: "Nous ne vous innonderons pas d'email. Grâce à" email_settings_url: "vos paramètres d'email " email_description_suffix: "ou avec des liens disponibles dans nos emails, vous pouvez changer vos préférences ou vous désinscrire à tout moment." cost_title: "Coût" cost_description: "Pour l'instant, CodeCombat est gratuit à 100%! Un de nos principaux objectifs est que ça le reste, pour qu'autant de gens possible puissent y jouer, indépendamment de leur niveau de vie. Si le ciel s'assombrit, nous devrons peut-être rendre les inscriptions payantes ou une partie du contenu, mais nous ne le souhaitons pas. Avec un peu de chance, nous serons capables de soutenir l'entreprise avec :" recruitment_title: "Recrutement" recruitment_description_prefix: "Ici chez CodeCombat, vous allez devenir un magicien puissant, pas seulement dans le jeu, mais aussi dans la vie réelle." url_hire_programmers: "Personne ne peut recruter des développeurs aussi vite" recruitment_description_suffix: "donc une fois que vous aurez aiguisé votre savoir-faire et si vous l'acceptez, nous montrerons vos meilleurs bouts de code aux milliers d'employeurs qui attendent une chance de vous recruter. Ils nous payent un peu pour ensuite vous payer" recruitment_description_italic: "beaucoup" recruitment_description_ending: "le site reste gratuit et tout le monde est content. C'est le but." copyrights_title: "Copyrights et Licences" contributor_title: "Contributor License Agreement" contributor_description_prefix: "Toute contribution, sur le site et sur le répertoire GitHub, est sujette à nos" cla_url: "CLA" contributor_description_suffix: "auxquelles vous devez vous soumettre avant de contribuer." code_title: "Code - MIT" code_description_prefix: "Tout code siglé CodeCombat ou hébergé sur codecombat.com, sur le répertoire GitHub ou dans la base de données de codecombat.com, est sous la licence" mit_license_url: "MIT" code_description_suffix: "Cela inclut le code dans Systèmes et Composants qui est rendu disponible par CodeCombat dans le but de créer des niveaux." art_title: "Art/Musique - Creative Commons " art_description_prefix: "Tout le contenu commun est sous licence" cc_license_url: "Creative Commons Attribution 4.0 International" art_description_suffix: "Le contenu commun est tout ce qui est rendu disponible par CodeCombat afin de créer des niveaux. Cela inclut :" art_music: "La musique" art_sound: "Le son" art_artwork: "Les artworks" art_sprites: "Les sprites" art_other: "Tout le reste du contenu non-code qui est rendu accessible lors de la création de niveaux." art_access: "Pour l'instant il n'y a aucun système universel et facile pour rassembler ces ressources. En général, accédez y par les URL comme le fait le site, contactez-nous pour de l'aide, ou aidez-nous à agrandir le site pour rendre ces ressources plus facilement accessibles." art_paragraph_1: "Pour l'attribution, s'il vous plait, nommez et référencez codecombat.com près de la source utilisée ou dans un endroit approprié. Par exemple:" use_list_1: "Si utilisé dans un film ou un autre jeu, incluez codecombat.com dans le générique." use_list_2: "Si utilisé sur un site web, incluez un lien près de l'utilisation, par exemple sous une image, ou sur une page d'attribution générale où vous pourrez aussi mentionner les autres travaux en Creative Commons et les logiciels open source utilisés sur votre site. Quelque chose qui fait clairement référence à CodeCombat, comme un article de blog mentionnant CodeCombat, n'a pas besoin d'attribution séparée." art_paragraph_2: "Si le contenu utilisé n'est pas créé par CodeCombat mais par un autre utilisateur de codecombat.com, attribuez le à cet utilisateur, et suivez les recommandations fournies dans la ressource de la description s'il y en a." rights_title: "Droits réservés" rights_desc: "Tous les droits sont réservés pour les niveaux eux-mêmes. Cela inclut" rights_scripts: "Les scripts" rights_unit: "La configuration unitaire" rights_description: "La description" rights_writings: "L'écriture" rights_media: "Les médias (sons, musiques) et tous les autres contenus créatifs créés spécialement pour ce niveau et non rendus généralement accessibles en créant des niveaux." rights_clarification: "Pour clarifier, tout ce qui est rendu accessible dans l'éditeur de niveaux dans le but de créer des niveaux est sous licence CC, tandis que le contenu créé avec l'éditeur de niveaux ou uploadé dans le but de créer un niveau ne l'est pas." nutshell_title: "En un mot" nutshell_description: "Chaque ressource que nous fournissons dans l'éditeur de niveau est libre d'utilisation pour créer des niveaux. Mais nous nous réservons le droit de restreindre la distribution des niveaux créés (qui sont créés sur codecombat.com) ils peuvent donc devenir payants dans le futur, si c'est ce qui doit arriver." canonical: "La version de ce document est la version définitive et canonique. En cas d'irrégularité dans les traductions, le document anglais fait foi." contribute: page_title: "Contribution" character_classes_title: "Classes du personnage" introduction_desc_intro: "Nous avons beaucoup d'espoir pour CodeCombat." introduction_desc_pref: "Nous voulons être l'endroit où les développeurs de tous horizons viennent pour apprendre et jouer ensemble, présenter les autres au monde du développement, et refléter le meilleur de la communauté. Nous ne pouvons et ne voulons pas faire ça seuls ; ce qui rend super les projets comme GitHub, Stack Overflow et Linux, est que les gens qui l'utilisent le construisent. Dans ce but, " introduction_desc_github_url: "CodeCombat est totalement open source" introduction_desc_suf: ", et nous avons pour objectif de fournir autant de manières possibles pour que vous participiez et fassiez de ce projet autant le votre que le notre." introduction_desc_ending: "Nous espérons que vous allez joindre notre aventure!" introduction_desc_signature: "- PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI et PI:NAME:<NAME>END_PI" alert_account_message_intro: "Et tiens!" alert_account_message: "Pour souscrire aux e-mails, vous devez être connecté" # archmage_summary: "Interested in working on game graphics, user interface design, database and server organization, multiplayer networking, physics, sound, or game engine performance? Want to help build a game to help other people learn what you are good at? We have a lot to do and if you are an experienced programmer and want to develop for CodeCombat, this class is for you. We would love your help building the best programming game ever." archmage_introduction: "L'une des meilleures parties de la création d'un jeu est qu'il regroupe tant de choses différentes. Graphismes, sons, réseau en temps réel, réseaux sociaux, et bien sur bien d'autres aspects de la programmation, de la gestion bas niveau de base de données, et de l'administration de serveur à l'élaboration d'interfaces utilisateur. Il y a tant à faire, et si vous êtes un programmeur expérimenté avec une aspiration à vraiment plonger dans le fond de CodeCombat, cette classe est faite pour vous. Nous aimerions avoir votre aide pour le meilleur jeu de développement de tous les temps." class_attributes: "Attributs de classe" archmage_attribute_1_pref: "Connaissance en " archmage_attribute_1_suf: ", ou le désir d'apprendre. La plupart de notre code est écrit avec ce langage. Si vous êtes fan de Ruby ou Python, vous vous sentirez chez vous. C'est du JavaScript, mais avec une syntaxe plus sympatique." archmage_attribute_2: "De l'expérience en développement et en initiatives personnelles. Nous vous aiderons à vous orienter, mais nous ne pouvons pas passer plus de temps à vous entrainer." how_to_join: "Comment nous rejoindre" join_desc_1: "N'importe qui peut aider! Vous avez seulement besoin de regarder " join_desc_2: "pour commencer, et cocher la case ci-dessous pour vous marquer comme un archimage courageux et obtenir les dernières nouvelles par email. Envie de discuter de ce qu'il y a à faire ou de comment être plus impliqué? " join_desc_3: ", ou trouvez-nous dans nos " join_desc_4: "et nous partirons de là!" join_url_email: "Contactez nous" join_url_hipchat: "conversation publique HipChat" more_about_archmage: "En apprendre plus sur devenir un puissant archimage" archmage_subscribe_desc: "Recevoir un email sur les nouvelles possibilités de développement et des annonces." # artisan_summary_pref: "Want to design levels and expand CodeCombat's arsenal? People are playing through our content at a pace faster than we can build! Right now, our level editor is barebone, so be wary. Making levels will be a little challenging and buggy. If you have visions of campaigns spanning for-loops to" artisan_summary_suf: ", alors ce travail est pour vous" artisan_introduction_pref: "Nous devons créer des niveaux additionnels! Les gens veulent plus de contenu, et nous ne pouvons pas tous les créer nous-mêmes. Maintenant votre station de travail est au niveau un ; notre éditeur de niveaux est à peine utilisable même par ses créateurs, donc méfiez-vous. Si vous avez des idées sur la boucle for de" artisan_introduction_suf: ", cette classe est faite pour vous." artisan_attribute_1: "Une expérience dans la création de contenu comme celui-ci serait un plus, comme utiliser l'éditeur de niveaux de Blizzard. Mais ce n'est pas nécessaire!" artisan_attribute_2: "Vous aspirez à faire beaucoup de tests et d'itérations. Pour faire de bons niveaux, vous aurez besoin de les proposer aux autres et les regarder les jouer, et être prêt à trouver un grand nombre de choses à corriger." artisan_attribute_3: "Pour l'heure, endurance en binôme avec un Aventurier. Notre éditeur de niveaux est vraiment préliminaire et frustrant à l'utilisation. Vous êtes prévenus!" artisan_join_desc: "Utilisez le créateur de niveaux pour à peu près ces étapes :" artisan_join_step1: "Lire la documentation." artisan_join_step2: "Créé un nouveau niveau et explore les niveaux existants." artisan_join_step3: "Retrouvez nous dans notre conversation HipChat pour obtenir de l'aide." artisan_join_step4: "Postez vos niveaux dans le forum pour avoir des retours." more_about_artisan: "En apprendre plus sur comment devenir un Artisan créatif" artisan_subscribe_desc: "Recevoir un email sur les annonces et mises à jour de l'éditeur de niveaux." # adventurer_summary: "Let us be clear about your role: you are the tank. You are going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class is for you." adventurer_introduction: "Soyons clair à propos de votre rôle : vous êtes le tank. Vous allez subir beaucoup de dommages. Nous avons besoin de gens pour essayer les nouveaux niveaux et aider à identifier comment améliorer les choses. La douleur sera énorme; faire de bons jeux est une longue tâche et personne n'y arrive du premier coup. Si vous pouvez résister et avez un gros score de constitution, alors cette classe est faite pour vous." adventurer_attribute_1: "Une soif d'apprendre. Vous voulez apprendre à développer et nous voulons vous apprendre. Vous allez toutefois faire la plupart de l'apprentissage." adventurer_attribute_2: "Charismatique. Soyez doux mais exprimez-vous sur ce qui a besoin d'être amélioré, et faites des propositions sur comment l'améliorer." adventurer_join_pref: "Soit faire équipe avec (ou recruter!) un artisan et travailler avec lui, ou cocher la case ci-dessous pour recevoir un email quand il y aura de nouveaux niveaux à tester. Nous parlons aussi des niveaux à réviser sur notre réseau" adventurer_forum_url: "notre forum" adventurer_join_suf: "si vous préférez être avertis ainsi, inscrivez-vous ici!" more_about_adventurer: "En apprendre plus sur devenir un brave Aventurier" adventurer_subscribe_desc: "Recevoir un email lorsqu'il y a de nouveaux niveaux à tester." # scribe_summary_pref: "CodeCombat is not just going to be a bunch of levels. It will also be a resource of programming knowledge that players can hook into. That way, each Artisan can link to a detailed article that for the player's edification: documentation akin to what the " # scribe_summary_suf: " has built. If you enjoy explaining programming concepts, then this class is for you." scribe_introduction_pref: "CodeCombat n'est pas seulement un ensemble de niveaux. Il contiendra aussi des ressources pour la connaissance, un wiki des concepts de programmation que les niveaux pourront illustrer. Dans ce but, chaque Artisan pourra, au lieu d'avoir à décrire en détail ce qu'est un opérateur de comparaison, seulement lier son niveau à l'article qui le décrit et qui a été écrit pour aider les joueurs. Quelque chose dans le sens de ce que le " scribe_introduction_url_mozilla: "Mozilla Developer Network" scribe_introduction_suf: " a développé. Si votre définition de l'amusement passe par le format Markdown, alors cette classe est pour vous." scribe_attribute_1: "Les compétences rédactionnelles sont quasiment la seule chose dont vous aurez besoin. Pas seulement la grammaire et l'orthographe, mais être également capable de lier des idées ensembles." contact_us_url: "Contactez-nous" scribe_join_description: "parlez nous un peu de vous, de votre expérience en programmation et de quels sujets vous souhaitez traiter. Nous partirons de là!" more_about_scribe: "En apprendre plus sur comment devenir un Scribe assidu" scribe_subscribe_desc: "Recevoir un email sur les annonces d'écriture d'article." # diplomat_summary: "There is a large interest in CodeCombat in other countries that do not speak English! We are looking for translators who are willing to spend their time translating the site's corpus of words so that CodeCombat is accessible across the world as soon as possible. If you'd like to help getting CodeCombat international, then this class is for you." diplomat_introduction_pref: "Si nous avons appris quelque chose du " diplomat_launch_url: "lancement en octobre" diplomat_introduction_suf: "c'est qu'il y a un intérêt considérable pour CodeCombat dans d'autres pays, particulièrement au Brésil! Nous créons une équipe de traducteurs pour changer une liste de mots en une autre pour que CodeCombat soit le plus accessible possible à travers le monde. Si vous souhaitez avoir un aperçu des prochains contenus et avoir les niveaux dans votre langue le plus tôt possible, alors cette classe est faite pour vous." diplomat_attribute_1: "Des facilités en anglais et dans la langue que vous souhaitez traduire. Pour transmettre des idées complexes, il est important d'avoir une solide compréhension des deux!" diplomat_join_pref_github: "Trouvez le fichier de langue souhaité" diplomat_github_url: "sur GitHub" # diplomat_join_suf_github: ", edit it online, and submit a pull request. Also, check this box below to keep up-to-date on new internationalization developments!" more_about_diplomat: "En apprendre plus sur comment devenir un bon diplomate" diplomat_subscribe_desc: "Recevoir un email sur le développement i18n et les niveaux à traduire." # ambassador_summary: "We are trying to build a community, and every community needs a support team when there are troubles. We have got chats, emails, and social networks so that our users can get acquainted with the game. If you want to help people get involved, have fun, and learn some programming, then this class is for you." ambassador_introduction: "C'est la communauté que nous construisons, et vous en êtes les connexions. Nous avons des discussions via le chat PI:NAME:<NAME>END_PI, emails et les réseaux sociaux avec plusieurs personnes, et l'aide vient à la fois du jeu lui-même et grâce à lui. Si vous voulez aider les gens, prendre part à l'aventure et vous amuser, avec un bon feeling de CodeCombat et ce vers quoi nous allons, alors cette classe est faite pour vous." ambassador_attribute_1: "Compétences en communication. Être capable d'identifier les problèmes que les joueurs ont et les aider à les résoudre. Mais aussi nous tenir informés de ce que les joueurs disent, ce qu'ils aiment et n'aiment pas et d'autres choses de ce genre!" ambassador_join_desc: "parlez-nous un peu de vous, de ce que vous avez fait et ce qui vous aimeriez faire. Nous partirons de ça!" ambassador_join_note_strong: "Note" ambassador_join_note_desc: "Une de nos priorités est de développer un jeu multijoueur où les joueurs qui ont du mal à réussir un niveau peuvent demander de l'aide à un joueur de plus haut niveau. Ce sera un bon moyen pour que les ambassadeurs fassent leur travail. Nous vous garderons en ligne!" more_about_ambassador: "En apprendre plus sur comment devenir un serviable Ambassadeur" ambassador_subscribe_desc: "Recevoir un email sur les mises à jour de l'aide et les développements multijoueur." # counselor_summary: "None of the above roles fit what you are interested in? Do not worry, we are on the lookout for anybody who wants a hand in the development of CodeCombat! If you are interested in teaching, game development, open source management, or anything else that you think will be relevant to us, then this class is for you." counselor_introduction_1: "Avez-vous de l'expérience dans la vie? Ou toute autre expérience qui peut nous aider à décider comment diriger CodeCombat? De tous ces rôles, ce sera probablement celui qui prend le moins de temps, mais vous ferez la différence. Nous recherchons des sages, particulièrement dans les domaines de : l'apprentissage, le développement de jeux, la gestion de projets open source, le recrutement technique, l'entreprenariat, ou la conception." counselor_introduction_2: "Ou vraiment toutes choses en rapport avec le développement de CodeCombat. Si vous avez des connaissances et que vous voulez les partager pour aider le projet à avancer, alors cette classe est faite pour vous." counselor_attribute_1: "De l'expérience, dans un des domaines ci-dessus ou quelque chose que vous pensez être utile." counselor_attribute_2: "Un peu de temps libre!" counselor_join_desc: "parlez-nous un peu de vous, de ce que vous avez fait et ce que vous aimeriez faire. Nous vous mettrons dans notre liste de contacts et ferons appel à vous quand nous aurons besoin de conseils (pas trop souvent)." more_about_counselor: "En apprendre plus sur devenir un précieux Conseiller" changes_auto_save: "Les changements sont sauvegardés automatiquement quand vous changez l'état des cases à cocher." diligent_scribes: "Nos Scribes assidus :" powerful_archmages: "Nos puissants Archimages :" creative_artisans: "Nos Artisans créatifs :" brave_adventurers: "Nos braves Aventuriers :" translating_diplomats: "Nos Diplomates traducteurs :" helpful_ambassadors: "Nos serviables Ambassadeurs :" classes: archmage_title: "Archimage" archmage_title_description: "(Développeur)" artisan_title: "Artisan" artisan_title_description: "(Créateur de niveau)" adventurer_title: "Aventurier" adventurer_title_description: "(Testeur de niveau)" scribe_title: "Scribe" scribe_title_description: "(Rédacteur d'articles)" diplomat_title: "Diplomate" diplomat_title_description: "(Traducteur)" ambassador_title: "Ambassadeur" ambassador_title_description: "(Aide)" counselor_title: "Conseiller" counselor_title_description: "(Expert/Professeur)" ladder: please_login: "Identifie toi avant de jouer à un ladder game." my_matches: "Mes Matchs" simulate: "Simuler" simulation_explanation: "En simulant une partie, tu peux classer ton rang plus rapidement!" simulate_games: "Simuler une Partie!" simulate_all: "REINITIALISER ET SIMULER DES PARTIES" games_simulated_by: "Parties que vous avez simulé :" games_simulated_for: "parties simulées pour vous :" games_simulated: "Partie simulée" games_played: "Parties jouées" ratio: "Moyenne" leaderboard: "Classement" battle_as: "Combattre comme " summary_your: "Vos " summary_matches: "Matchs - " summary_wins: " Victoires, " summary_losses: " Défaites" rank_no_code: "Nouveau Code à Classer" rank_my_game: "Classer ma Partie!" rank_submitting: "Soumission en cours..." rank_submitted: "Soumis pour le Classement" rank_failed: "Erreur lors du Classement" rank_being_ranked: "Partie en cours de Classement" rank_last_submitted: "Envoyé " help_simulate: "De l'aide pour simuler vos parties" code_being_simulated: "Votre nouveau code est en cours de simulation par les autres joueurs pour le classement. Cela va se rafraichir lors que d'autres matchs auront lieu." no_ranked_matches_pre: "Pas de match classé pour l'équipe " no_ranked_matches_post: "! Affronte d'autres compétiteurs et reviens ici pour classer ta partie." choose_opponent: "Choisir un Adversaire" # select_your_language: "Select your language!" tutorial_play: "Jouer au Tutoriel" tutorial_recommended: "Recommendé si tu n'as jamais joué avant" tutorial_skip: "Passer le Tutoriel" tutorial_not_sure: "Pas sûr de ce qu'il se passe?" tutorial_play_first: "Jouer au Tutoriel d'abord." simple_ai: "IA simple" warmup: "PréchauffPI:NAME:<NAME>END_PI" vs: "VS" # friends_playing: "Friends Playing" log_in_for_friends: "Connectez vous pour jouer avec vos amis!" social_connect_blurb: "Connectez vous pour jouer contre vos amis!" # invite_friends_to_battle: "Invite your friends to join you in battle!" fight: "Combattez !" watch_victory: "Regardez votre victoire" # defeat_the: "Defeat the" tournament_ends: "Fin du tournoi" # tournament_ended: "Tournament ended" tournament_rules: "Règles du tournoi" # tournament_blurb: "Write code, collect gold, build armies, crush foes, win prizes, and upgrade your career in our $40,000 Greed tournament! Check out the details" tournament_blurb_blog: "Sur notre blog" # rules: "Rules" # winners: "Winners" ladder_prizes: title: "Prix du tournoi" # blurb_1: "These prizes will be awarded according to" blurb_2: "Régles du tournoi" # blurb_3: "to the top human and ogre players." # blurb_4: "Two teams means double the prizes!" # blurb_5: "(There will be two first place winners, two second-place winners, etc.)" rank: "Rang" prizes: "Prix" total_value: "Valeur totale" # in_cash: "in cash" # custom_wizard: "Custom CodeCombat Wizard" # custom_avatar: "Custom CodeCombat avatar" # heap: "for six months of \"Startup\" access" credits: "Crédits" # one_month_coupon: "coupon: choose either Rails or HTML" # one_month_discount: "discount, 30% off: choose either Rails or HTML" license: "Licence" # oreilly: "ebook of your choice" multiplayer_launch: # introducing_dungeon_arena: "Introducing Dungeon Arena" # new_way: "The new way to compete with code." # to_battle: "To Battle, Developers!" # modern_day_sorcerer: "You know how to code? That's badass. You're a modern-day sorcerer! Isn't about time that you used your magic coding powers to command your minions in epic combat? And we're not talking robots here." # arenas_are_here: "CodeCombat head-to-head multiplayer arenas are here." # ladder_explanation: "Choose your heroes, enchant your human or ogre armies, and climb your way over defeated fellow Wizards to reach the top of the ladders–then challenge your friends in our glorious, asynchronous multiplayer coding arenas. If you're feeling creative, you can even" # fork_our_arenas: "fork our arenas" create_worlds: "et créez votre monde" javascript_rusty: "JavaScript un peu rouillé? Pas de souci; il y a un" tutorial: "Tutoriel" new_to_programming: ". Débutant en programmation? Essaie la campagne débutant pour progresser." so_ready: "Je Suis Prêt Pour Ca" loading_error: could_not_load: "Erreur de chargement du serveur" connection_failure: "La connexion a échouée." unauthorized: "Vous devez être identifiée pour faire cela. Avez-vous désactivé les cookies ?" forbidden: "Vous n'avez pas la permission." not_found: "Introuvable." not_allowed: "Méthode non autorisée." timeout: "Connexion au serveur écoulée." conflict: "Conflit de Ressources." bad_input: "Données incorrectes ." server_error: "Erreur serveur." unknown: "Erreur inconnue." resources: your_sessions: "vos Sessions" level: "Niveau" # social_network_apis: "Social Network APIs" facebook_status: "Statut Facebook" facebook_friends: "Amis Facebook" # facebook_friend_sessions: "Facebook Friend Sessions" # gplus_friends: "G+ Friends" # gplus_friend_sessions: "G+ Friend Sessions" leaderboard: "Classement" # user_schema: "User Schema" # user_profile: "User Profile" patches: "Patchs" # patched_model: "Source Document" # model: "Model" system: "Système" # component: "Component" # components: "Components" # thang: "Thang" # thangs: "Thangs" # level_session: "Your Session" # opponent_session: "Opponent Session" article: "Article" user_names: "PI:NAME:<NAME>END_PI'PI:NAME:<NAME>END_PI" # thang_names: "Thang Names" files: "Fichiers" top_simulators: "Top Simulateurs" source_document: "Document Source" document: "Document" # sprite_sheet: "Sprite Sheet" # candidate_sessions: "Candidate Sessions" # user_remark: "User Remark" # versions: "Versions" delta: added: "Ajouté" modified: "Modifié" deleted: "Supprimé" moved_index: "Index changé" text_diff: "Différence de texte" merge_conflict_with: "Fusionner les conflits avec" no_changes: "Aucuns Changements"
[ { "context": " data: JSON.stringify(\n cur_password: cpass\n new_password: npass1\n )\n ", "end": 1340, "score": 0.9121830463409424, "start": 1335, "tag": "PASSWORD", "value": "cpass" }, { "context": " cur_password: cpass\n new_passw...
views/js/admin_config.coffee
pjmtdw/kagetra
2
define ["crypto-aes", "crypto-hmac", "crypto-base64", "crypto-pbkdf2"], -> AdminChangePassView = Backbone.View.extend el: "#admin-change-pass" events: "submit #change-shared-pass" : "change_shared_pass" "submit #change-addrbook-pass" : "change_addrbook_pass" change_shared_pass: -> _.confirm_change_password el: $("#change-shared-pass") cur: "input[name='old-shared-pass']" new_1: "input[name='new-shared-pass-1']" new_2: "input[name='new-shared-pass-2']" url_confirm: 'api/user/auth/shared' url_change: 'api/user/change_shared_password' url_salt: 'api/user/shared_salt' change_addrbook_pass: _.wrap_submit -> fel = $("#change-addrbook-pass") cpass = fel.find("input[name='old-addrbook-pass']").val() npass1 = fel.find("input[name='new-addrbook-pass-1']").val() npass2 = fel.find("input[name='new-addrbook-pass-2']").val() if not g_addrbook_check_password(cpass) _.cb_alert('旧パスワードが間違っています') return else if npass1.length == 0 _.cb_alert('新パスワードが空白です') return else if npass1 != npass2 _.cb_alert('確認用パスワードが一致しません') return # TODO: パスワードを平文で送るのは危険 aj = $.ajax("api/addrbook/change_pass", data: JSON.stringify( cur_password: cpass new_password: npass1 ) contentType: "application/json" type: "POST").done(_.with_error("完了")) AdminChangeBoardMessageModel = Backbone.Model.extend url: -> "/api/board_message/#{@get('mode')}" AdminChangeBoardMessageView = Backbone.View.extend template: _.template_braces($("#templ-change-board-message").html()) events: "submit" : "do_submit" initialize: -> mode = @options.mode @setElement("#admin-change-board-message-" + mode) @model = new AdminChangeBoardMessageModel(mode:mode) @listenTo(@model,"sync",@render) @model.fetch() render: -> data = @model.toJSON() data.mode= @options.mode @$el.html(@template(data:data)) do_submit: _.wrap_submit -> @model.set("message",@$el.find("[name='message']").val()) @model.save().done(_.with_error("更新しました")) init: -> window.admin_config_view = new AdminChangePassView() window.admin_change_board_message_shared = new AdminChangeBoardMessageView(mode:"shared") window.admin_change_board_message_user = new AdminChangeBoardMessageView(mode:"user")
151422
define ["crypto-aes", "crypto-hmac", "crypto-base64", "crypto-pbkdf2"], -> AdminChangePassView = Backbone.View.extend el: "#admin-change-pass" events: "submit #change-shared-pass" : "change_shared_pass" "submit #change-addrbook-pass" : "change_addrbook_pass" change_shared_pass: -> _.confirm_change_password el: $("#change-shared-pass") cur: "input[name='old-shared-pass']" new_1: "input[name='new-shared-pass-1']" new_2: "input[name='new-shared-pass-2']" url_confirm: 'api/user/auth/shared' url_change: 'api/user/change_shared_password' url_salt: 'api/user/shared_salt' change_addrbook_pass: _.wrap_submit -> fel = $("#change-addrbook-pass") cpass = fel.find("input[name='old-addrbook-pass']").val() npass1 = fel.find("input[name='new-addrbook-pass-1']").val() npass2 = fel.find("input[name='new-addrbook-pass-2']").val() if not g_addrbook_check_password(cpass) _.cb_alert('旧パスワードが間違っています') return else if npass1.length == 0 _.cb_alert('新パスワードが空白です') return else if npass1 != npass2 _.cb_alert('確認用パスワードが一致しません') return # TODO: パスワードを平文で送るのは危険 aj = $.ajax("api/addrbook/change_pass", data: JSON.stringify( cur_password: <PASSWORD> new_password: <PASSWORD> ) contentType: "application/json" type: "POST").done(_.with_error("完了")) AdminChangeBoardMessageModel = Backbone.Model.extend url: -> "/api/board_message/#{@get('mode')}" AdminChangeBoardMessageView = Backbone.View.extend template: _.template_braces($("#templ-change-board-message").html()) events: "submit" : "do_submit" initialize: -> mode = @options.mode @setElement("#admin-change-board-message-" + mode) @model = new AdminChangeBoardMessageModel(mode:mode) @listenTo(@model,"sync",@render) @model.fetch() render: -> data = @model.toJSON() data.mode= @options.mode @$el.html(@template(data:data)) do_submit: _.wrap_submit -> @model.set("message",@$el.find("[name='message']").val()) @model.save().done(_.with_error("更新しました")) init: -> window.admin_config_view = new AdminChangePassView() window.admin_change_board_message_shared = new AdminChangeBoardMessageView(mode:"shared") window.admin_change_board_message_user = new AdminChangeBoardMessageView(mode:"user")
true
define ["crypto-aes", "crypto-hmac", "crypto-base64", "crypto-pbkdf2"], -> AdminChangePassView = Backbone.View.extend el: "#admin-change-pass" events: "submit #change-shared-pass" : "change_shared_pass" "submit #change-addrbook-pass" : "change_addrbook_pass" change_shared_pass: -> _.confirm_change_password el: $("#change-shared-pass") cur: "input[name='old-shared-pass']" new_1: "input[name='new-shared-pass-1']" new_2: "input[name='new-shared-pass-2']" url_confirm: 'api/user/auth/shared' url_change: 'api/user/change_shared_password' url_salt: 'api/user/shared_salt' change_addrbook_pass: _.wrap_submit -> fel = $("#change-addrbook-pass") cpass = fel.find("input[name='old-addrbook-pass']").val() npass1 = fel.find("input[name='new-addrbook-pass-1']").val() npass2 = fel.find("input[name='new-addrbook-pass-2']").val() if not g_addrbook_check_password(cpass) _.cb_alert('旧パスワードが間違っています') return else if npass1.length == 0 _.cb_alert('新パスワードが空白です') return else if npass1 != npass2 _.cb_alert('確認用パスワードが一致しません') return # TODO: パスワードを平文で送るのは危険 aj = $.ajax("api/addrbook/change_pass", data: JSON.stringify( cur_password: PI:PASSWORD:<PASSWORD>END_PI new_password: PI:PASSWORD:<PASSWORD>END_PI ) contentType: "application/json" type: "POST").done(_.with_error("完了")) AdminChangeBoardMessageModel = Backbone.Model.extend url: -> "/api/board_message/#{@get('mode')}" AdminChangeBoardMessageView = Backbone.View.extend template: _.template_braces($("#templ-change-board-message").html()) events: "submit" : "do_submit" initialize: -> mode = @options.mode @setElement("#admin-change-board-message-" + mode) @model = new AdminChangeBoardMessageModel(mode:mode) @listenTo(@model,"sync",@render) @model.fetch() render: -> data = @model.toJSON() data.mode= @options.mode @$el.html(@template(data:data)) do_submit: _.wrap_submit -> @model.set("message",@$el.find("[name='message']").val()) @model.save().done(_.with_error("更新しました")) init: -> window.admin_config_view = new AdminChangePassView() window.admin_change_board_message_shared = new AdminChangeBoardMessageView(mode:"shared") window.admin_change_board_message_user = new AdminChangeBoardMessageView(mode:"user")
[ { "context": "rn if not value\n\n $scope.storageKey = \"comment-\" + value.project + \"-\" + value.id + \"-\" + value._n", "end": 2091, "score": 0.8864040970802307, "start": 2082, "tag": "KEY", "value": "comment-\"" }, { "context": " $scope.storageKey = \"comment-\" + val...
app/modules/components/wysiwyg/comment-wysiwyg.directive.coffee
threefoldtech/Threefold-Circles-front
0
### # Copyright (C) 2014-2018 Taiga Agile LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: components/wysiwyg/comment-wysiwyg.directive.coffee ### CommentWysiwyg = ($modelTransform, $rootscope, attachmentsFullService) -> link = ($scope, $el, $attrs) -> $scope.editableDescription = false $scope.saveComment = (description, cb) -> $scope.content = '' $scope.vm.type.comment = description transform = $modelTransform.save (item) -> return transform.then -> if $scope.vm.onAddComment $scope.vm.onAddComment() $rootscope.$broadcast("object:updated") transform.finally(cb) types = { epics: "epic", userstories: "us", issues: "issue", tasks: "task" } uploadFile = (file, cb) -> return attachmentsFullService.addAttachment($scope.vm.projectId, $scope.vm.type.id, types[$scope.vm.type._name], file, true, true).then (result) -> cb(result.getIn(['file', 'name']), result.getIn(['file', 'url'])) $scope.onChange = (markdown) -> $scope.vm.type.comment = markdown $scope.uploadFiles = (files, cb) -> for file in files uploadFile(file, cb) $scope.content = '' $scope.$watch "vm.type", (value) -> return if not value $scope.storageKey = "comment-" + value.project + "-" + value.id + "-" + value._name return { scope: true, link: link, template: """ <div> <tg-wysiwyg required not-persist placeholder='{{"COMMENTS.TYPE_NEW_COMMENT" | translate}}' storage-key='storageKey' content='content' on-save='saveComment(text, cb)' on-upload-file='uploadFiles(files, cb)'> </tg-wysiwyg> </div> """ } angular.module("taigaComponents") .directive("tgCommentWysiwyg", [ "$tgQueueModelTransformation", "$rootScope", "tgAttachmentsFullService", CommentWysiwyg])
122956
### # Copyright (C) 2014-2018 Taiga Agile LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: components/wysiwyg/comment-wysiwyg.directive.coffee ### CommentWysiwyg = ($modelTransform, $rootscope, attachmentsFullService) -> link = ($scope, $el, $attrs) -> $scope.editableDescription = false $scope.saveComment = (description, cb) -> $scope.content = '' $scope.vm.type.comment = description transform = $modelTransform.save (item) -> return transform.then -> if $scope.vm.onAddComment $scope.vm.onAddComment() $rootscope.$broadcast("object:updated") transform.finally(cb) types = { epics: "epic", userstories: "us", issues: "issue", tasks: "task" } uploadFile = (file, cb) -> return attachmentsFullService.addAttachment($scope.vm.projectId, $scope.vm.type.id, types[$scope.vm.type._name], file, true, true).then (result) -> cb(result.getIn(['file', 'name']), result.getIn(['file', 'url'])) $scope.onChange = (markdown) -> $scope.vm.type.comment = markdown $scope.uploadFiles = (files, cb) -> for file in files uploadFile(file, cb) $scope.content = '' $scope.$watch "vm.type", (value) -> return if not value $scope.storageKey = "<KEY> + value.project + <KEY> + value.id + <KEY> + value._name return { scope: true, link: link, template: """ <div> <tg-wysiwyg required not-persist placeholder='{{"COMMENTS.TYPE_NEW_COMMENT" | translate}}' storage-key='storageKey' content='content' on-save='saveComment(text, cb)' on-upload-file='uploadFiles(files, cb)'> </tg-wysiwyg> </div> """ } angular.module("taigaComponents") .directive("tgCommentWysiwyg", [ "$tgQueueModelTransformation", "$rootScope", "tgAttachmentsFullService", CommentWysiwyg])
true
### # Copyright (C) 2014-2018 Taiga Agile LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: components/wysiwyg/comment-wysiwyg.directive.coffee ### CommentWysiwyg = ($modelTransform, $rootscope, attachmentsFullService) -> link = ($scope, $el, $attrs) -> $scope.editableDescription = false $scope.saveComment = (description, cb) -> $scope.content = '' $scope.vm.type.comment = description transform = $modelTransform.save (item) -> return transform.then -> if $scope.vm.onAddComment $scope.vm.onAddComment() $rootscope.$broadcast("object:updated") transform.finally(cb) types = { epics: "epic", userstories: "us", issues: "issue", tasks: "task" } uploadFile = (file, cb) -> return attachmentsFullService.addAttachment($scope.vm.projectId, $scope.vm.type.id, types[$scope.vm.type._name], file, true, true).then (result) -> cb(result.getIn(['file', 'name']), result.getIn(['file', 'url'])) $scope.onChange = (markdown) -> $scope.vm.type.comment = markdown $scope.uploadFiles = (files, cb) -> for file in files uploadFile(file, cb) $scope.content = '' $scope.$watch "vm.type", (value) -> return if not value $scope.storageKey = "PI:KEY:<KEY>END_PI + value.project + PI:KEY:<KEY>END_PI + value.id + PI:KEY:<KEY>END_PI + value._name return { scope: true, link: link, template: """ <div> <tg-wysiwyg required not-persist placeholder='{{"COMMENTS.TYPE_NEW_COMMENT" | translate}}' storage-key='storageKey' content='content' on-save='saveComment(text, cb)' on-upload-file='uploadFiles(files, cb)'> </tg-wysiwyg> </div> """ } angular.module("taigaComponents") .directive("tgCommentWysiwyg", [ "$tgQueueModelTransformation", "$rootScope", "tgAttachmentsFullService", CommentWysiwyg])
[ { "context": "errors = {}\n this._parent = {}\n this._name = name\n this._json = {}\n this._uid = _.uniqueId(\"#", "end": 198, "score": 0.8532000780105591, "start": 194, "tag": "NAME", "value": "name" } ]
src/model.coffee
lancecarlson/corpus
1
this.Model = (name, options, func) -> model = (attributes) -> self = this this._tagId = null this._refresh attributes this._errors = {} this._parent = {} this._name = name this._json = {} this._uid = _.uniqueId("#{this._name}_") this.bind "change", this._change this.bind "data:format", this.toData _.each model.listAssociations(), (associationName) -> self[associationName]._parent = self this.initialize(attributes) this model._name = name _.extend model.prototype, Model.Events, # Callback that can be used when a record is initialized initialize: -> # Do nothing # Returns the model name of the record modelName: -> "#{_.classify this._name}" # Returns the attributes associated with the record attributes: -> this._attributes _change: (record) -> _.each record._changes, (value, key) -> if $(name).val() != value $(name).val value _refresh: (attributes) -> this._attributes = attributes or= {} this._parseAssociations attributes this._prevAttributes = _.clone(this._attributes) this._changes = {} this.attr(attributes) this._changes = {} _parseAssociations: (attributes) -> _.each model._manyAssociations, (assoc) -> val = attributes[assoc] delete attributes[assoc] _.each val, (attrs) -> instance = eval("new #{_.classify assoc}") instance._refresh(attrs) instance._parent = this this[assoc].add instance , this , this # Get the attribute value. # post.get("body") get: (key) -> this._attributes[key] # Set the attribute value. Can set multiple keys at once. # post.set("body", "Lorem Ipsum..") # post.set({body: "Lorem Ipsum", title: "Fake Latin Lesson"}) set: (key, value) -> if _.isString(key) or _.isNumber(key) # Run value through sanitation if set if model._sanitizers[key] value = model._sanitizers[key].call(this, value) # Delete from changes if changed back to previous value if _.isEqual this._prevAttributes[key], value delete this._changes[key] # Create new changes else this._changes[key] = value # Set new value and trigger changes this._attributes[key] = value this.trigger("change", [this]) else for k, v of key this.set(k, v) # Set or get an attribute value/values # post.attr("body", "Lorem Ipsum") # post.attr("body") #=> "Lorem Ipsum" attr: (key, value) -> argLen = arguments.length return false if (_.isUndefined(key) or _.isEmpty(key)) && argLen > 0 if (argLen == 0) this._attributes else if (argLen == 2) this.set(key, value) else if _.isString(key) or _.isNumber(key) this.get(key) else this.set(key) # Indicates if the record has changed or not. # Returns true or false changed: -> this._changes != {} # Changes to the attributes of the record # Returns {key: "value", key2: "value2"} changes: -> this._changes # Unbind record from a form. See bindTo() unbindFrom: (form) -> $(form).undelegate ":input", "change", this.onBoundChange $(form).undelegate ":input", "keyup", this.onBoundChange # Bind record to a form. All changes to input/select/textarea fields will automatically update the # attributes on a record. # post.bindTo "#post_form" bindTo: (form) -> self = this $(form).delegate ":input", "change", {record: this}, this.onBoundChange $(form).delegate ":input", "keyup", {record: this}, this.onBoundChange onBoundChange: (e) -> el = $(e.target) record = e.data.record value = el.val() keys = record._parseNameField el keys.shift() record._parseAttributeKeys(keys, value) _parseAttributeKeys: (keys, value) -> # attribute if keys.length == 1 key = keys[0] this.attr key, value # association else if keys.length > 1 this._parseAssociationKeys(keys, value) _parseAssociationKeys: (keys, value) -> assoc = keys.shift().replace("_attributes", "") uid = keys.shift() key = keys[0] if !this[assoc]._object obj = this[assoc].findByUid(uid) else obj = this[assoc]._object obj._parseAttributeKeys(keys, value) _parseNameField: (el) -> _.map el.attr("name").split("["), (p) -> p.replace("]", "") # Gets the id of the record from the server id: -> this.get("id") # The UID for the record object. This is generated randomly for each record and is never equal to the id() uid: -> this._uid # Determines if the record is new or not. Looks at the id() and if it is set, then it's not new. # Returns true or false isNew: -> !_.isNumber this.id() # Displays the validations errors that came from the server response errors: -> this._errors # Reset validation errors resetErrors: -> this._errors = {} # When a record has been marked hasMany or hasOne, they become a child in that association. # parent() is a convenient way to access the parent object. # Example, Post.hasMany "comments" # comment.parent() #=> post record parent: -> this._parent # Deprecated tagId: -> this._tagId # Generates JSON for the persistence request. You never need to call this but it's useful to look at # for debugging purposes. You can also override this method to generate your own toJSON logic. toJSON: (options) -> baseObj = if options and options.child this._json = _.clone this.attributes() else this._json[model._name] = _.clone this.attributes() this.trigger "data:format", [this] # Loop through hasMany associations _.each model._manyAssociations, (association) -> model.prototype[association].each (child) -> childKey = "#{association}_attributes" baseObj[childKey] = [] unless baseObj[childKey] baseObj[childKey].push child.toJSON({child: true}) , this , this # Loop through hasOne associations _.each model._oneAssociations, (association) -> child = model.prototype[association] baseObj["#{association}_attributes"] = child._object.toJSON({child: true}) if child._object , this this._json # The url used to make REST requests getUrl: (method) -> path = _.pluralize "/#{model._name}" path = "#{path}/#{this.id()}" unless this.isNew() path # Saves the record # Example: # post.save # success: (validPost) -> # console.log "SUCCESS" # errors: (invalidPost) -> # console.log invalidPost.errors save: (options) -> method = if this.isNew() then "create" else "update" record = this options or= {} success = options.success error = options.error options.success = (resp, status, xhr) -> record.resetErrors() unless _.isEmpty resp record.attr "id", resp["id"] success record, resp, xhr record.trigger "save:after", [record] options.error = (resp, status, xhr) -> record._errors = $.parseJSON(resp.responseText) error record, resp, xhr if error record.trigger "save:after", [record] record.trigger "save:before", [record] Model.Sync(record, method, options) # Deprecated. toData: -> # Do nothing # Associations _.extend model, _manyAssociations: [] _oneAssociations: [] _sanitizers: {} listAssociations: -> this._manyAssociations.concat this._oneAssociations # Sets a hasMany association for the model # Post.hasMany "comments" # # post.comments #=> [{comment1...}, {comment2...}] # # You can also extend the collection methods by using extend # Post.hasMany "comments", # extend: # popularComments: -> # this.records = this.sortBy (comment) -> comment.position() hasMany: (name, options) -> this._manyAssociations.push name manyArray = {} collection = new Model.Collection(name) if options and options.extend _.extend collection, options.extend manyArray[name] = collection _.extend model.prototype, manyArray # Sets a hasOne association for the model # Post.hasOne "user" hasOne: (name) -> this._oneAssociations.push name association = new Model.One(name) oneObj = {} oneObj[name] = association oneObj["build_#{name}"] = -> association.build() oneObj["clear_#{name}"] = -> association.clear() _.extend model.prototype, oneObj # Sanitize incoming record attribute data # Task.sanitize "hours", (hours) -> parseInt(hours) # # Then if you do this: # task.set("hours", "5") # # You should get: # task.get("hours") #=> 5 sanitize: (key, callback) -> this._sanitizers[key] = callback newCollection: -> new Model.Collection(this._name) fetch: (params) -> model.newCollection().fetch(params) query: (options) -> model.newCollection().query(options) model this.Model.Events = bind: (event, callback) -> this.callbacks = this.callbacks || {} this.callbacks[event] = this.callbacks[event] || [] this.callbacks[event].push(callback) this trigger: (name, data) -> this.callbacks = this.callbacks || {} callbacks = this.callbacks[name] if callbacks for callback in callbacks callback.apply(this, data || []) this # Ajax persistence this.Model.Sync = (obj, method, options) -> methodVerbs = { "create": "POST", "update": "PUT", "delete": "DELETE", "read": "GET" } params = _.extend({ type: methodVerbs[method], contentType: "application/json", dataType: "json", processData: if method == "read" then true else false}, options) params.url = obj.getUrl(method) unless options.data data = JSON.stringify obj.toJSON() params.data = data unless data == "{}" $.ajax(params) # One this.Model.One = (name) -> this._name = name this _.extend Model.One.prototype, build: -> record = eval("new #{_.classify this._name}") record._parent = this.parent() if this.parent() this._object = record clear: -> this.parent()[this._name] = this parent: -> this._parent # Collection this.Model.Collection = (name) -> this._name = _.singularize name this._options = {} this._reset() this.url = this.getUrl(name) this.bind "change", this._change this.bind "add", (collection) -> this.trigger("refresh", [collection]) this.bind "remove", (collection) -> this.trigger("refresh", [collection]) this _.extend Model.Collection.prototype, Model.Events, getUrl: -> "/#{_.pluralize this._name}" add: (records) -> if _.isArray records _.each records, (record) -> this._add record , this else this._add records removeAll: -> this.records = [] #this.remove this.records remove: (records) -> if _.isArray records _.each records, (record) -> this._remove record , this else this._remove records _change: (record) -> self = this _.each record._changes, (value, key) -> index_id = record.tagId() current_model_name = _.pluralize(record._name) name = '[name="' + self.parent()._name + "[#{current_model_name}_attributes][#{index_id}][#{key}]" + '"]' $(name).val value parent: -> this._parent get: (id) -> return null if _.isNull id return this._byId[if !_.isNull id.id then id.id else id] refresh: (records) -> this._reset() this.add(records) this.trigger("refresh", [this]) this fetch: (params) -> this.query(data: params) this findByTagId: (tag_id) -> _.detect this.records, (element) -> element.tagId() == parseInt(tag_id) removeByTagId: (tag_id) -> record = _.detect this.records, (element) -> element.tagId() == parseInt(tag_id) this._remove(record) if record findByUid: (uid) -> _.detect this.records, (record) -> record.uid() == uid removeByUid: (uid) -> record = this.findByUid(uid) this._remove(record) if record query: (options) -> this._options = options or= {} collection = this success = options.success options.success = (resp, status, xhr) -> collection.refresh(resp) success(collection, resp) if success Model.Sync(this, "read", options) this toJSON: -> this._options pluck: (attr) -> _.map this.records, (record) -> record.get attr _add: (record) -> # If a json object is passed, convert to record object unless record._name attr = record record = eval("new #{_.classify this._name}") record._refresh(attr) this._bindRecordEvents(record) record._parent = this.parent() if this.parent() this.records.push record this.length++ this.trigger("add", [record]) record _remove: (record) -> index = this.records.indexOf(record) this.records.splice(index, 1) this.trigger("remove", [record]) # Deprecate this in favor of dispatching a change event after a bind to remove this.trigger("change", [record]) this.length-- _reset: -> this.length = 0 this.records = [] this._byId = {} _bindRecordEvents: (record) -> collection = this record.bind "change", -> collection.trigger "change", [record] # Underscore methods that we want to implement on the Collection. methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size', 'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty'] _.each methods, (method) -> Model.Collection.prototype[method] = -> _[method].apply(_, [this.records].concat(_.toArray(arguments)))
125507
this.Model = (name, options, func) -> model = (attributes) -> self = this this._tagId = null this._refresh attributes this._errors = {} this._parent = {} this._name = <NAME> this._json = {} this._uid = _.uniqueId("#{this._name}_") this.bind "change", this._change this.bind "data:format", this.toData _.each model.listAssociations(), (associationName) -> self[associationName]._parent = self this.initialize(attributes) this model._name = name _.extend model.prototype, Model.Events, # Callback that can be used when a record is initialized initialize: -> # Do nothing # Returns the model name of the record modelName: -> "#{_.classify this._name}" # Returns the attributes associated with the record attributes: -> this._attributes _change: (record) -> _.each record._changes, (value, key) -> if $(name).val() != value $(name).val value _refresh: (attributes) -> this._attributes = attributes or= {} this._parseAssociations attributes this._prevAttributes = _.clone(this._attributes) this._changes = {} this.attr(attributes) this._changes = {} _parseAssociations: (attributes) -> _.each model._manyAssociations, (assoc) -> val = attributes[assoc] delete attributes[assoc] _.each val, (attrs) -> instance = eval("new #{_.classify assoc}") instance._refresh(attrs) instance._parent = this this[assoc].add instance , this , this # Get the attribute value. # post.get("body") get: (key) -> this._attributes[key] # Set the attribute value. Can set multiple keys at once. # post.set("body", "Lorem Ipsum..") # post.set({body: "Lorem Ipsum", title: "Fake Latin Lesson"}) set: (key, value) -> if _.isString(key) or _.isNumber(key) # Run value through sanitation if set if model._sanitizers[key] value = model._sanitizers[key].call(this, value) # Delete from changes if changed back to previous value if _.isEqual this._prevAttributes[key], value delete this._changes[key] # Create new changes else this._changes[key] = value # Set new value and trigger changes this._attributes[key] = value this.trigger("change", [this]) else for k, v of key this.set(k, v) # Set or get an attribute value/values # post.attr("body", "Lorem Ipsum") # post.attr("body") #=> "Lorem Ipsum" attr: (key, value) -> argLen = arguments.length return false if (_.isUndefined(key) or _.isEmpty(key)) && argLen > 0 if (argLen == 0) this._attributes else if (argLen == 2) this.set(key, value) else if _.isString(key) or _.isNumber(key) this.get(key) else this.set(key) # Indicates if the record has changed or not. # Returns true or false changed: -> this._changes != {} # Changes to the attributes of the record # Returns {key: "value", key2: "value2"} changes: -> this._changes # Unbind record from a form. See bindTo() unbindFrom: (form) -> $(form).undelegate ":input", "change", this.onBoundChange $(form).undelegate ":input", "keyup", this.onBoundChange # Bind record to a form. All changes to input/select/textarea fields will automatically update the # attributes on a record. # post.bindTo "#post_form" bindTo: (form) -> self = this $(form).delegate ":input", "change", {record: this}, this.onBoundChange $(form).delegate ":input", "keyup", {record: this}, this.onBoundChange onBoundChange: (e) -> el = $(e.target) record = e.data.record value = el.val() keys = record._parseNameField el keys.shift() record._parseAttributeKeys(keys, value) _parseAttributeKeys: (keys, value) -> # attribute if keys.length == 1 key = keys[0] this.attr key, value # association else if keys.length > 1 this._parseAssociationKeys(keys, value) _parseAssociationKeys: (keys, value) -> assoc = keys.shift().replace("_attributes", "") uid = keys.shift() key = keys[0] if !this[assoc]._object obj = this[assoc].findByUid(uid) else obj = this[assoc]._object obj._parseAttributeKeys(keys, value) _parseNameField: (el) -> _.map el.attr("name").split("["), (p) -> p.replace("]", "") # Gets the id of the record from the server id: -> this.get("id") # The UID for the record object. This is generated randomly for each record and is never equal to the id() uid: -> this._uid # Determines if the record is new or not. Looks at the id() and if it is set, then it's not new. # Returns true or false isNew: -> !_.isNumber this.id() # Displays the validations errors that came from the server response errors: -> this._errors # Reset validation errors resetErrors: -> this._errors = {} # When a record has been marked hasMany or hasOne, they become a child in that association. # parent() is a convenient way to access the parent object. # Example, Post.hasMany "comments" # comment.parent() #=> post record parent: -> this._parent # Deprecated tagId: -> this._tagId # Generates JSON for the persistence request. You never need to call this but it's useful to look at # for debugging purposes. You can also override this method to generate your own toJSON logic. toJSON: (options) -> baseObj = if options and options.child this._json = _.clone this.attributes() else this._json[model._name] = _.clone this.attributes() this.trigger "data:format", [this] # Loop through hasMany associations _.each model._manyAssociations, (association) -> model.prototype[association].each (child) -> childKey = "#{association}_attributes" baseObj[childKey] = [] unless baseObj[childKey] baseObj[childKey].push child.toJSON({child: true}) , this , this # Loop through hasOne associations _.each model._oneAssociations, (association) -> child = model.prototype[association] baseObj["#{association}_attributes"] = child._object.toJSON({child: true}) if child._object , this this._json # The url used to make REST requests getUrl: (method) -> path = _.pluralize "/#{model._name}" path = "#{path}/#{this.id()}" unless this.isNew() path # Saves the record # Example: # post.save # success: (validPost) -> # console.log "SUCCESS" # errors: (invalidPost) -> # console.log invalidPost.errors save: (options) -> method = if this.isNew() then "create" else "update" record = this options or= {} success = options.success error = options.error options.success = (resp, status, xhr) -> record.resetErrors() unless _.isEmpty resp record.attr "id", resp["id"] success record, resp, xhr record.trigger "save:after", [record] options.error = (resp, status, xhr) -> record._errors = $.parseJSON(resp.responseText) error record, resp, xhr if error record.trigger "save:after", [record] record.trigger "save:before", [record] Model.Sync(record, method, options) # Deprecated. toData: -> # Do nothing # Associations _.extend model, _manyAssociations: [] _oneAssociations: [] _sanitizers: {} listAssociations: -> this._manyAssociations.concat this._oneAssociations # Sets a hasMany association for the model # Post.hasMany "comments" # # post.comments #=> [{comment1...}, {comment2...}] # # You can also extend the collection methods by using extend # Post.hasMany "comments", # extend: # popularComments: -> # this.records = this.sortBy (comment) -> comment.position() hasMany: (name, options) -> this._manyAssociations.push name manyArray = {} collection = new Model.Collection(name) if options and options.extend _.extend collection, options.extend manyArray[name] = collection _.extend model.prototype, manyArray # Sets a hasOne association for the model # Post.hasOne "user" hasOne: (name) -> this._oneAssociations.push name association = new Model.One(name) oneObj = {} oneObj[name] = association oneObj["build_#{name}"] = -> association.build() oneObj["clear_#{name}"] = -> association.clear() _.extend model.prototype, oneObj # Sanitize incoming record attribute data # Task.sanitize "hours", (hours) -> parseInt(hours) # # Then if you do this: # task.set("hours", "5") # # You should get: # task.get("hours") #=> 5 sanitize: (key, callback) -> this._sanitizers[key] = callback newCollection: -> new Model.Collection(this._name) fetch: (params) -> model.newCollection().fetch(params) query: (options) -> model.newCollection().query(options) model this.Model.Events = bind: (event, callback) -> this.callbacks = this.callbacks || {} this.callbacks[event] = this.callbacks[event] || [] this.callbacks[event].push(callback) this trigger: (name, data) -> this.callbacks = this.callbacks || {} callbacks = this.callbacks[name] if callbacks for callback in callbacks callback.apply(this, data || []) this # Ajax persistence this.Model.Sync = (obj, method, options) -> methodVerbs = { "create": "POST", "update": "PUT", "delete": "DELETE", "read": "GET" } params = _.extend({ type: methodVerbs[method], contentType: "application/json", dataType: "json", processData: if method == "read" then true else false}, options) params.url = obj.getUrl(method) unless options.data data = JSON.stringify obj.toJSON() params.data = data unless data == "{}" $.ajax(params) # One this.Model.One = (name) -> this._name = name this _.extend Model.One.prototype, build: -> record = eval("new #{_.classify this._name}") record._parent = this.parent() if this.parent() this._object = record clear: -> this.parent()[this._name] = this parent: -> this._parent # Collection this.Model.Collection = (name) -> this._name = _.singularize name this._options = {} this._reset() this.url = this.getUrl(name) this.bind "change", this._change this.bind "add", (collection) -> this.trigger("refresh", [collection]) this.bind "remove", (collection) -> this.trigger("refresh", [collection]) this _.extend Model.Collection.prototype, Model.Events, getUrl: -> "/#{_.pluralize this._name}" add: (records) -> if _.isArray records _.each records, (record) -> this._add record , this else this._add records removeAll: -> this.records = [] #this.remove this.records remove: (records) -> if _.isArray records _.each records, (record) -> this._remove record , this else this._remove records _change: (record) -> self = this _.each record._changes, (value, key) -> index_id = record.tagId() current_model_name = _.pluralize(record._name) name = '[name="' + self.parent()._name + "[#{current_model_name}_attributes][#{index_id}][#{key}]" + '"]' $(name).val value parent: -> this._parent get: (id) -> return null if _.isNull id return this._byId[if !_.isNull id.id then id.id else id] refresh: (records) -> this._reset() this.add(records) this.trigger("refresh", [this]) this fetch: (params) -> this.query(data: params) this findByTagId: (tag_id) -> _.detect this.records, (element) -> element.tagId() == parseInt(tag_id) removeByTagId: (tag_id) -> record = _.detect this.records, (element) -> element.tagId() == parseInt(tag_id) this._remove(record) if record findByUid: (uid) -> _.detect this.records, (record) -> record.uid() == uid removeByUid: (uid) -> record = this.findByUid(uid) this._remove(record) if record query: (options) -> this._options = options or= {} collection = this success = options.success options.success = (resp, status, xhr) -> collection.refresh(resp) success(collection, resp) if success Model.Sync(this, "read", options) this toJSON: -> this._options pluck: (attr) -> _.map this.records, (record) -> record.get attr _add: (record) -> # If a json object is passed, convert to record object unless record._name attr = record record = eval("new #{_.classify this._name}") record._refresh(attr) this._bindRecordEvents(record) record._parent = this.parent() if this.parent() this.records.push record this.length++ this.trigger("add", [record]) record _remove: (record) -> index = this.records.indexOf(record) this.records.splice(index, 1) this.trigger("remove", [record]) # Deprecate this in favor of dispatching a change event after a bind to remove this.trigger("change", [record]) this.length-- _reset: -> this.length = 0 this.records = [] this._byId = {} _bindRecordEvents: (record) -> collection = this record.bind "change", -> collection.trigger "change", [record] # Underscore methods that we want to implement on the Collection. methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size', 'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty'] _.each methods, (method) -> Model.Collection.prototype[method] = -> _[method].apply(_, [this.records].concat(_.toArray(arguments)))
true
this.Model = (name, options, func) -> model = (attributes) -> self = this this._tagId = null this._refresh attributes this._errors = {} this._parent = {} this._name = PI:NAME:<NAME>END_PI this._json = {} this._uid = _.uniqueId("#{this._name}_") this.bind "change", this._change this.bind "data:format", this.toData _.each model.listAssociations(), (associationName) -> self[associationName]._parent = self this.initialize(attributes) this model._name = name _.extend model.prototype, Model.Events, # Callback that can be used when a record is initialized initialize: -> # Do nothing # Returns the model name of the record modelName: -> "#{_.classify this._name}" # Returns the attributes associated with the record attributes: -> this._attributes _change: (record) -> _.each record._changes, (value, key) -> if $(name).val() != value $(name).val value _refresh: (attributes) -> this._attributes = attributes or= {} this._parseAssociations attributes this._prevAttributes = _.clone(this._attributes) this._changes = {} this.attr(attributes) this._changes = {} _parseAssociations: (attributes) -> _.each model._manyAssociations, (assoc) -> val = attributes[assoc] delete attributes[assoc] _.each val, (attrs) -> instance = eval("new #{_.classify assoc}") instance._refresh(attrs) instance._parent = this this[assoc].add instance , this , this # Get the attribute value. # post.get("body") get: (key) -> this._attributes[key] # Set the attribute value. Can set multiple keys at once. # post.set("body", "Lorem Ipsum..") # post.set({body: "Lorem Ipsum", title: "Fake Latin Lesson"}) set: (key, value) -> if _.isString(key) or _.isNumber(key) # Run value through sanitation if set if model._sanitizers[key] value = model._sanitizers[key].call(this, value) # Delete from changes if changed back to previous value if _.isEqual this._prevAttributes[key], value delete this._changes[key] # Create new changes else this._changes[key] = value # Set new value and trigger changes this._attributes[key] = value this.trigger("change", [this]) else for k, v of key this.set(k, v) # Set or get an attribute value/values # post.attr("body", "Lorem Ipsum") # post.attr("body") #=> "Lorem Ipsum" attr: (key, value) -> argLen = arguments.length return false if (_.isUndefined(key) or _.isEmpty(key)) && argLen > 0 if (argLen == 0) this._attributes else if (argLen == 2) this.set(key, value) else if _.isString(key) or _.isNumber(key) this.get(key) else this.set(key) # Indicates if the record has changed or not. # Returns true or false changed: -> this._changes != {} # Changes to the attributes of the record # Returns {key: "value", key2: "value2"} changes: -> this._changes # Unbind record from a form. See bindTo() unbindFrom: (form) -> $(form).undelegate ":input", "change", this.onBoundChange $(form).undelegate ":input", "keyup", this.onBoundChange # Bind record to a form. All changes to input/select/textarea fields will automatically update the # attributes on a record. # post.bindTo "#post_form" bindTo: (form) -> self = this $(form).delegate ":input", "change", {record: this}, this.onBoundChange $(form).delegate ":input", "keyup", {record: this}, this.onBoundChange onBoundChange: (e) -> el = $(e.target) record = e.data.record value = el.val() keys = record._parseNameField el keys.shift() record._parseAttributeKeys(keys, value) _parseAttributeKeys: (keys, value) -> # attribute if keys.length == 1 key = keys[0] this.attr key, value # association else if keys.length > 1 this._parseAssociationKeys(keys, value) _parseAssociationKeys: (keys, value) -> assoc = keys.shift().replace("_attributes", "") uid = keys.shift() key = keys[0] if !this[assoc]._object obj = this[assoc].findByUid(uid) else obj = this[assoc]._object obj._parseAttributeKeys(keys, value) _parseNameField: (el) -> _.map el.attr("name").split("["), (p) -> p.replace("]", "") # Gets the id of the record from the server id: -> this.get("id") # The UID for the record object. This is generated randomly for each record and is never equal to the id() uid: -> this._uid # Determines if the record is new or not. Looks at the id() and if it is set, then it's not new. # Returns true or false isNew: -> !_.isNumber this.id() # Displays the validations errors that came from the server response errors: -> this._errors # Reset validation errors resetErrors: -> this._errors = {} # When a record has been marked hasMany or hasOne, they become a child in that association. # parent() is a convenient way to access the parent object. # Example, Post.hasMany "comments" # comment.parent() #=> post record parent: -> this._parent # Deprecated tagId: -> this._tagId # Generates JSON for the persistence request. You never need to call this but it's useful to look at # for debugging purposes. You can also override this method to generate your own toJSON logic. toJSON: (options) -> baseObj = if options and options.child this._json = _.clone this.attributes() else this._json[model._name] = _.clone this.attributes() this.trigger "data:format", [this] # Loop through hasMany associations _.each model._manyAssociations, (association) -> model.prototype[association].each (child) -> childKey = "#{association}_attributes" baseObj[childKey] = [] unless baseObj[childKey] baseObj[childKey].push child.toJSON({child: true}) , this , this # Loop through hasOne associations _.each model._oneAssociations, (association) -> child = model.prototype[association] baseObj["#{association}_attributes"] = child._object.toJSON({child: true}) if child._object , this this._json # The url used to make REST requests getUrl: (method) -> path = _.pluralize "/#{model._name}" path = "#{path}/#{this.id()}" unless this.isNew() path # Saves the record # Example: # post.save # success: (validPost) -> # console.log "SUCCESS" # errors: (invalidPost) -> # console.log invalidPost.errors save: (options) -> method = if this.isNew() then "create" else "update" record = this options or= {} success = options.success error = options.error options.success = (resp, status, xhr) -> record.resetErrors() unless _.isEmpty resp record.attr "id", resp["id"] success record, resp, xhr record.trigger "save:after", [record] options.error = (resp, status, xhr) -> record._errors = $.parseJSON(resp.responseText) error record, resp, xhr if error record.trigger "save:after", [record] record.trigger "save:before", [record] Model.Sync(record, method, options) # Deprecated. toData: -> # Do nothing # Associations _.extend model, _manyAssociations: [] _oneAssociations: [] _sanitizers: {} listAssociations: -> this._manyAssociations.concat this._oneAssociations # Sets a hasMany association for the model # Post.hasMany "comments" # # post.comments #=> [{comment1...}, {comment2...}] # # You can also extend the collection methods by using extend # Post.hasMany "comments", # extend: # popularComments: -> # this.records = this.sortBy (comment) -> comment.position() hasMany: (name, options) -> this._manyAssociations.push name manyArray = {} collection = new Model.Collection(name) if options and options.extend _.extend collection, options.extend manyArray[name] = collection _.extend model.prototype, manyArray # Sets a hasOne association for the model # Post.hasOne "user" hasOne: (name) -> this._oneAssociations.push name association = new Model.One(name) oneObj = {} oneObj[name] = association oneObj["build_#{name}"] = -> association.build() oneObj["clear_#{name}"] = -> association.clear() _.extend model.prototype, oneObj # Sanitize incoming record attribute data # Task.sanitize "hours", (hours) -> parseInt(hours) # # Then if you do this: # task.set("hours", "5") # # You should get: # task.get("hours") #=> 5 sanitize: (key, callback) -> this._sanitizers[key] = callback newCollection: -> new Model.Collection(this._name) fetch: (params) -> model.newCollection().fetch(params) query: (options) -> model.newCollection().query(options) model this.Model.Events = bind: (event, callback) -> this.callbacks = this.callbacks || {} this.callbacks[event] = this.callbacks[event] || [] this.callbacks[event].push(callback) this trigger: (name, data) -> this.callbacks = this.callbacks || {} callbacks = this.callbacks[name] if callbacks for callback in callbacks callback.apply(this, data || []) this # Ajax persistence this.Model.Sync = (obj, method, options) -> methodVerbs = { "create": "POST", "update": "PUT", "delete": "DELETE", "read": "GET" } params = _.extend({ type: methodVerbs[method], contentType: "application/json", dataType: "json", processData: if method == "read" then true else false}, options) params.url = obj.getUrl(method) unless options.data data = JSON.stringify obj.toJSON() params.data = data unless data == "{}" $.ajax(params) # One this.Model.One = (name) -> this._name = name this _.extend Model.One.prototype, build: -> record = eval("new #{_.classify this._name}") record._parent = this.parent() if this.parent() this._object = record clear: -> this.parent()[this._name] = this parent: -> this._parent # Collection this.Model.Collection = (name) -> this._name = _.singularize name this._options = {} this._reset() this.url = this.getUrl(name) this.bind "change", this._change this.bind "add", (collection) -> this.trigger("refresh", [collection]) this.bind "remove", (collection) -> this.trigger("refresh", [collection]) this _.extend Model.Collection.prototype, Model.Events, getUrl: -> "/#{_.pluralize this._name}" add: (records) -> if _.isArray records _.each records, (record) -> this._add record , this else this._add records removeAll: -> this.records = [] #this.remove this.records remove: (records) -> if _.isArray records _.each records, (record) -> this._remove record , this else this._remove records _change: (record) -> self = this _.each record._changes, (value, key) -> index_id = record.tagId() current_model_name = _.pluralize(record._name) name = '[name="' + self.parent()._name + "[#{current_model_name}_attributes][#{index_id}][#{key}]" + '"]' $(name).val value parent: -> this._parent get: (id) -> return null if _.isNull id return this._byId[if !_.isNull id.id then id.id else id] refresh: (records) -> this._reset() this.add(records) this.trigger("refresh", [this]) this fetch: (params) -> this.query(data: params) this findByTagId: (tag_id) -> _.detect this.records, (element) -> element.tagId() == parseInt(tag_id) removeByTagId: (tag_id) -> record = _.detect this.records, (element) -> element.tagId() == parseInt(tag_id) this._remove(record) if record findByUid: (uid) -> _.detect this.records, (record) -> record.uid() == uid removeByUid: (uid) -> record = this.findByUid(uid) this._remove(record) if record query: (options) -> this._options = options or= {} collection = this success = options.success options.success = (resp, status, xhr) -> collection.refresh(resp) success(collection, resp) if success Model.Sync(this, "read", options) this toJSON: -> this._options pluck: (attr) -> _.map this.records, (record) -> record.get attr _add: (record) -> # If a json object is passed, convert to record object unless record._name attr = record record = eval("new #{_.classify this._name}") record._refresh(attr) this._bindRecordEvents(record) record._parent = this.parent() if this.parent() this.records.push record this.length++ this.trigger("add", [record]) record _remove: (record) -> index = this.records.indexOf(record) this.records.splice(index, 1) this.trigger("remove", [record]) # Deprecate this in favor of dispatching a change event after a bind to remove this.trigger("change", [record]) this.length-- _reset: -> this.length = 0 this.records = [] this._byId = {} _bindRecordEvents: (record) -> collection = this record.bind "change", -> collection.trigger "change", [record] # Underscore methods that we want to implement on the Collection. methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size', 'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty'] _.each methods, (method) -> Model.Collection.prototype[method] = -> _[method].apply(_, [this.records].concat(_.toArray(arguments)))
[ { "context": "one\"\n encrypt: true\n name: \"test\"\n proxy: \"http://localdb.emptystack.ne", "end": 211, "score": 0.8587133288383484, "start": 207, "tag": "USERNAME", "value": "test" }, { "context": " 'setItem', ->\n proxy.setItem \"name\...
test/core/proxySpec.coffee
wh1100717/localDB
59
define (require, exports, module) -> 'use strict' Proxy = require('core/proxy') describe 'Proxy', -> options = { expire: "none" encrypt: true name: "test" proxy: "http://localdb.emptystack.net/server.html" } proxy = new Proxy(options) it 'setItem', -> proxy.setItem "name", "Arron", (data) -> console.log("proxy=======>setItem==" + data) it 'key', -> proxy.key 0, (data) -> console.log("proxy=======>key==" + data) it 'size', -> proxy.size (data) -> console.log("proxy=======>size==" + data) it 'getItem', -> proxy.getItem "name", (data) -> console.log("proxy=======>getItem==" + data) it 'removeItem', -> proxy.removeItem "name", (data) -> console.log("proxy=======>removeItem==" + data) it 'usage', -> proxy.usage (data) -> console.log("proxy=======>usage==" + data)
47720
define (require, exports, module) -> 'use strict' Proxy = require('core/proxy') describe 'Proxy', -> options = { expire: "none" encrypt: true name: "test" proxy: "http://localdb.emptystack.net/server.html" } proxy = new Proxy(options) it 'setItem', -> proxy.setItem "name", "Arr<NAME>", (data) -> console.log("proxy=======>setItem==" + data) it 'key', -> proxy.key 0, (data) -> console.log("proxy=======>key==" + data) it 'size', -> proxy.size (data) -> console.log("proxy=======>size==" + data) it 'getItem', -> proxy.getItem "name", (data) -> console.log("proxy=======>getItem==" + data) it 'removeItem', -> proxy.removeItem "name", (data) -> console.log("proxy=======>removeItem==" + data) it 'usage', -> proxy.usage (data) -> console.log("proxy=======>usage==" + data)
true
define (require, exports, module) -> 'use strict' Proxy = require('core/proxy') describe 'Proxy', -> options = { expire: "none" encrypt: true name: "test" proxy: "http://localdb.emptystack.net/server.html" } proxy = new Proxy(options) it 'setItem', -> proxy.setItem "name", "ArrPI:NAME:<NAME>END_PI", (data) -> console.log("proxy=======>setItem==" + data) it 'key', -> proxy.key 0, (data) -> console.log("proxy=======>key==" + data) it 'size', -> proxy.size (data) -> console.log("proxy=======>size==" + data) it 'getItem', -> proxy.getItem "name", (data) -> console.log("proxy=======>getItem==" + data) it 'removeItem', -> proxy.removeItem "name", (data) -> console.log("proxy=======>removeItem==" + data) it 'usage', -> proxy.usage (data) -> console.log("proxy=======>usage==" + data)
[ { "context": "h1 style='font: 300 52px/62px Helvetica Neue'>2007 Cabernet Sauvignon</h1>\n\t\t\"\"\"\n\t\t\n\t\t@titleLayer = new Layer\n\t\t\tparent", "end": 883, "score": 0.9996171593666077, "start": 865, "tag": "NAME", "value": "Cabernet Sauvignon" }, { "context": " i \n\t\tscroll...
snapping-details.framer/app.coffee
bberak/snapping-details
0
# Set background bg = new BackgroundLayer backgroundColor: "#877DD7" # Create ScrollComponent scroll = new ScrollComponent width: bg.width height: bg.height scrollHorizontal: false class Details extends Layer constructor: ({x, y, width, height, scroll, h1, h3, image, borderRadius}) -> super x: x y: y parent: scroll.content width: width height: height backgroundColor: "white" borderRadius: borderRadius clip: true @open = false @originalX = x @originalY = y @originalWidth = width @originalHeight = height @parentScroll = scroll @h1 = h1 @h3 = h3 @picLayer = new Layer parent: this width: @parentScroll.width height: @parentScroll.height image: image titleHtml = """ <h3 style='font: bold 30px/42px Helvetica Neue'>Five Oaks</h3><h1 style='font: 300 52px/62px Helvetica Neue'>2007 Cabernet Sauvignon</h1> """ @titleLayer = new Layer parent: @picLayer y: height - 120 x: 0 width: @picLayer.width html: titleHtml backgroundColor: "transparent" style: paddingLeft: "20px" @picLayer.onClick this.toggle.bind(this) createInfoLayer: () -> infoLayerHtml = """ <h3 style='padding: 0px 0px 0px 10px;font: bold 30px/42px Helvetica Neue; color: #555'>Description</h3> <p style='text-align: justify; padding: 30px 10px 0px 10px; font: normal 30px/42px Helvetica Neue; color: #777'>The wine has a complex fragrant dark fruit nose of ripe blackcurrants, blackberries and black plums, with hints of spice, which is replicated on the concentrated palate.</p> <p style='text-align: justify; padding: 30px 10px 0px 10px; font: normal 30px/42px Helvetica Neue; color: #777'>Fine-grained grape tannins balance the rich flavours and seamlessly integrated elegant French oak tannins, giving the wine a smooth long finish.</p> """ infoLayer = new Layer parent: @parentScroll.content width: @parentScroll.width height: @parentScroll.height y: @parentScroll.scrollY + @parentScroll.height backgroundColor: "#FFF" html: infoLayerHtml style: paddingTop: "20px" paddingLeft: "20px" paddingRight: "20px" return infoLayer toggle: () -> @open = not @open if @open @parentScroll.scrollVertical = false this.bringToFront() this.animate properties: height: @parentScroll.height * 0.7 width: @parentScroll.width x: @parentScroll.scrollX y: @parentScroll.scrollY curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @titleLayer.animate properties: y: (@parentScroll.height * 0.7) - 120 opacity: 1 curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @infoLayer = this.createInfoLayer() @infoLayer.onClick () -> 42 @infoLayer.animate properties: y: @parentScroll.scrollY + (@parentScroll.height * 0.7) opacity: 1 curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 else @parentScroll.scrollVertical = true this.animate properties: height: @originalHeight width: @originalWidth x: @originalX y: @originalY curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @titleLayer.animate properties: y: @originalHeight - 120 opacity: 1 curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @infoLayer.animate properties: y: @parentScroll.scrollY + @parentScroll.height curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @infoLayer.onAnimationEnd (event, layer) -> layer.destroy() # Create 10 detail items for i in [0..10] details = new Details width: scroll.width - 40 height: 280 x: 20 y: 300 * i scroll: scroll h3: "Five Oaks" h1: "2007 Cabernet Sauvignon" image: "http://placekitten.com/g/#{scroll.width}/#{scroll.height}" borderRadius: 0
193521
# Set background bg = new BackgroundLayer backgroundColor: "#877DD7" # Create ScrollComponent scroll = new ScrollComponent width: bg.width height: bg.height scrollHorizontal: false class Details extends Layer constructor: ({x, y, width, height, scroll, h1, h3, image, borderRadius}) -> super x: x y: y parent: scroll.content width: width height: height backgroundColor: "white" borderRadius: borderRadius clip: true @open = false @originalX = x @originalY = y @originalWidth = width @originalHeight = height @parentScroll = scroll @h1 = h1 @h3 = h3 @picLayer = new Layer parent: this width: @parentScroll.width height: @parentScroll.height image: image titleHtml = """ <h3 style='font: bold 30px/42px Helvetica Neue'>Five Oaks</h3><h1 style='font: 300 52px/62px Helvetica Neue'>2007 <NAME></h1> """ @titleLayer = new Layer parent: @picLayer y: height - 120 x: 0 width: @picLayer.width html: titleHtml backgroundColor: "transparent" style: paddingLeft: "20px" @picLayer.onClick this.toggle.bind(this) createInfoLayer: () -> infoLayerHtml = """ <h3 style='padding: 0px 0px 0px 10px;font: bold 30px/42px Helvetica Neue; color: #555'>Description</h3> <p style='text-align: justify; padding: 30px 10px 0px 10px; font: normal 30px/42px Helvetica Neue; color: #777'>The wine has a complex fragrant dark fruit nose of ripe blackcurrants, blackberries and black plums, with hints of spice, which is replicated on the concentrated palate.</p> <p style='text-align: justify; padding: 30px 10px 0px 10px; font: normal 30px/42px Helvetica Neue; color: #777'>Fine-grained grape tannins balance the rich flavours and seamlessly integrated elegant French oak tannins, giving the wine a smooth long finish.</p> """ infoLayer = new Layer parent: @parentScroll.content width: @parentScroll.width height: @parentScroll.height y: @parentScroll.scrollY + @parentScroll.height backgroundColor: "#FFF" html: infoLayerHtml style: paddingTop: "20px" paddingLeft: "20px" paddingRight: "20px" return infoLayer toggle: () -> @open = not @open if @open @parentScroll.scrollVertical = false this.bringToFront() this.animate properties: height: @parentScroll.height * 0.7 width: @parentScroll.width x: @parentScroll.scrollX y: @parentScroll.scrollY curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @titleLayer.animate properties: y: (@parentScroll.height * 0.7) - 120 opacity: 1 curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @infoLayer = this.createInfoLayer() @infoLayer.onClick () -> 42 @infoLayer.animate properties: y: @parentScroll.scrollY + (@parentScroll.height * 0.7) opacity: 1 curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 else @parentScroll.scrollVertical = true this.animate properties: height: @originalHeight width: @originalWidth x: @originalX y: @originalY curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @titleLayer.animate properties: y: @originalHeight - 120 opacity: 1 curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @infoLayer.animate properties: y: @parentScroll.scrollY + @parentScroll.height curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @infoLayer.onAnimationEnd (event, layer) -> layer.destroy() # Create 10 detail items for i in [0..10] details = new Details width: scroll.width - 40 height: 280 x: 20 y: 300 * i scroll: scroll h3: "Five Oaks" h1: "2007 <NAME>" image: "http://placekitten.com/g/#{scroll.width}/#{scroll.height}" borderRadius: 0
true
# Set background bg = new BackgroundLayer backgroundColor: "#877DD7" # Create ScrollComponent scroll = new ScrollComponent width: bg.width height: bg.height scrollHorizontal: false class Details extends Layer constructor: ({x, y, width, height, scroll, h1, h3, image, borderRadius}) -> super x: x y: y parent: scroll.content width: width height: height backgroundColor: "white" borderRadius: borderRadius clip: true @open = false @originalX = x @originalY = y @originalWidth = width @originalHeight = height @parentScroll = scroll @h1 = h1 @h3 = h3 @picLayer = new Layer parent: this width: @parentScroll.width height: @parentScroll.height image: image titleHtml = """ <h3 style='font: bold 30px/42px Helvetica Neue'>Five Oaks</h3><h1 style='font: 300 52px/62px Helvetica Neue'>2007 PI:NAME:<NAME>END_PI</h1> """ @titleLayer = new Layer parent: @picLayer y: height - 120 x: 0 width: @picLayer.width html: titleHtml backgroundColor: "transparent" style: paddingLeft: "20px" @picLayer.onClick this.toggle.bind(this) createInfoLayer: () -> infoLayerHtml = """ <h3 style='padding: 0px 0px 0px 10px;font: bold 30px/42px Helvetica Neue; color: #555'>Description</h3> <p style='text-align: justify; padding: 30px 10px 0px 10px; font: normal 30px/42px Helvetica Neue; color: #777'>The wine has a complex fragrant dark fruit nose of ripe blackcurrants, blackberries and black plums, with hints of spice, which is replicated on the concentrated palate.</p> <p style='text-align: justify; padding: 30px 10px 0px 10px; font: normal 30px/42px Helvetica Neue; color: #777'>Fine-grained grape tannins balance the rich flavours and seamlessly integrated elegant French oak tannins, giving the wine a smooth long finish.</p> """ infoLayer = new Layer parent: @parentScroll.content width: @parentScroll.width height: @parentScroll.height y: @parentScroll.scrollY + @parentScroll.height backgroundColor: "#FFF" html: infoLayerHtml style: paddingTop: "20px" paddingLeft: "20px" paddingRight: "20px" return infoLayer toggle: () -> @open = not @open if @open @parentScroll.scrollVertical = false this.bringToFront() this.animate properties: height: @parentScroll.height * 0.7 width: @parentScroll.width x: @parentScroll.scrollX y: @parentScroll.scrollY curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @titleLayer.animate properties: y: (@parentScroll.height * 0.7) - 120 opacity: 1 curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @infoLayer = this.createInfoLayer() @infoLayer.onClick () -> 42 @infoLayer.animate properties: y: @parentScroll.scrollY + (@parentScroll.height * 0.7) opacity: 1 curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 else @parentScroll.scrollVertical = true this.animate properties: height: @originalHeight width: @originalWidth x: @originalX y: @originalY curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @titleLayer.animate properties: y: @originalHeight - 120 opacity: 1 curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @infoLayer.animate properties: y: @parentScroll.scrollY + @parentScroll.height curve: "spring-rk4" curveOptions: tension: 200, friction: 25, velocity: 10 @infoLayer.onAnimationEnd (event, layer) -> layer.destroy() # Create 10 detail items for i in [0..10] details = new Details width: scroll.width - 40 height: 280 x: 20 y: 300 * i scroll: scroll h3: "Five Oaks" h1: "2007 PI:NAME:<NAME>END_PI" image: "http://placekitten.com/g/#{scroll.width}/#{scroll.height}" borderRadius: 0
[ { "context": "TP POST request to create a manufacturer.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass CreateAircraftM", "end": 161, "score": 0.9998619556427002, "start": 149, "tag": "NAME", "value": "Nathan Klick" } ]
Workspace/QRef/NodeServer/src/specification/request/ajax/CreateAircraftManufacturerAjaxRequest.coffee
qrefdev/qref
0
AjaxRequest = require('../../../serialization/AjaxRequest') ### Object sent as the body of an HTTP POST request to create a manufacturer. @author Nathan Klick @copyright QRef 2012 ### class CreateAircraftManufacturerAjaxRequest extends AjaxRequest ### @property [String] (Required) The name of the manufacturer. ### name: type: String required: true unique: true ### @property [String] (Optional) A detailed description of this manufacturer. ### description: type: String required: false module.exports = CreateAircraftManufacturerAjaxRequest
61727
AjaxRequest = require('../../../serialization/AjaxRequest') ### Object sent as the body of an HTTP POST request to create a manufacturer. @author <NAME> @copyright QRef 2012 ### class CreateAircraftManufacturerAjaxRequest extends AjaxRequest ### @property [String] (Required) The name of the manufacturer. ### name: type: String required: true unique: true ### @property [String] (Optional) A detailed description of this manufacturer. ### description: type: String required: false module.exports = CreateAircraftManufacturerAjaxRequest
true
AjaxRequest = require('../../../serialization/AjaxRequest') ### Object sent as the body of an HTTP POST request to create a manufacturer. @author PI:NAME:<NAME>END_PI @copyright QRef 2012 ### class CreateAircraftManufacturerAjaxRequest extends AjaxRequest ### @property [String] (Required) The name of the manufacturer. ### name: type: String required: true unique: true ### @property [String] (Optional) A detailed description of this manufacturer. ### description: type: String required: false module.exports = CreateAircraftManufacturerAjaxRequest
[ { "context": "ts.HrefVariables()\n hrefVariables.set('name', 'Doe')\n hrefVariables.getMember('name').attributes.", "end": 688, "score": 0.9985744953155518, "start": 685, "tag": "NAME", "value": "Doe" }, { "context": ": {\n default: undefined,\n example: 'Doe',\n ...
test/unit/compile-uri/compile-params-test.coffee
DMG-Cloud-Services/adsk-dredd-transactions
0
{assert} = require 'chai' fury = new require 'adsk-fury' compileParams = require '../../../src/compile-uri/compile-params' describe 'compileParams', -> it 'should compile a primitive href variable', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('name', new fury.minim.elements.String()) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { name: { default: undefined, example: undefined, required: false, values: [] } }) it 'should compile a required href variable', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('name', 'Doe') hrefVariables.getMember('name').attributes.set('typeAttributes', ['required']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { name: { default: undefined, example: 'Doe', required: true, values: [] } }) it 'should compile a primitive href variable with value', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('name', 'Doe') parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { name: { default: undefined, example: 'Doe', required: false, values: [] } }) it 'should compile a primitive href variable with default', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('name', new fury.minim.elements.String()) hrefVariables.get('name').attributes.set('default', 'Unknown') parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { name: { default: 'Unknown', example: undefined, required: false, values: [] } }) it 'should compile an array href variable', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', []) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: undefined, example: [], required: false, values: [] } }) it 'should compile an array href variable with values', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', ['One', 'Two']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: undefined, example: ['One', 'Two'], required: false, values: [] } }) it 'should compile an array href variable with default', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', []) hrefVariables.get('names').attributes.set('default', ['Unknown']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: ['Unknown'], example: [], required: false, values: [] } }) it 'should compile an array href variable with values', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', ['One', 'Two']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: undefined, example: ['One', 'Two'], required: false, values: [] } }) it 'should compile an array href variable with default', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', []) hrefVariables.get('names').attributes.set('default', ['Unknown']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: ['Unknown'], example: [], required: false, values: [] } }) it 'should compile an enum href variable', -> hrefVariables = new fury.minim.elements.HrefVariables() value = new fury.minim.elements.Element() value.element = 'enum' value.attributes.set('enumerations', ['ascending', 'decending']) hrefVariables.set('order', value) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { order: { default: undefined, example: 'ascending', required: false, values: ['ascending', 'decending'] } }) it 'should compile an enum href variable with values', -> hrefVariables = new fury.minim.elements.HrefVariables() value = new fury.minim.elements.Element('decending') value.element = 'enum' value.attributes.set('enumerations', ['ascending', 'decending']) hrefVariables.set('order', value) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { order: { default: undefined, example: 'decending', required: false, values: ['ascending', 'decending'] } }) it 'should compile an enum href variable with default', -> hrefVariables = new fury.minim.elements.HrefVariables() value = new fury.minim.elements.Element() value.element = 'enum' value.attributes.set('enumerations', ['ascending', 'decending']) value.attributes.set('default', 'decending') hrefVariables.set('order', value) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { order: { default: 'decending', example: 'ascending', required: false, values: ['ascending', 'decending'] } })
12500
{assert} = require 'chai' fury = new require 'adsk-fury' compileParams = require '../../../src/compile-uri/compile-params' describe 'compileParams', -> it 'should compile a primitive href variable', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('name', new fury.minim.elements.String()) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { name: { default: undefined, example: undefined, required: false, values: [] } }) it 'should compile a required href variable', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('name', '<NAME>') hrefVariables.getMember('name').attributes.set('typeAttributes', ['required']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { name: { default: undefined, example: '<NAME>', required: true, values: [] } }) it 'should compile a primitive href variable with value', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('name', '<NAME>') parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { name: { default: undefined, example: '<NAME>', required: false, values: [] } }) it 'should compile a primitive href variable with default', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('name', new fury.minim.elements.String()) hrefVariables.get('name').attributes.set('default', 'Unknown') parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { name: { default: 'Unknown', example: undefined, required: false, values: [] } }) it 'should compile an array href variable', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', []) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: undefined, example: [], required: false, values: [] } }) it 'should compile an array href variable with values', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', ['One', 'Two']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: undefined, example: ['One', 'Two'], required: false, values: [] } }) it 'should compile an array href variable with default', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', []) hrefVariables.get('names').attributes.set('default', ['Unknown']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: ['Unknown'], example: [], required: false, values: [] } }) it 'should compile an array href variable with values', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', ['One', 'Two']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: undefined, example: ['One', 'Two'], required: false, values: [] } }) it 'should compile an array href variable with default', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', []) hrefVariables.get('names').attributes.set('default', ['Unknown']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: ['Unknown'], example: [], required: false, values: [] } }) it 'should compile an enum href variable', -> hrefVariables = new fury.minim.elements.HrefVariables() value = new fury.minim.elements.Element() value.element = 'enum' value.attributes.set('enumerations', ['ascending', 'decending']) hrefVariables.set('order', value) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { order: { default: undefined, example: 'ascending', required: false, values: ['ascending', 'decending'] } }) it 'should compile an enum href variable with values', -> hrefVariables = new fury.minim.elements.HrefVariables() value = new fury.minim.elements.Element('decending') value.element = 'enum' value.attributes.set('enumerations', ['ascending', 'decending']) hrefVariables.set('order', value) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { order: { default: undefined, example: 'decending', required: false, values: ['ascending', 'decending'] } }) it 'should compile an enum href variable with default', -> hrefVariables = new fury.minim.elements.HrefVariables() value = new fury.minim.elements.Element() value.element = 'enum' value.attributes.set('enumerations', ['ascending', 'decending']) value.attributes.set('default', 'decending') hrefVariables.set('order', value) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { order: { default: 'decending', example: 'ascending', required: false, values: ['ascending', 'decending'] } })
true
{assert} = require 'chai' fury = new require 'adsk-fury' compileParams = require '../../../src/compile-uri/compile-params' describe 'compileParams', -> it 'should compile a primitive href variable', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('name', new fury.minim.elements.String()) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { name: { default: undefined, example: undefined, required: false, values: [] } }) it 'should compile a required href variable', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('name', 'PI:NAME:<NAME>END_PI') hrefVariables.getMember('name').attributes.set('typeAttributes', ['required']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { name: { default: undefined, example: 'PI:NAME:<NAME>END_PI', required: true, values: [] } }) it 'should compile a primitive href variable with value', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('name', 'PI:NAME:<NAME>END_PI') parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { name: { default: undefined, example: 'PI:NAME:<NAME>END_PI', required: false, values: [] } }) it 'should compile a primitive href variable with default', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('name', new fury.minim.elements.String()) hrefVariables.get('name').attributes.set('default', 'Unknown') parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { name: { default: 'Unknown', example: undefined, required: false, values: [] } }) it 'should compile an array href variable', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', []) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: undefined, example: [], required: false, values: [] } }) it 'should compile an array href variable with values', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', ['One', 'Two']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: undefined, example: ['One', 'Two'], required: false, values: [] } }) it 'should compile an array href variable with default', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', []) hrefVariables.get('names').attributes.set('default', ['Unknown']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: ['Unknown'], example: [], required: false, values: [] } }) it 'should compile an array href variable with values', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', ['One', 'Two']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: undefined, example: ['One', 'Two'], required: false, values: [] } }) it 'should compile an array href variable with default', -> hrefVariables = new fury.minim.elements.HrefVariables() hrefVariables.set('names', []) hrefVariables.get('names').attributes.set('default', ['Unknown']) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { names: { default: ['Unknown'], example: [], required: false, values: [] } }) it 'should compile an enum href variable', -> hrefVariables = new fury.minim.elements.HrefVariables() value = new fury.minim.elements.Element() value.element = 'enum' value.attributes.set('enumerations', ['ascending', 'decending']) hrefVariables.set('order', value) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { order: { default: undefined, example: 'ascending', required: false, values: ['ascending', 'decending'] } }) it 'should compile an enum href variable with values', -> hrefVariables = new fury.minim.elements.HrefVariables() value = new fury.minim.elements.Element('decending') value.element = 'enum' value.attributes.set('enumerations', ['ascending', 'decending']) hrefVariables.set('order', value) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { order: { default: undefined, example: 'decending', required: false, values: ['ascending', 'decending'] } }) it 'should compile an enum href variable with default', -> hrefVariables = new fury.minim.elements.HrefVariables() value = new fury.minim.elements.Element() value.element = 'enum' value.attributes.set('enumerations', ['ascending', 'decending']) value.attributes.set('default', 'decending') hrefVariables.set('order', value) parameters = compileParams(hrefVariables) assert.deepEqual(parameters, { order: { default: 'decending', example: 'ascending', required: false, values: ['ascending', 'decending'] } })
[ { "context": "sl(a) or rgb(a) as input, outputs rgb(a)\n# author: Valerio Proietti (@kamicane) http://mad4milk.net http://mootools.n", "end": 125, "score": 0.9998679161071777, "start": 109, "tag": "NAME", "value": "Valerio Proietti" }, { "context": "s input, outputs rgb(a)\n# author:...
src/color.coffee
sebmarkbage/moofx
2
# color: A color converter. Takes a named color, hex(a), hsl(a) or rgb(a) as input, outputs rgb(a) # author: Valerio Proietti (@kamicane) http://mad4milk.net http://mootools.net # credits: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript # license: MIT colors = maroon: '#800000', red: '#ff0000', orange: '#ffA500', yellow: '#ffff00', olive: '#808000' purple: '#800080', fuchsia: "#ff00ff", white: '#ffffff', lime: '#00ff00', green: '#008000' navy: '#000080', blue: '#0000ff', aqua: '#00ffff', teal: '#008080', black: '#000000', silver: '#c0c0c0', gray: '#808080' RGBtoRGB = (r, g, b, a = 1) -> if (r > 255 or r < 0) or (g > 255 or g < 0) or (b > 255 or b < 0) or (a > 255 or a < 0) then null; else [Math.round(r), Math.round(g), Math.round(b), parseFloat(a)] HEXtoRGB = (hex) -> if hex.length is 3 then hex += 'f' if hex.length is 4 h0 = hex.charAt(0) h1 = hex.charAt(1) h2 = hex.charAt(2) h3 = hex.charAt(3) hex = h0 + h0 + h1 + h1 + h2 + h2 + h3 + h3 if hex.length is 6 then hex +='ff' parseInt(hex.substr(i, 2), 16) / (if i is 6 then 255 else 1) for i in [0..hex.length] by 2 HUEtoRGB = (p, q, t) -> if t < 0 then t += 1 if t > 1 then t -= 1 if t < 1/6 then return p + (q - p) * 6 * t if t < 1/2 then return q if t < 2/3 then return p + (q - p) * (2/3 - t) * 6 p HSLtoRGB = (h, s, l, a = 1) -> h /= 360 s /= 100 l /= 100 if (h > 1 or h < 0) or (s > 1 or s < 0) or (l > 1 or l < 0) or (a > 1 or a < 0) then return null if s is 0 then r = b = g = l else q = if l < 0.5 then l * (1 + s) else l + s - l * s p = 2 * l - q r = HUEtoRGB(p, q, h + 1/3) g = HUEtoRGB(p, q, h) b = HUEtoRGB(p, q, h - 1/3) [r * 255, g * 255, b * 255, parseFloat(a)] moofx.color = (input, array) -> input = colors[input = input.replace(/\s+/g, '')] or input if input.match(/^#[a-f0-9]{3,8}/) then input = HEXtoRGB(input.replace('#', '')) else if match = input.match(/([\d.])+/g) if input.match(/^rgb/) then input = match else if input.match(/^hsl/) then input = HSLtoRGB(match...) return null unless input and input = RGBtoRGB(input...) return input if array input.splice(3, 1) if input[3] is 1 "rgb#{if input.length > 3 then 'a' else ''}(#{input})"
166969
# color: A color converter. Takes a named color, hex(a), hsl(a) or rgb(a) as input, outputs rgb(a) # author: <NAME> (@kamicane) http://mad4milk.net http://mootools.net # credits: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript # license: MIT colors = maroon: '#800000', red: '#ff0000', orange: '#ffA500', yellow: '#ffff00', olive: '#808000' purple: '#800080', fuchsia: "#ff00ff", white: '#ffffff', lime: '#00ff00', green: '#008000' navy: '#000080', blue: '#0000ff', aqua: '#00ffff', teal: '#008080', black: '#000000', silver: '#c0c0c0', gray: '#808080' RGBtoRGB = (r, g, b, a = 1) -> if (r > 255 or r < 0) or (g > 255 or g < 0) or (b > 255 or b < 0) or (a > 255 or a < 0) then null; else [Math.round(r), Math.round(g), Math.round(b), parseFloat(a)] HEXtoRGB = (hex) -> if hex.length is 3 then hex += 'f' if hex.length is 4 h0 = hex.charAt(0) h1 = hex.charAt(1) h2 = hex.charAt(2) h3 = hex.charAt(3) hex = h0 + h0 + h1 + h1 + h2 + h2 + h3 + h3 if hex.length is 6 then hex +='ff' parseInt(hex.substr(i, 2), 16) / (if i is 6 then 255 else 1) for i in [0..hex.length] by 2 HUEtoRGB = (p, q, t) -> if t < 0 then t += 1 if t > 1 then t -= 1 if t < 1/6 then return p + (q - p) * 6 * t if t < 1/2 then return q if t < 2/3 then return p + (q - p) * (2/3 - t) * 6 p HSLtoRGB = (h, s, l, a = 1) -> h /= 360 s /= 100 l /= 100 if (h > 1 or h < 0) or (s > 1 or s < 0) or (l > 1 or l < 0) or (a > 1 or a < 0) then return null if s is 0 then r = b = g = l else q = if l < 0.5 then l * (1 + s) else l + s - l * s p = 2 * l - q r = HUEtoRGB(p, q, h + 1/3) g = HUEtoRGB(p, q, h) b = HUEtoRGB(p, q, h - 1/3) [r * 255, g * 255, b * 255, parseFloat(a)] moofx.color = (input, array) -> input = colors[input = input.replace(/\s+/g, '')] or input if input.match(/^#[a-f0-9]{3,8}/) then input = HEXtoRGB(input.replace('#', '')) else if match = input.match(/([\d.])+/g) if input.match(/^rgb/) then input = match else if input.match(/^hsl/) then input = HSLtoRGB(match...) return null unless input and input = RGBtoRGB(input...) return input if array input.splice(3, 1) if input[3] is 1 "rgb#{if input.length > 3 then 'a' else ''}(#{input})"
true
# color: A color converter. Takes a named color, hex(a), hsl(a) or rgb(a) as input, outputs rgb(a) # author: PI:NAME:<NAME>END_PI (@kamicane) http://mad4milk.net http://mootools.net # credits: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript # license: MIT colors = maroon: '#800000', red: '#ff0000', orange: '#ffA500', yellow: '#ffff00', olive: '#808000' purple: '#800080', fuchsia: "#ff00ff", white: '#ffffff', lime: '#00ff00', green: '#008000' navy: '#000080', blue: '#0000ff', aqua: '#00ffff', teal: '#008080', black: '#000000', silver: '#c0c0c0', gray: '#808080' RGBtoRGB = (r, g, b, a = 1) -> if (r > 255 or r < 0) or (g > 255 or g < 0) or (b > 255 or b < 0) or (a > 255 or a < 0) then null; else [Math.round(r), Math.round(g), Math.round(b), parseFloat(a)] HEXtoRGB = (hex) -> if hex.length is 3 then hex += 'f' if hex.length is 4 h0 = hex.charAt(0) h1 = hex.charAt(1) h2 = hex.charAt(2) h3 = hex.charAt(3) hex = h0 + h0 + h1 + h1 + h2 + h2 + h3 + h3 if hex.length is 6 then hex +='ff' parseInt(hex.substr(i, 2), 16) / (if i is 6 then 255 else 1) for i in [0..hex.length] by 2 HUEtoRGB = (p, q, t) -> if t < 0 then t += 1 if t > 1 then t -= 1 if t < 1/6 then return p + (q - p) * 6 * t if t < 1/2 then return q if t < 2/3 then return p + (q - p) * (2/3 - t) * 6 p HSLtoRGB = (h, s, l, a = 1) -> h /= 360 s /= 100 l /= 100 if (h > 1 or h < 0) or (s > 1 or s < 0) or (l > 1 or l < 0) or (a > 1 or a < 0) then return null if s is 0 then r = b = g = l else q = if l < 0.5 then l * (1 + s) else l + s - l * s p = 2 * l - q r = HUEtoRGB(p, q, h + 1/3) g = HUEtoRGB(p, q, h) b = HUEtoRGB(p, q, h - 1/3) [r * 255, g * 255, b * 255, parseFloat(a)] moofx.color = (input, array) -> input = colors[input = input.replace(/\s+/g, '')] or input if input.match(/^#[a-f0-9]{3,8}/) then input = HEXtoRGB(input.replace('#', '')) else if match = input.match(/([\d.])+/g) if input.match(/^rgb/) then input = match else if input.match(/^hsl/) then input = HSLtoRGB(match...) return null unless input and input = RGBtoRGB(input...) return input if array input.splice(3, 1) if input[3] is 1 "rgb#{if input.length > 3 then 'a' else ''}(#{input})"
[ { "context": "# @file particle.coffee\n# @Copyright (c) 2017 Taylor Siviter\n# This source code is licensed under the MIT Lice", "end": 60, "score": 0.9998103976249695, "start": 46, "tag": "NAME", "value": "Taylor Siviter" } ]
src/particle/particle.coffee
siviter-t/lampyridae.coffee
4
# @file particle.coffee # @Copyright (c) 2017 Taylor Siviter # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. require 'maths/vec2d' class Lampyridae.Particle ### Construct and manage a generic circular particle. # # @param canvas [Object] Instance of Lampyridae.Canvas to attach the particle to # # @option x [Number] Position of the particle along the x-axis # @option y [Number] Position of the particle along the y-axis # @option vx [Number] Velocity of the particle along the x-axis # @option vy [Number] Velocity of the particle along the y-axis # @option radius [Number] Radius of the particle # @option bound [String] Type of bounding [none|hard|periodic] # @option alpha [Number] Opacity of the particle (requires enableAlpha) # @option glow [Number] Factor of the radius to emit a glow effect (requires enableGlow) # @option colour [String] Colour code to fill particle: e.g. "rgb(70, 70, 70)" or "0" = none # @option stroke [Number] Width of the stroke [default: 0] # @option strokeColour [String] Colour of the stroke [default: @colour] ### constructor: (@canvas, options) -> unless arguments.length > 0 throw new Error "Particle requires a valid Canvas instance to be attached to" options ?= {} if toString.call(options) isnt '[object Object]' throw new Error "Particle requires a valid options object" # Mechanical properties # @pos = new Lampyridae.Vec2D options.x ? 0.0, options.y ? 0.0 @vel = new Lampyridae.Vec2D options.vx ? 0.0, options.vy ? 0.0 @r = options.radius ? 1.0 @bounded = false @periodic = false if options.bound? switch options.bound when "hard" then @bounded = true when "periodic" then @bounded = true; @periodic = true when "none" else console.warn "Bound #{options.bound} is not valid. Defaulting to 'none'" # Drawing properties # @glow = options.glow ? 0.0 @alpha = options.alpha ? 1.0 @colour = options.colour ? "rgb(255, 255, 255)" @stroke = options.stroke ? 0 @strokeColour = options.strokeColour ? @colour @glowColour = options.glowColour ? @colour # Temporary calculation variables # @_v = new Lampyridae.Vec2D 0.0, 0.0 ### Particle class prototype parameters. # Can be set by the user; e.g. Lampyridae.Particle::enableGlow = true, etc. ### enableAlpha: false enableGlow: false # Movement methods # ### Turn the particle's velocity! # # @param angle [Number] Number of radians to turn anticlockwise from the x-axis ### turn: (angle = 0.0) -> @vel.rotate(angle) # Detection and boundary methods # ### Is the particle outside the canvas in the x-axis? ### isOutsideCanvasX: () -> unless 0.0 + @r <= @pos.x <= @canvas.width() - @r then return true return false ### Is the particle outside the canvas in the y-axis? ### isOutsideCanvasY: () -> unless 0.0 + @r <= @pos.y <= @canvas.height() - @r then return true return false ### Is the particle outside the canvas window? ### isOutsideCanvas: () -> return @isOutsideCanvasX() or @isOutsideCanvasY() ### Act as if the boundary of the canvas is 'hard-walled'. ### applyHardBounds: () -> result = false if @isOutsideCanvasX() then @vel.normalLeft() ; @acc.normalLeft() ; result = true if @isOutsideCanvasY() then @vel.normalRight() ; @acc.normalRight() ; result = true return result ### Act as if the boundary of the canvas is 'periodic'. ### applyPeriodicBounds: () -> result = false if @isOutsideCanvasX() then @pos.x = -@pos.x + @canvas.width() ; result = true if @isOutsideCanvasY() then @pos.y = -@pos.y + @canvas.height() ; result = true return result ### Check and act if there are bounds applied. ### applyBounds: () -> if @periodic then return @applyPeriodicBounds() if @bounded then return @applyHardBounds() return false ### Move the particle using its velocity in the defined time step. ### move: () -> @pos.add @_v.copy(@vel).scale(Lampyridae.timestep) ### Simple particle update method. ### update: () -> @applyBounds() @move() @draw() ### Draw the particle to the screen. # Alpha and glow can be toggled by proto members # Fill and stroke can be toggled by instance members ### draw: () -> @canvas.draw.begin() if @enableAlpha then @canvas.draw.setGlobalAlpha @alpha if @enableGlow then @canvas.draw.glow @glow * @r, @glowColour @canvas.draw.circle @pos.x, @pos.y, @r unless @colour == 0 then @canvas.draw.fill @colour if @stroke > 0 then @canvas.draw.stroke @stroke, @strokeColour @canvas.draw.end() # end class Lampyridae.Particle module.exports = Lampyridae.Particle
213605
# @file particle.coffee # @Copyright (c) 2017 <NAME> # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. require 'maths/vec2d' class Lampyridae.Particle ### Construct and manage a generic circular particle. # # @param canvas [Object] Instance of Lampyridae.Canvas to attach the particle to # # @option x [Number] Position of the particle along the x-axis # @option y [Number] Position of the particle along the y-axis # @option vx [Number] Velocity of the particle along the x-axis # @option vy [Number] Velocity of the particle along the y-axis # @option radius [Number] Radius of the particle # @option bound [String] Type of bounding [none|hard|periodic] # @option alpha [Number] Opacity of the particle (requires enableAlpha) # @option glow [Number] Factor of the radius to emit a glow effect (requires enableGlow) # @option colour [String] Colour code to fill particle: e.g. "rgb(70, 70, 70)" or "0" = none # @option stroke [Number] Width of the stroke [default: 0] # @option strokeColour [String] Colour of the stroke [default: @colour] ### constructor: (@canvas, options) -> unless arguments.length > 0 throw new Error "Particle requires a valid Canvas instance to be attached to" options ?= {} if toString.call(options) isnt '[object Object]' throw new Error "Particle requires a valid options object" # Mechanical properties # @pos = new Lampyridae.Vec2D options.x ? 0.0, options.y ? 0.0 @vel = new Lampyridae.Vec2D options.vx ? 0.0, options.vy ? 0.0 @r = options.radius ? 1.0 @bounded = false @periodic = false if options.bound? switch options.bound when "hard" then @bounded = true when "periodic" then @bounded = true; @periodic = true when "none" else console.warn "Bound #{options.bound} is not valid. Defaulting to 'none'" # Drawing properties # @glow = options.glow ? 0.0 @alpha = options.alpha ? 1.0 @colour = options.colour ? "rgb(255, 255, 255)" @stroke = options.stroke ? 0 @strokeColour = options.strokeColour ? @colour @glowColour = options.glowColour ? @colour # Temporary calculation variables # @_v = new Lampyridae.Vec2D 0.0, 0.0 ### Particle class prototype parameters. # Can be set by the user; e.g. Lampyridae.Particle::enableGlow = true, etc. ### enableAlpha: false enableGlow: false # Movement methods # ### Turn the particle's velocity! # # @param angle [Number] Number of radians to turn anticlockwise from the x-axis ### turn: (angle = 0.0) -> @vel.rotate(angle) # Detection and boundary methods # ### Is the particle outside the canvas in the x-axis? ### isOutsideCanvasX: () -> unless 0.0 + @r <= @pos.x <= @canvas.width() - @r then return true return false ### Is the particle outside the canvas in the y-axis? ### isOutsideCanvasY: () -> unless 0.0 + @r <= @pos.y <= @canvas.height() - @r then return true return false ### Is the particle outside the canvas window? ### isOutsideCanvas: () -> return @isOutsideCanvasX() or @isOutsideCanvasY() ### Act as if the boundary of the canvas is 'hard-walled'. ### applyHardBounds: () -> result = false if @isOutsideCanvasX() then @vel.normalLeft() ; @acc.normalLeft() ; result = true if @isOutsideCanvasY() then @vel.normalRight() ; @acc.normalRight() ; result = true return result ### Act as if the boundary of the canvas is 'periodic'. ### applyPeriodicBounds: () -> result = false if @isOutsideCanvasX() then @pos.x = -@pos.x + @canvas.width() ; result = true if @isOutsideCanvasY() then @pos.y = -@pos.y + @canvas.height() ; result = true return result ### Check and act if there are bounds applied. ### applyBounds: () -> if @periodic then return @applyPeriodicBounds() if @bounded then return @applyHardBounds() return false ### Move the particle using its velocity in the defined time step. ### move: () -> @pos.add @_v.copy(@vel).scale(Lampyridae.timestep) ### Simple particle update method. ### update: () -> @applyBounds() @move() @draw() ### Draw the particle to the screen. # Alpha and glow can be toggled by proto members # Fill and stroke can be toggled by instance members ### draw: () -> @canvas.draw.begin() if @enableAlpha then @canvas.draw.setGlobalAlpha @alpha if @enableGlow then @canvas.draw.glow @glow * @r, @glowColour @canvas.draw.circle @pos.x, @pos.y, @r unless @colour == 0 then @canvas.draw.fill @colour if @stroke > 0 then @canvas.draw.stroke @stroke, @strokeColour @canvas.draw.end() # end class Lampyridae.Particle module.exports = Lampyridae.Particle
true
# @file particle.coffee # @Copyright (c) 2017 PI:NAME:<NAME>END_PI # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. require 'maths/vec2d' class Lampyridae.Particle ### Construct and manage a generic circular particle. # # @param canvas [Object] Instance of Lampyridae.Canvas to attach the particle to # # @option x [Number] Position of the particle along the x-axis # @option y [Number] Position of the particle along the y-axis # @option vx [Number] Velocity of the particle along the x-axis # @option vy [Number] Velocity of the particle along the y-axis # @option radius [Number] Radius of the particle # @option bound [String] Type of bounding [none|hard|periodic] # @option alpha [Number] Opacity of the particle (requires enableAlpha) # @option glow [Number] Factor of the radius to emit a glow effect (requires enableGlow) # @option colour [String] Colour code to fill particle: e.g. "rgb(70, 70, 70)" or "0" = none # @option stroke [Number] Width of the stroke [default: 0] # @option strokeColour [String] Colour of the stroke [default: @colour] ### constructor: (@canvas, options) -> unless arguments.length > 0 throw new Error "Particle requires a valid Canvas instance to be attached to" options ?= {} if toString.call(options) isnt '[object Object]' throw new Error "Particle requires a valid options object" # Mechanical properties # @pos = new Lampyridae.Vec2D options.x ? 0.0, options.y ? 0.0 @vel = new Lampyridae.Vec2D options.vx ? 0.0, options.vy ? 0.0 @r = options.radius ? 1.0 @bounded = false @periodic = false if options.bound? switch options.bound when "hard" then @bounded = true when "periodic" then @bounded = true; @periodic = true when "none" else console.warn "Bound #{options.bound} is not valid. Defaulting to 'none'" # Drawing properties # @glow = options.glow ? 0.0 @alpha = options.alpha ? 1.0 @colour = options.colour ? "rgb(255, 255, 255)" @stroke = options.stroke ? 0 @strokeColour = options.strokeColour ? @colour @glowColour = options.glowColour ? @colour # Temporary calculation variables # @_v = new Lampyridae.Vec2D 0.0, 0.0 ### Particle class prototype parameters. # Can be set by the user; e.g. Lampyridae.Particle::enableGlow = true, etc. ### enableAlpha: false enableGlow: false # Movement methods # ### Turn the particle's velocity! # # @param angle [Number] Number of radians to turn anticlockwise from the x-axis ### turn: (angle = 0.0) -> @vel.rotate(angle) # Detection and boundary methods # ### Is the particle outside the canvas in the x-axis? ### isOutsideCanvasX: () -> unless 0.0 + @r <= @pos.x <= @canvas.width() - @r then return true return false ### Is the particle outside the canvas in the y-axis? ### isOutsideCanvasY: () -> unless 0.0 + @r <= @pos.y <= @canvas.height() - @r then return true return false ### Is the particle outside the canvas window? ### isOutsideCanvas: () -> return @isOutsideCanvasX() or @isOutsideCanvasY() ### Act as if the boundary of the canvas is 'hard-walled'. ### applyHardBounds: () -> result = false if @isOutsideCanvasX() then @vel.normalLeft() ; @acc.normalLeft() ; result = true if @isOutsideCanvasY() then @vel.normalRight() ; @acc.normalRight() ; result = true return result ### Act as if the boundary of the canvas is 'periodic'. ### applyPeriodicBounds: () -> result = false if @isOutsideCanvasX() then @pos.x = -@pos.x + @canvas.width() ; result = true if @isOutsideCanvasY() then @pos.y = -@pos.y + @canvas.height() ; result = true return result ### Check and act if there are bounds applied. ### applyBounds: () -> if @periodic then return @applyPeriodicBounds() if @bounded then return @applyHardBounds() return false ### Move the particle using its velocity in the defined time step. ### move: () -> @pos.add @_v.copy(@vel).scale(Lampyridae.timestep) ### Simple particle update method. ### update: () -> @applyBounds() @move() @draw() ### Draw the particle to the screen. # Alpha and glow can be toggled by proto members # Fill and stroke can be toggled by instance members ### draw: () -> @canvas.draw.begin() if @enableAlpha then @canvas.draw.setGlobalAlpha @alpha if @enableGlow then @canvas.draw.glow @glow * @r, @glowColour @canvas.draw.circle @pos.x, @pos.y, @r unless @colour == 0 then @canvas.draw.fill @colour if @stroke > 0 then @canvas.draw.stroke @stroke, @strokeColour @canvas.draw.end() # end class Lampyridae.Particle module.exports = Lampyridae.Particle
[ { "context": "s/icons/heroku@2x.png'\n\n @_fields.push\n key: 'webhookUrl'\n type: 'text'\n readonly: true\n descr", "end": 1116, "score": 0.6921895742416382, "start": 1109, "tag": "KEY", "value": "webhook" } ]
src/services/heroku.coffee
jianliaoim/talk-services
40
_ = require 'lodash' Promise = require 'bluebird' util = require '../util' ###* * Define handler when receive incoming webhook from heroku * @param {Object} req Express request object * @param {Object} res Express response object * @param {Function} callback * @return {Promise} ### _receiveWebhook = ({body}) -> payload = body return unless payload message = attachments: [ category: 'quote' data: redirectUrl: payload.url text: """ #{ payload.user } deployed version #{ payload.head }, git log: #{ payload.git_log } """ title: "#{ payload.app }" ] message module.exports = -> @title = 'Heroku' @template = 'webhook' @summary = util.i18n zh: '支持多种编程语言的云平台即服务。' en: 'A cloud platform as a service (PaaS).' @description = util.i18n zh: 'Heroku 是支持多种编程语言的云平台即服务(PaaS)。接入后可以收到部署的通知。' en: 'Heroku is a cloud platform as a service (PaaS) supporting several programming languages.' @iconUrl = util.static 'images/icons/heroku@2x.png' @_fields.push key: 'webhookUrl' type: 'text' readonly: true description: util.i18n zh: '复制 web hook 地址到你的 Heroku 中使用。' en: 'Copy this web hook to your Heroku account to use it.' # Apply function on `webhook` event @registerEvent 'service.webhook', _receiveWebhook
200626
_ = require 'lodash' Promise = require 'bluebird' util = require '../util' ###* * Define handler when receive incoming webhook from heroku * @param {Object} req Express request object * @param {Object} res Express response object * @param {Function} callback * @return {Promise} ### _receiveWebhook = ({body}) -> payload = body return unless payload message = attachments: [ category: 'quote' data: redirectUrl: payload.url text: """ #{ payload.user } deployed version #{ payload.head }, git log: #{ payload.git_log } """ title: "#{ payload.app }" ] message module.exports = -> @title = 'Heroku' @template = 'webhook' @summary = util.i18n zh: '支持多种编程语言的云平台即服务。' en: 'A cloud platform as a service (PaaS).' @description = util.i18n zh: 'Heroku 是支持多种编程语言的云平台即服务(PaaS)。接入后可以收到部署的通知。' en: 'Heroku is a cloud platform as a service (PaaS) supporting several programming languages.' @iconUrl = util.static 'images/icons/heroku@2x.png' @_fields.push key: '<KEY>Url' type: 'text' readonly: true description: util.i18n zh: '复制 web hook 地址到你的 Heroku 中使用。' en: 'Copy this web hook to your Heroku account to use it.' # Apply function on `webhook` event @registerEvent 'service.webhook', _receiveWebhook
true
_ = require 'lodash' Promise = require 'bluebird' util = require '../util' ###* * Define handler when receive incoming webhook from heroku * @param {Object} req Express request object * @param {Object} res Express response object * @param {Function} callback * @return {Promise} ### _receiveWebhook = ({body}) -> payload = body return unless payload message = attachments: [ category: 'quote' data: redirectUrl: payload.url text: """ #{ payload.user } deployed version #{ payload.head }, git log: #{ payload.git_log } """ title: "#{ payload.app }" ] message module.exports = -> @title = 'Heroku' @template = 'webhook' @summary = util.i18n zh: '支持多种编程语言的云平台即服务。' en: 'A cloud platform as a service (PaaS).' @description = util.i18n zh: 'Heroku 是支持多种编程语言的云平台即服务(PaaS)。接入后可以收到部署的通知。' en: 'Heroku is a cloud platform as a service (PaaS) supporting several programming languages.' @iconUrl = util.static 'images/icons/heroku@2x.png' @_fields.push key: 'PI:KEY:<KEY>END_PIUrl' type: 'text' readonly: true description: util.i18n zh: '复制 web hook 地址到你的 Heroku 中使用。' en: 'Copy this web hook to your Heroku account to use it.' # Apply function on `webhook` event @registerEvent 'service.webhook', _receiveWebhook
[ { "context": "nd query', ->\n kb = Prolog.parseKb \"father(abraham, isaac).\n father(haran, lot).\n ", "end": 968, "score": 0.784266471862793, "start": 961, "tag": "NAME", "value": "abraham" }, { "context": "', ->\n kb = Prolog.parseKb \"father(abraham...
test/simple.coffee
mattsouth/dprolog
7
should = require('chai').should() Prolog = require '../src/simple' describe 'Parser', -> it 'should parse a fact', -> kb = Prolog.parseKb "likes(X, pomegranate)." kb.should.have.length 1 kb[0].head.functor.should.equal "likes" kb[0].head.params.should.have.length 2 kb[0].head.params[0].name.should.equal "X" kb[0].head.params[1].functor.should.equal "pomegranate" it 'should parse a rule', -> kb = Prolog.parseKb "likes(X, Z) :- likes(X, Y), likes(Y, Z)." kb.should.have.length 1 kb[0].body.should.have.length 2 kb[0].body[1].functor.should.equal "likes" kb[0].body[1].params.should.have.length 2 kb[0].body[1].params[1].name.should.equal "Z" it 'should parse a query', -> q = Prolog.parseQuery 'a' q.functor.should.equal "a" describe 'Simple', -> it 'should correctly answer ground query', -> kb = Prolog.parseKb "father(abraham, isaac). father(haran, lot). father(haran, milcah). father(haran, yischa). male(isaac). male(lot). female(milcah). female(yiscah). son(X, Y) :- father(Y, X), male(X). daughter(X, Y) :- father(Y, X), female(X)." query = Prolog.parseQuery "son(lot, haran)" Prolog.solve(query, kb).should.equal true query = Prolog.parseQuery "son(milcah, haran)" Prolog.solve(query, kb).should.equal false it 'shouldnt accept a non-ground query', -> kb = Prolog.parseKb "resistor(power, n1(2))." query = Prolog.parseQuery "resistor(power, n1(X))" try Prolog.solve(query, kb) catch e e.should.equal 'cannot interpret a non-ground query'
90480
should = require('chai').should() Prolog = require '../src/simple' describe 'Parser', -> it 'should parse a fact', -> kb = Prolog.parseKb "likes(X, pomegranate)." kb.should.have.length 1 kb[0].head.functor.should.equal "likes" kb[0].head.params.should.have.length 2 kb[0].head.params[0].name.should.equal "X" kb[0].head.params[1].functor.should.equal "pomegranate" it 'should parse a rule', -> kb = Prolog.parseKb "likes(X, Z) :- likes(X, Y), likes(Y, Z)." kb.should.have.length 1 kb[0].body.should.have.length 2 kb[0].body[1].functor.should.equal "likes" kb[0].body[1].params.should.have.length 2 kb[0].body[1].params[1].name.should.equal "Z" it 'should parse a query', -> q = Prolog.parseQuery 'a' q.functor.should.equal "a" describe 'Simple', -> it 'should correctly answer ground query', -> kb = Prolog.parseKb "father(<NAME>, <NAME>). father(<NAME>, lot). father(<NAME>, mil<NAME>). father(har<NAME>, y<NAME>). male(isaac). male(lot). female(milcah). female(yiscah). son(X, Y) :- father(Y, X), male(X). daughter(X, Y) :- father(Y, X), female(X)." query = Prolog.parseQuery "son(lot, har<NAME>)" Prolog.solve(query, kb).should.equal true query = Prolog.parseQuery "son(milcah, haran)" Prolog.solve(query, kb).should.equal false it 'shouldnt accept a non-ground query', -> kb = Prolog.parseKb "resistor(power, n1(2))." query = Prolog.parseQuery "resistor(power, n1(X))" try Prolog.solve(query, kb) catch e e.should.equal 'cannot interpret a non-ground query'
true
should = require('chai').should() Prolog = require '../src/simple' describe 'Parser', -> it 'should parse a fact', -> kb = Prolog.parseKb "likes(X, pomegranate)." kb.should.have.length 1 kb[0].head.functor.should.equal "likes" kb[0].head.params.should.have.length 2 kb[0].head.params[0].name.should.equal "X" kb[0].head.params[1].functor.should.equal "pomegranate" it 'should parse a rule', -> kb = Prolog.parseKb "likes(X, Z) :- likes(X, Y), likes(Y, Z)." kb.should.have.length 1 kb[0].body.should.have.length 2 kb[0].body[1].functor.should.equal "likes" kb[0].body[1].params.should.have.length 2 kb[0].body[1].params[1].name.should.equal "Z" it 'should parse a query', -> q = Prolog.parseQuery 'a' q.functor.should.equal "a" describe 'Simple', -> it 'should correctly answer ground query', -> kb = Prolog.parseKb "father(PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI). father(PI:NAME:<NAME>END_PI, lot). father(PI:NAME:<NAME>END_PI, milPI:NAME:<NAME>END_PI). father(harPI:NAME:<NAME>END_PI, yPI:NAME:<NAME>END_PI). male(isaac). male(lot). female(milcah). female(yiscah). son(X, Y) :- father(Y, X), male(X). daughter(X, Y) :- father(Y, X), female(X)." query = Prolog.parseQuery "son(lot, harPI:NAME:<NAME>END_PI)" Prolog.solve(query, kb).should.equal true query = Prolog.parseQuery "son(milcah, haran)" Prolog.solve(query, kb).should.equal false it 'shouldnt accept a non-ground query', -> kb = Prolog.parseKb "resistor(power, n1(2))." query = Prolog.parseQuery "resistor(power, n1(X))" try Prolog.solve(query, kb) catch e e.should.equal 'cannot interpret a non-ground query'
[ { "context": "ng Else'})\n .addEmail('Email', { value: 'a@a.a'})\n .addUrl('Url', { value: 'http://www.", "end": 7433, "score": 0.9331843256950378, "start": 7428, "tag": "EMAIL", "value": "a@a.a" }, { "context": "e })\n .addPassword('Password', { value: 'ab...
src/components/form/spec.coffee
p-koscielniak/hexagonjs
61
import { userFacingText } from 'utils/user-facing-text' import { div, select, detached } from 'utils/selection' import { Form, validateForm } from 'components/form' export default () -> describe 'form', -> it 'should have user facing text defined', -> userFacingText('form', 'missingRadioValue').should.equal('Please select one of these options') userFacingText('form', 'missingValue').should.equal('Please fill in this field') userFacingText('form', 'pleaseAddAValue').should.equal('Please add at least one item') userFacingText('form', 'pleaseSelectAValue').should.equal('Please select a value from the list') userFacingText('form', 'typeMismatch').should.equal('Please enter a valid value for this field') describe 'validateForm', () -> fixture = select('body').append(div('hx-test-form')) beforeEach -> fixture.clear() after -> fixture.remove() makeInput = (text, val='', type='text') -> div() .add(detached('label').text(text)) .add(detached('input').value(val).attr('type', type)) describe 'with valid forms', -> validForm = undefined validation = undefined beforeEach () -> validForm = detached('form') .add(makeInput('Text', 'something')) fixture.add(validForm) validation = validateForm(validForm) it 'should validate the form with no errors', () -> validation.should.eql({ valid: true, errors: [] }) it 'should not show any error messages', () -> validForm.selectAll('.hx-form-error').empty().should.equal(true) describe 'with showMessage false', -> beforeEach () -> validation = validateForm(validForm, { showMessage: false }) it 'returns valid true', () -> validation.valid.should.equal(true) it 'returns no errors', () -> validation.errors.should.eql([]) it 'does not show any error messages', () -> validForm.selectAll('.hx-form-error').empty().should.equal(true) if navigator.userAgent.toLowerCase().indexOf('phantom') is -1 # PhantomJS doesn't support offsetParent so the beforeEach block fails in the tests without causing a failure. Disabling these tests in phantom for now describe 'with invalid forms', -> invalidForm = undefined validation = undefined invalidNode = undefined inputContainer = undefined beforeEach () -> inputContainer = makeInput('Text') invalidNode = inputContainer.select('input') .attr('required', true) invalidForm = detached('form') .add(inputContainer) fixture.append(invalidForm) validation = validateForm(invalidForm) it 'returns valid false', () -> validation.valid.should.equal(false) it 'returns the correct number of errors', () -> validation.errors.length.should.equal(1) # it 'returns the correct message', () -> # validation.errors[0].message.should.equal(userFacingText('form','missingValue')) it 'returns the correct node', () -> validation.errors[0].node.should.equal(invalidNode.node()) it 'returns the correct validity', () -> validation.errors[0].validity.should.eql(invalidNode.node().validity) it 'returns the correct focused', () -> validation.errors[0].focused.should.equal(false) it 'shows a single error message', () -> invalidForm.selectAll('.hx-form-error').size().should.equal(1) # it 'shows the correct error text in the message', () -> # invalidForm.selectAll('.hx-form-error').text().should.eql([userFacingText('form', 'missingValue')]) describe 'with showMessage false', -> beforeEach () -> invalidForm.selectAll('.hx-form-error').remove() validation = validateForm(invalidForm, { showMessage: false }) it 'returns valid false', () -> validation.valid.should.equal(false) it 'returns the correct number of errors', () -> validation.errors.length.should.equal(1) # it 'returns the correct message', () -> # validation.errors[0].message.should.equal(userFacingText('form','missingValue')) it 'returns the correct node', () -> validation.errors[0].node.should.equal(invalidNode.node()) it 'returns the correct validity', () -> validation.errors[0].validity.should.eql(invalidNode.node().validity) it 'returns the correct focused', () -> validation.errors[0].focused.should.equal(false) it 'does not show any error messages', () -> invalidForm.selectAll('.hx-form-error').empty().should.equal(true) describe 'with form buttons', -> validForm = undefined validate = undefined beforeEach () -> validForm = detached('form') .add(makeInput('Text', 'something')) .add(div().class('hx-form-buttons') .add(detached('button').text('submit'))) fixture.add(validForm) validate = -> validateForm(validForm) it 'does not throw an error', -> validate.should.not.throw() describe 'Form', () -> it 'should return the value for disabled fields', -> form = new Form(div()) .addText('Text') .addText('Text', { key: 'text' }) form.data({ 'text': '123', 'Text': '456' }) form.disabled('Text', true) form.data().should.eql({ Text: '456', text: '123' }) it 'should not return the value for hidden fields', -> form = new Form(div()) .addText('Text') .addText('Text', { key: 'text' }) form.data({ 'text': '123', 'Text': '456' }) form.hidden('Text', true) form.data().should.eql({ text: '123' }) it 'should disable and hide fields when they are added', -> form = new Form(div()) .addText('Text') .addText('Text', { key: 'text' }) .addText('Text', { key: 'd1', disabled: true }) .addText('Text', { key: 'h1', hidden: true }) .addText('Text', { key: 'hd1', hidden: true, disabled: true }) .addText('d2', { disabled: true }) .addText('h2', { hidden: true }) .addText('hd2', { hidden: true, disabled: true }) form.disabled('Text').should.equal(false) form.hidden('text').should.equal(false) form.disabled('d1').should.equal(true) form.disabled('d2').should.equal(true) form.hidden('h1').should.equal(true) form.hidden('h2').should.equal(true) form.disabled('hd1').should.equal(true) form.disabled('hd2').should.equal(true) form.hidden('hd1').should.equal(true) form.hidden('hd2').should.equal(true) it 'should allow html fields to be initialised with a value', -> form = new Form(div()) .addText('Text', { value: 'Something'}) .addTextArea('Text Area', { value: 'Something Else'}) .addEmail('Email', { value: 'a@a.a'}) .addUrl('Url', { value: 'http://www.a.co'}) .addNumber('Number', { value: 10 }) .addCheckbox('Checkbox', { value: true }) .addPassword('Password', { value: 'abc' }) .addRadio('Radio', ['One', 'Two', 'Three'], { value: 'Two' }) form.data().should.eql({ 'Text': 'Something' 'Text Area': 'Something Else' 'Email': 'a@a.a' 'Url': 'http://www.a.co' 'Number': '10' 'Checkbox': true 'Password': 'abc' 'Radio': 'Two' }) describe 'feature flags', -> describe 'useUpdatedStructure', -> testForm = undefined testSel = undefined beforeEach -> testSel = div() testForm = new Form(testSel, { featureFlags: { useUpdatedStructure: true, }, }) .addText('Text') .addTextArea('Text Area') .addCheckbox('Checkbox') .addRadio('Radio', ['One', 'Two', 'Three']) it 'adds hx-flag-form', -> testSel.classed('hx-flag-form').should.equal(true) it 'adds hx-flag-button', -> testSel.classed('hx-flag-button').should.equal(true) it 'does not add hx-form-vertical', -> testSel.classed('hx-form-vertical').should.equal(false) it 'wraps each field with a hx-form-group', -> testSel.selectAll('.hx-form-group').size().should.equal(4) it 'wraps checkbox and radio fields with hx-form-items', -> testSel.selectAll('.hx-form-items').size().should.equal(2) it 'wraps each checkbox and radio input in a hx-field-item', -> testSel.selectAll('.hx-form-item').size().should.equal(4) it 'uses the hx-input class', -> testSel.selectAll('.hx-input').size().should.equal(1) it 'uses the hx-input-textarea class', -> testSel.selectAll('.hx-input-textarea').size().should.equal(1) it 'uses the hx-input-checkbox class', -> testSel.selectAll('.hx-input-checkbox').size().should.equal(1) it 'uses the hx-input-radio class', -> testSel.selectAll('.hx-input-radio').size().should.equal(3) it 'uses the hx-form-label class', -> testSel.selectAll('.hx-form-label').size().should.equal(7) describe 'displayVertical', -> testForm = undefined testSel = undefined beforeEach -> testSel = div() testForm = new Form(testSel, { featureFlags: { displayVertical: true, }, }) .addText('Text') .addTextArea('Text Area') .addCheckbox('Checkbox') .addRadio('Radio', ['One', 'Two', 'Three']) it 'adds hx-flag-form', -> testSel.classed('hx-flag-form').should.equal(true) it 'adds hx-flag-button', -> testSel.classed('hx-flag-button').should.equal(true) it 'adds hx-form-vertical', -> testSel.classed('hx-form-vertical').should.equal(true) it 'wraps each field with a hx-form-group', -> testSel.selectAll('.hx-form-group').size().should.equal(4) it 'wraps checkbox and radio fields with hx-form-items', -> testSel.selectAll('.hx-form-items').size().should.equal(2) it 'wraps each checkbox and radio input in a hx-field-item', -> testSel.selectAll('.hx-form-item').size().should.equal(4) it 'uses the hx-input class', -> testSel.selectAll('.hx-input').size().should.equal(1) it 'uses the hx-input-textarea class', -> testSel.selectAll('.hx-input-textarea').size().should.equal(1) it 'uses the hx-input-checkbox class', -> testSel.selectAll('.hx-input-checkbox').size().should.equal(1) it 'uses the hx-input-radio class', -> testSel.selectAll('.hx-input-radio').size().should.equal(3) it 'uses the hx-form-label class', -> testSel.selectAll('.hx-form-label').size().should.equal(7)
169605
import { userFacingText } from 'utils/user-facing-text' import { div, select, detached } from 'utils/selection' import { Form, validateForm } from 'components/form' export default () -> describe 'form', -> it 'should have user facing text defined', -> userFacingText('form', 'missingRadioValue').should.equal('Please select one of these options') userFacingText('form', 'missingValue').should.equal('Please fill in this field') userFacingText('form', 'pleaseAddAValue').should.equal('Please add at least one item') userFacingText('form', 'pleaseSelectAValue').should.equal('Please select a value from the list') userFacingText('form', 'typeMismatch').should.equal('Please enter a valid value for this field') describe 'validateForm', () -> fixture = select('body').append(div('hx-test-form')) beforeEach -> fixture.clear() after -> fixture.remove() makeInput = (text, val='', type='text') -> div() .add(detached('label').text(text)) .add(detached('input').value(val).attr('type', type)) describe 'with valid forms', -> validForm = undefined validation = undefined beforeEach () -> validForm = detached('form') .add(makeInput('Text', 'something')) fixture.add(validForm) validation = validateForm(validForm) it 'should validate the form with no errors', () -> validation.should.eql({ valid: true, errors: [] }) it 'should not show any error messages', () -> validForm.selectAll('.hx-form-error').empty().should.equal(true) describe 'with showMessage false', -> beforeEach () -> validation = validateForm(validForm, { showMessage: false }) it 'returns valid true', () -> validation.valid.should.equal(true) it 'returns no errors', () -> validation.errors.should.eql([]) it 'does not show any error messages', () -> validForm.selectAll('.hx-form-error').empty().should.equal(true) if navigator.userAgent.toLowerCase().indexOf('phantom') is -1 # PhantomJS doesn't support offsetParent so the beforeEach block fails in the tests without causing a failure. Disabling these tests in phantom for now describe 'with invalid forms', -> invalidForm = undefined validation = undefined invalidNode = undefined inputContainer = undefined beforeEach () -> inputContainer = makeInput('Text') invalidNode = inputContainer.select('input') .attr('required', true) invalidForm = detached('form') .add(inputContainer) fixture.append(invalidForm) validation = validateForm(invalidForm) it 'returns valid false', () -> validation.valid.should.equal(false) it 'returns the correct number of errors', () -> validation.errors.length.should.equal(1) # it 'returns the correct message', () -> # validation.errors[0].message.should.equal(userFacingText('form','missingValue')) it 'returns the correct node', () -> validation.errors[0].node.should.equal(invalidNode.node()) it 'returns the correct validity', () -> validation.errors[0].validity.should.eql(invalidNode.node().validity) it 'returns the correct focused', () -> validation.errors[0].focused.should.equal(false) it 'shows a single error message', () -> invalidForm.selectAll('.hx-form-error').size().should.equal(1) # it 'shows the correct error text in the message', () -> # invalidForm.selectAll('.hx-form-error').text().should.eql([userFacingText('form', 'missingValue')]) describe 'with showMessage false', -> beforeEach () -> invalidForm.selectAll('.hx-form-error').remove() validation = validateForm(invalidForm, { showMessage: false }) it 'returns valid false', () -> validation.valid.should.equal(false) it 'returns the correct number of errors', () -> validation.errors.length.should.equal(1) # it 'returns the correct message', () -> # validation.errors[0].message.should.equal(userFacingText('form','missingValue')) it 'returns the correct node', () -> validation.errors[0].node.should.equal(invalidNode.node()) it 'returns the correct validity', () -> validation.errors[0].validity.should.eql(invalidNode.node().validity) it 'returns the correct focused', () -> validation.errors[0].focused.should.equal(false) it 'does not show any error messages', () -> invalidForm.selectAll('.hx-form-error').empty().should.equal(true) describe 'with form buttons', -> validForm = undefined validate = undefined beforeEach () -> validForm = detached('form') .add(makeInput('Text', 'something')) .add(div().class('hx-form-buttons') .add(detached('button').text('submit'))) fixture.add(validForm) validate = -> validateForm(validForm) it 'does not throw an error', -> validate.should.not.throw() describe 'Form', () -> it 'should return the value for disabled fields', -> form = new Form(div()) .addText('Text') .addText('Text', { key: 'text' }) form.data({ 'text': '123', 'Text': '456' }) form.disabled('Text', true) form.data().should.eql({ Text: '456', text: '123' }) it 'should not return the value for hidden fields', -> form = new Form(div()) .addText('Text') .addText('Text', { key: 'text' }) form.data({ 'text': '123', 'Text': '456' }) form.hidden('Text', true) form.data().should.eql({ text: '123' }) it 'should disable and hide fields when they are added', -> form = new Form(div()) .addText('Text') .addText('Text', { key: 'text' }) .addText('Text', { key: 'd1', disabled: true }) .addText('Text', { key: 'h1', hidden: true }) .addText('Text', { key: 'hd1', hidden: true, disabled: true }) .addText('d2', { disabled: true }) .addText('h2', { hidden: true }) .addText('hd2', { hidden: true, disabled: true }) form.disabled('Text').should.equal(false) form.hidden('text').should.equal(false) form.disabled('d1').should.equal(true) form.disabled('d2').should.equal(true) form.hidden('h1').should.equal(true) form.hidden('h2').should.equal(true) form.disabled('hd1').should.equal(true) form.disabled('hd2').should.equal(true) form.hidden('hd1').should.equal(true) form.hidden('hd2').should.equal(true) it 'should allow html fields to be initialised with a value', -> form = new Form(div()) .addText('Text', { value: 'Something'}) .addTextArea('Text Area', { value: 'Something Else'}) .addEmail('Email', { value: '<EMAIL>'}) .addUrl('Url', { value: 'http://www.a.co'}) .addNumber('Number', { value: 10 }) .addCheckbox('Checkbox', { value: true }) .addPassword('Password', { value: '<PASSWORD>' }) .addRadio('Radio', ['One', 'Two', 'Three'], { value: 'Two' }) form.data().should.eql({ 'Text': 'Something' 'Text Area': 'Something Else' 'Email': '<EMAIL>' 'Url': 'http://www.a.co' 'Number': '10' 'Checkbox': true 'Password': '<PASSWORD>' 'Radio': 'Two' }) describe 'feature flags', -> describe 'useUpdatedStructure', -> testForm = undefined testSel = undefined beforeEach -> testSel = div() testForm = new Form(testSel, { featureFlags: { useUpdatedStructure: true, }, }) .addText('Text') .addTextArea('Text Area') .addCheckbox('Checkbox') .addRadio('Radio', ['One', 'Two', 'Three']) it 'adds hx-flag-form', -> testSel.classed('hx-flag-form').should.equal(true) it 'adds hx-flag-button', -> testSel.classed('hx-flag-button').should.equal(true) it 'does not add hx-form-vertical', -> testSel.classed('hx-form-vertical').should.equal(false) it 'wraps each field with a hx-form-group', -> testSel.selectAll('.hx-form-group').size().should.equal(4) it 'wraps checkbox and radio fields with hx-form-items', -> testSel.selectAll('.hx-form-items').size().should.equal(2) it 'wraps each checkbox and radio input in a hx-field-item', -> testSel.selectAll('.hx-form-item').size().should.equal(4) it 'uses the hx-input class', -> testSel.selectAll('.hx-input').size().should.equal(1) it 'uses the hx-input-textarea class', -> testSel.selectAll('.hx-input-textarea').size().should.equal(1) it 'uses the hx-input-checkbox class', -> testSel.selectAll('.hx-input-checkbox').size().should.equal(1) it 'uses the hx-input-radio class', -> testSel.selectAll('.hx-input-radio').size().should.equal(3) it 'uses the hx-form-label class', -> testSel.selectAll('.hx-form-label').size().should.equal(7) describe 'displayVertical', -> testForm = undefined testSel = undefined beforeEach -> testSel = div() testForm = new Form(testSel, { featureFlags: { displayVertical: true, }, }) .addText('Text') .addTextArea('Text Area') .addCheckbox('Checkbox') .addRadio('Radio', ['One', 'Two', 'Three']) it 'adds hx-flag-form', -> testSel.classed('hx-flag-form').should.equal(true) it 'adds hx-flag-button', -> testSel.classed('hx-flag-button').should.equal(true) it 'adds hx-form-vertical', -> testSel.classed('hx-form-vertical').should.equal(true) it 'wraps each field with a hx-form-group', -> testSel.selectAll('.hx-form-group').size().should.equal(4) it 'wraps checkbox and radio fields with hx-form-items', -> testSel.selectAll('.hx-form-items').size().should.equal(2) it 'wraps each checkbox and radio input in a hx-field-item', -> testSel.selectAll('.hx-form-item').size().should.equal(4) it 'uses the hx-input class', -> testSel.selectAll('.hx-input').size().should.equal(1) it 'uses the hx-input-textarea class', -> testSel.selectAll('.hx-input-textarea').size().should.equal(1) it 'uses the hx-input-checkbox class', -> testSel.selectAll('.hx-input-checkbox').size().should.equal(1) it 'uses the hx-input-radio class', -> testSel.selectAll('.hx-input-radio').size().should.equal(3) it 'uses the hx-form-label class', -> testSel.selectAll('.hx-form-label').size().should.equal(7)
true
import { userFacingText } from 'utils/user-facing-text' import { div, select, detached } from 'utils/selection' import { Form, validateForm } from 'components/form' export default () -> describe 'form', -> it 'should have user facing text defined', -> userFacingText('form', 'missingRadioValue').should.equal('Please select one of these options') userFacingText('form', 'missingValue').should.equal('Please fill in this field') userFacingText('form', 'pleaseAddAValue').should.equal('Please add at least one item') userFacingText('form', 'pleaseSelectAValue').should.equal('Please select a value from the list') userFacingText('form', 'typeMismatch').should.equal('Please enter a valid value for this field') describe 'validateForm', () -> fixture = select('body').append(div('hx-test-form')) beforeEach -> fixture.clear() after -> fixture.remove() makeInput = (text, val='', type='text') -> div() .add(detached('label').text(text)) .add(detached('input').value(val).attr('type', type)) describe 'with valid forms', -> validForm = undefined validation = undefined beforeEach () -> validForm = detached('form') .add(makeInput('Text', 'something')) fixture.add(validForm) validation = validateForm(validForm) it 'should validate the form with no errors', () -> validation.should.eql({ valid: true, errors: [] }) it 'should not show any error messages', () -> validForm.selectAll('.hx-form-error').empty().should.equal(true) describe 'with showMessage false', -> beforeEach () -> validation = validateForm(validForm, { showMessage: false }) it 'returns valid true', () -> validation.valid.should.equal(true) it 'returns no errors', () -> validation.errors.should.eql([]) it 'does not show any error messages', () -> validForm.selectAll('.hx-form-error').empty().should.equal(true) if navigator.userAgent.toLowerCase().indexOf('phantom') is -1 # PhantomJS doesn't support offsetParent so the beforeEach block fails in the tests without causing a failure. Disabling these tests in phantom for now describe 'with invalid forms', -> invalidForm = undefined validation = undefined invalidNode = undefined inputContainer = undefined beforeEach () -> inputContainer = makeInput('Text') invalidNode = inputContainer.select('input') .attr('required', true) invalidForm = detached('form') .add(inputContainer) fixture.append(invalidForm) validation = validateForm(invalidForm) it 'returns valid false', () -> validation.valid.should.equal(false) it 'returns the correct number of errors', () -> validation.errors.length.should.equal(1) # it 'returns the correct message', () -> # validation.errors[0].message.should.equal(userFacingText('form','missingValue')) it 'returns the correct node', () -> validation.errors[0].node.should.equal(invalidNode.node()) it 'returns the correct validity', () -> validation.errors[0].validity.should.eql(invalidNode.node().validity) it 'returns the correct focused', () -> validation.errors[0].focused.should.equal(false) it 'shows a single error message', () -> invalidForm.selectAll('.hx-form-error').size().should.equal(1) # it 'shows the correct error text in the message', () -> # invalidForm.selectAll('.hx-form-error').text().should.eql([userFacingText('form', 'missingValue')]) describe 'with showMessage false', -> beforeEach () -> invalidForm.selectAll('.hx-form-error').remove() validation = validateForm(invalidForm, { showMessage: false }) it 'returns valid false', () -> validation.valid.should.equal(false) it 'returns the correct number of errors', () -> validation.errors.length.should.equal(1) # it 'returns the correct message', () -> # validation.errors[0].message.should.equal(userFacingText('form','missingValue')) it 'returns the correct node', () -> validation.errors[0].node.should.equal(invalidNode.node()) it 'returns the correct validity', () -> validation.errors[0].validity.should.eql(invalidNode.node().validity) it 'returns the correct focused', () -> validation.errors[0].focused.should.equal(false) it 'does not show any error messages', () -> invalidForm.selectAll('.hx-form-error').empty().should.equal(true) describe 'with form buttons', -> validForm = undefined validate = undefined beforeEach () -> validForm = detached('form') .add(makeInput('Text', 'something')) .add(div().class('hx-form-buttons') .add(detached('button').text('submit'))) fixture.add(validForm) validate = -> validateForm(validForm) it 'does not throw an error', -> validate.should.not.throw() describe 'Form', () -> it 'should return the value for disabled fields', -> form = new Form(div()) .addText('Text') .addText('Text', { key: 'text' }) form.data({ 'text': '123', 'Text': '456' }) form.disabled('Text', true) form.data().should.eql({ Text: '456', text: '123' }) it 'should not return the value for hidden fields', -> form = new Form(div()) .addText('Text') .addText('Text', { key: 'text' }) form.data({ 'text': '123', 'Text': '456' }) form.hidden('Text', true) form.data().should.eql({ text: '123' }) it 'should disable and hide fields when they are added', -> form = new Form(div()) .addText('Text') .addText('Text', { key: 'text' }) .addText('Text', { key: 'd1', disabled: true }) .addText('Text', { key: 'h1', hidden: true }) .addText('Text', { key: 'hd1', hidden: true, disabled: true }) .addText('d2', { disabled: true }) .addText('h2', { hidden: true }) .addText('hd2', { hidden: true, disabled: true }) form.disabled('Text').should.equal(false) form.hidden('text').should.equal(false) form.disabled('d1').should.equal(true) form.disabled('d2').should.equal(true) form.hidden('h1').should.equal(true) form.hidden('h2').should.equal(true) form.disabled('hd1').should.equal(true) form.disabled('hd2').should.equal(true) form.hidden('hd1').should.equal(true) form.hidden('hd2').should.equal(true) it 'should allow html fields to be initialised with a value', -> form = new Form(div()) .addText('Text', { value: 'Something'}) .addTextArea('Text Area', { value: 'Something Else'}) .addEmail('Email', { value: 'PI:EMAIL:<EMAIL>END_PI'}) .addUrl('Url', { value: 'http://www.a.co'}) .addNumber('Number', { value: 10 }) .addCheckbox('Checkbox', { value: true }) .addPassword('Password', { value: 'PI:PASSWORD:<PASSWORD>END_PI' }) .addRadio('Radio', ['One', 'Two', 'Three'], { value: 'Two' }) form.data().should.eql({ 'Text': 'Something' 'Text Area': 'Something Else' 'Email': 'PI:EMAIL:<EMAIL>END_PI' 'Url': 'http://www.a.co' 'Number': '10' 'Checkbox': true 'Password': 'PI:PASSWORD:<PASSWORD>END_PI' 'Radio': 'Two' }) describe 'feature flags', -> describe 'useUpdatedStructure', -> testForm = undefined testSel = undefined beforeEach -> testSel = div() testForm = new Form(testSel, { featureFlags: { useUpdatedStructure: true, }, }) .addText('Text') .addTextArea('Text Area') .addCheckbox('Checkbox') .addRadio('Radio', ['One', 'Two', 'Three']) it 'adds hx-flag-form', -> testSel.classed('hx-flag-form').should.equal(true) it 'adds hx-flag-button', -> testSel.classed('hx-flag-button').should.equal(true) it 'does not add hx-form-vertical', -> testSel.classed('hx-form-vertical').should.equal(false) it 'wraps each field with a hx-form-group', -> testSel.selectAll('.hx-form-group').size().should.equal(4) it 'wraps checkbox and radio fields with hx-form-items', -> testSel.selectAll('.hx-form-items').size().should.equal(2) it 'wraps each checkbox and radio input in a hx-field-item', -> testSel.selectAll('.hx-form-item').size().should.equal(4) it 'uses the hx-input class', -> testSel.selectAll('.hx-input').size().should.equal(1) it 'uses the hx-input-textarea class', -> testSel.selectAll('.hx-input-textarea').size().should.equal(1) it 'uses the hx-input-checkbox class', -> testSel.selectAll('.hx-input-checkbox').size().should.equal(1) it 'uses the hx-input-radio class', -> testSel.selectAll('.hx-input-radio').size().should.equal(3) it 'uses the hx-form-label class', -> testSel.selectAll('.hx-form-label').size().should.equal(7) describe 'displayVertical', -> testForm = undefined testSel = undefined beforeEach -> testSel = div() testForm = new Form(testSel, { featureFlags: { displayVertical: true, }, }) .addText('Text') .addTextArea('Text Area') .addCheckbox('Checkbox') .addRadio('Radio', ['One', 'Two', 'Three']) it 'adds hx-flag-form', -> testSel.classed('hx-flag-form').should.equal(true) it 'adds hx-flag-button', -> testSel.classed('hx-flag-button').should.equal(true) it 'adds hx-form-vertical', -> testSel.classed('hx-form-vertical').should.equal(true) it 'wraps each field with a hx-form-group', -> testSel.selectAll('.hx-form-group').size().should.equal(4) it 'wraps checkbox and radio fields with hx-form-items', -> testSel.selectAll('.hx-form-items').size().should.equal(2) it 'wraps each checkbox and radio input in a hx-field-item', -> testSel.selectAll('.hx-form-item').size().should.equal(4) it 'uses the hx-input class', -> testSel.selectAll('.hx-input').size().should.equal(1) it 'uses the hx-input-textarea class', -> testSel.selectAll('.hx-input-textarea').size().should.equal(1) it 'uses the hx-input-checkbox class', -> testSel.selectAll('.hx-input-checkbox').size().should.equal(1) it 'uses the hx-input-radio class', -> testSel.selectAll('.hx-input-radio').size().should.equal(3) it 'uses the hx-form-label class', -> testSel.selectAll('.hx-form-label').size().should.equal(7)
[ { "context": " position:\n company:\n name: \"Empresa\"\n title: \"Puesto profesional\"\n summ", "end": 210, "score": 0.9942916631698608, "start": 203, "tag": "NAME", "value": "Empresa" } ]
app/scripts/controllers/main.coffee
N4N0/portfolio
0
'use strict' angular.module('portfolioApp') .controller 'MainCtrl', ['$scope', '$http', 'linkedIn', ($scope, $http, linkedIn) -> templates = position: company: name: "Empresa" title: "Puesto profesional" summary: "Descripción" education: degree: "Titulo" schoolName: "Institución" skill: skill: name: "aptitud" authCallback = -> linkedIn.getProfile (data) -> if data and data.values and data.values[0] $scope.profile = data.values[0] $scope.$apply() unless $scope.$$phase is '$apply' or $scope.$$phase is '$digest' linkedIn.regCallback authCallback $scope.new = (type, array) -> array.unshift angular.copy templates[type] ]
143898
'use strict' angular.module('portfolioApp') .controller 'MainCtrl', ['$scope', '$http', 'linkedIn', ($scope, $http, linkedIn) -> templates = position: company: name: "<NAME>" title: "Puesto profesional" summary: "Descripción" education: degree: "Titulo" schoolName: "Institución" skill: skill: name: "aptitud" authCallback = -> linkedIn.getProfile (data) -> if data and data.values and data.values[0] $scope.profile = data.values[0] $scope.$apply() unless $scope.$$phase is '$apply' or $scope.$$phase is '$digest' linkedIn.regCallback authCallback $scope.new = (type, array) -> array.unshift angular.copy templates[type] ]
true
'use strict' angular.module('portfolioApp') .controller 'MainCtrl', ['$scope', '$http', 'linkedIn', ($scope, $http, linkedIn) -> templates = position: company: name: "PI:NAME:<NAME>END_PI" title: "Puesto profesional" summary: "Descripción" education: degree: "Titulo" schoolName: "Institución" skill: skill: name: "aptitud" authCallback = -> linkedIn.getProfile (data) -> if data and data.values and data.values[0] $scope.profile = data.values[0] $scope.$apply() unless $scope.$$phase is '$apply' or $scope.$$phase is '$digest' linkedIn.regCallback authCallback $scope.new = (type, array) -> array.unshift angular.copy templates[type] ]
[ { "context": "stdout.slice(0, 10)}\n * http://github.com/elabs/serenade.js\n *\n * Copyright 2011,", "end": 625, "score": 0.7539781332015991, "start": 620, "tag": "USERNAME", "value": "elabs" }, { "context": "/serenade.js\n *\n * Copyright 2011...
src/build.coffee
varvet/serenade.js
5
# We prioritize getting this to work in the browser over being a good node/commonjs citizen. # To get this to work in commonjs anyway, we basically eval the whole thing. Sue me. CoffeeScript = require 'coffee-script' fs = require 'fs' path = require 'path' gzip = require 'gzip-js' vm = require("vm") fs = require("fs") exec = require('child_process').exec Build = header: (callback) -> exec "git rev-parse HEAD", (error, stdout, stderr) -> callback """ /** * Serenade.js JavaScript Framework v#{Serenade.VERSION} * Revision: #{stdout.slice(0, 10)} * http://github.com/elabs/serenade.js * * Copyright 2011, Jonas Nicklas, Elabs AB * Released under the MIT License */ """ sourceFiles: [ "helpers" "transform" "event" "cache" "collection" "association_collection" "property" "model" "lexer" "node" "dynamic_node" "compile" "view" "serenade" ] source: -> files = {} js = require('./grammar').Parser.generate({ moduleType: "js" }) coffee = "" coffee += fs.readFileSync(path.join(__dirname, "#{name}.coffee")).toString() for name in @sourceFiles js += CoffeeScript.compile(coffee, bare: true) """ (function(root) { #{js}; root.Serenade = Serenade; }(this)); """ load: -> # unfortunately because vm is pretty broken we need to declare every single object/function we refer to here sandbox = { Object: Object SyntaxError: SyntaxError console: console parser: require('./grammar').Parser, clearTimeout: -> clearTimeout(arguments...) setTimeout: -> setTimeout(arguments...) requestAnimationFrame: (fn) -> setTimeout(fn, 17) cancelAnimationFrame: clearTimeout } context = vm.createContext(sandbox) for name in @sourceFiles filePath = path.join(__dirname, "#{name}.coffee") source = fs.readFileSync(filePath) data = CoffeeScript.compile(source.toString(), bare: true, filename: filePath) vm.runInContext(data, context, filePath) context unpacked: (callback) -> @header (header) => callback(header + '\n' + @source()) minified: (callback) -> @header (header) => {parser, uglify} = require 'uglify-js' minified = uglify.gen_code uglify.ast_squeeze uglify.ast_mangle parser.parse @source() callback(header + "\n" + minified) gzipped: (callback) -> Build.minified (minified) -> callback(gzip.zip(minified)) build = Build.load() build.Build = Build Serenade = build.Serenade module.exports = build # Express.js support module.exports.compile = -> document = require("jsdom").jsdom(null, null, {}) fs = require("fs") window = document.createWindow() Serenade.document = document (env) -> model = env.model viewName = env.filename.split('/').reverse()[0].replace(/\.serenade$/, '') Serenade.view(viewName, fs.readFileSync(env.filename).toString()) element = Serenade.render(viewName, model, {}) document.body.appendChild(element) html = document.body.innerHTML html = "<!DOCTYPE html>\n" + html unless env.doctype is false html
133045
# We prioritize getting this to work in the browser over being a good node/commonjs citizen. # To get this to work in commonjs anyway, we basically eval the whole thing. Sue me. CoffeeScript = require 'coffee-script' fs = require 'fs' path = require 'path' gzip = require 'gzip-js' vm = require("vm") fs = require("fs") exec = require('child_process').exec Build = header: (callback) -> exec "git rev-parse HEAD", (error, stdout, stderr) -> callback """ /** * Serenade.js JavaScript Framework v#{Serenade.VERSION} * Revision: #{stdout.slice(0, 10)} * http://github.com/elabs/serenade.js * * Copyright 2011, <NAME>, Elabs AB * Released under the MIT License */ """ sourceFiles: [ "helpers" "transform" "event" "cache" "collection" "association_collection" "property" "model" "lexer" "node" "dynamic_node" "compile" "view" "serenade" ] source: -> files = {} js = require('./grammar').Parser.generate({ moduleType: "js" }) coffee = "" coffee += fs.readFileSync(path.join(__dirname, "#{name}.coffee")).toString() for name in @sourceFiles js += CoffeeScript.compile(coffee, bare: true) """ (function(root) { #{js}; root.Serenade = Serenade; }(this)); """ load: -> # unfortunately because vm is pretty broken we need to declare every single object/function we refer to here sandbox = { Object: Object SyntaxError: SyntaxError console: console parser: require('./grammar').Parser, clearTimeout: -> clearTimeout(arguments...) setTimeout: -> setTimeout(arguments...) requestAnimationFrame: (fn) -> setTimeout(fn, 17) cancelAnimationFrame: clearTimeout } context = vm.createContext(sandbox) for name in @sourceFiles filePath = path.join(__dirname, "#{name}.coffee") source = fs.readFileSync(filePath) data = CoffeeScript.compile(source.toString(), bare: true, filename: filePath) vm.runInContext(data, context, filePath) context unpacked: (callback) -> @header (header) => callback(header + '\n' + @source()) minified: (callback) -> @header (header) => {parser, uglify} = require 'uglify-js' minified = uglify.gen_code uglify.ast_squeeze uglify.ast_mangle parser.parse @source() callback(header + "\n" + minified) gzipped: (callback) -> Build.minified (minified) -> callback(gzip.zip(minified)) build = Build.load() build.Build = Build Serenade = build.Serenade module.exports = build # Express.js support module.exports.compile = -> document = require("jsdom").jsdom(null, null, {}) fs = require("fs") window = document.createWindow() Serenade.document = document (env) -> model = env.model viewName = env.filename.split('/').reverse()[0].replace(/\.serenade$/, '') Serenade.view(viewName, fs.readFileSync(env.filename).toString()) element = Serenade.render(viewName, model, {}) document.body.appendChild(element) html = document.body.innerHTML html = "<!DOCTYPE html>\n" + html unless env.doctype is false html
true
# We prioritize getting this to work in the browser over being a good node/commonjs citizen. # To get this to work in commonjs anyway, we basically eval the whole thing. Sue me. CoffeeScript = require 'coffee-script' fs = require 'fs' path = require 'path' gzip = require 'gzip-js' vm = require("vm") fs = require("fs") exec = require('child_process').exec Build = header: (callback) -> exec "git rev-parse HEAD", (error, stdout, stderr) -> callback """ /** * Serenade.js JavaScript Framework v#{Serenade.VERSION} * Revision: #{stdout.slice(0, 10)} * http://github.com/elabs/serenade.js * * Copyright 2011, PI:NAME:<NAME>END_PI, Elabs AB * Released under the MIT License */ """ sourceFiles: [ "helpers" "transform" "event" "cache" "collection" "association_collection" "property" "model" "lexer" "node" "dynamic_node" "compile" "view" "serenade" ] source: -> files = {} js = require('./grammar').Parser.generate({ moduleType: "js" }) coffee = "" coffee += fs.readFileSync(path.join(__dirname, "#{name}.coffee")).toString() for name in @sourceFiles js += CoffeeScript.compile(coffee, bare: true) """ (function(root) { #{js}; root.Serenade = Serenade; }(this)); """ load: -> # unfortunately because vm is pretty broken we need to declare every single object/function we refer to here sandbox = { Object: Object SyntaxError: SyntaxError console: console parser: require('./grammar').Parser, clearTimeout: -> clearTimeout(arguments...) setTimeout: -> setTimeout(arguments...) requestAnimationFrame: (fn) -> setTimeout(fn, 17) cancelAnimationFrame: clearTimeout } context = vm.createContext(sandbox) for name in @sourceFiles filePath = path.join(__dirname, "#{name}.coffee") source = fs.readFileSync(filePath) data = CoffeeScript.compile(source.toString(), bare: true, filename: filePath) vm.runInContext(data, context, filePath) context unpacked: (callback) -> @header (header) => callback(header + '\n' + @source()) minified: (callback) -> @header (header) => {parser, uglify} = require 'uglify-js' minified = uglify.gen_code uglify.ast_squeeze uglify.ast_mangle parser.parse @source() callback(header + "\n" + minified) gzipped: (callback) -> Build.minified (minified) -> callback(gzip.zip(minified)) build = Build.load() build.Build = Build Serenade = build.Serenade module.exports = build # Express.js support module.exports.compile = -> document = require("jsdom").jsdom(null, null, {}) fs = require("fs") window = document.createWindow() Serenade.document = document (env) -> model = env.model viewName = env.filename.split('/').reverse()[0].replace(/\.serenade$/, '') Serenade.view(viewName, fs.readFileSync(env.filename).toString()) element = Serenade.render(viewName, model, {}) document.body.appendChild(element) html = document.body.innerHTML html = "<!DOCTYPE html>\n" + html unless env.doctype is false html
[ { "context": "\n expected = 'Solved <a href=\"https://github.com/travis-ci/travis-web/issues/11\">#11</a>hey'\n\n equal(result", "end": 242, "score": 0.9995834231376648, "start": 233, "tag": "USERNAME", "value": "travis-ci" }, { "context": "\n expected = 'Solved <a href=\"https://...
assets/scripts/spec/unit/helpers_spec.coffee
Acidburn0zzz/travis-web
0
module "Travis.Helpers.githubify" test 'replaces #Num with github issues link', -> message = 'Solved #11hey' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Solved <a href="https://github.com/travis-ci/travis-web/issues/11">#11</a>hey' equal(result, expected, "#num should be converted to a link") test 'replaces User#Num with github issues link to forked repo', -> message = 'Solved test#11hey' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Solved <a href="https://github.com/test/travis-web/issues/11">test#11</a>hey' equal(result, expected, "user#num should be converted to a link") test 'replaces User/Project#Num with github issues link to another repo', -> message = 'Solved test_1-a2/test-a_11#11hey' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Solved <a href="https://github.com/test_1-a2/test-a_11/issues/11">test_1-a2/test-a_11#11</a>hey' equal(result, expected, "owner/repo#num should be converted to a link") test 'replaces gh-Num with github issues link', -> message = 'Solved gh-22hey' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Solved <a href="https://github.com/travis-ci/travis-web/issues/22">gh-22</a>hey' equal(result, expected, "gh-Num should be converted to a link") test 'replaces multiple references with github issues links', -> message = 'Try #1 and test#2 and test/testing#3' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Try <a href="https://github.com/travis-ci/travis-web/issues/1">#1</a> and ' expected += '<a href="https://github.com/test/travis-web/issues/2">test#2</a> and ' expected += '<a href="https://github.com/test/testing/issues/3">test/testing#3</a>' equal(result, expected, "references should be converted to links") test 'replaces multiple references with github issues links', -> message = 'Try #1 and test#2 and test/testing#3' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Try <a href="https://github.com/travis-ci/travis-web/issues/1">#1</a> and ' expected += '<a href="https://github.com/test/travis-web/issues/2">test#2</a> and ' expected += '<a href="https://github.com/test/testing/issues/3">test/testing#3</a>' equal(result, expected, "references should be converted to links") test 'replaces @user with github user link', -> message = 'It is for you @tender_love1' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'It is for you <a href="https://github.com/tender_love1">@tender_love1</a>' equal(result, expected, "@user should be converted to a link") test 'does not replace @user if it is a sign-off', -> message = 'Signed-off-by: GitHub User <user@example.com>' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') equal(result, message, "@user should not be converted to a link if it matches an email") test 'replaces one commit reference with github commit link', -> message = 'See travis-ci/travis-core@732fe00' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'See <a href="https://github.com/travis-ci/travis-core/commit/732fe00">travis-ci/travis-core@732fe00</a>' equal(result, expected, "Commit reference should be converted to a link") test 'replaces multiple commit references with github commit links', -> message = 'See travis-ci/travis-core@732fe00 and travis-ci/travis-web@3b6aa17' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'See <a href="https://github.com/travis-ci/travis-core/commit/732fe00">travis-ci/travis-core@732fe00</a> and <a href="https://github.com/travis-ci/travis-web/commit/3b6aa17">travis-ci/travis-web@3b6aa17</a>' equal(result, expected, "Commit references should be converted to links")
40292
module "Travis.Helpers.githubify" test 'replaces #Num with github issues link', -> message = 'Solved #11hey' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Solved <a href="https://github.com/travis-ci/travis-web/issues/11">#11</a>hey' equal(result, expected, "#num should be converted to a link") test 'replaces User#Num with github issues link to forked repo', -> message = 'Solved test#11hey' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Solved <a href="https://github.com/test/travis-web/issues/11">test#11</a>hey' equal(result, expected, "user#num should be converted to a link") test 'replaces User/Project#Num with github issues link to another repo', -> message = 'Solved test_1-a2/test-a_11#11hey' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Solved <a href="https://github.com/test_1-a2/test-a_11/issues/11">test_1-a2/test-a_11#11</a>hey' equal(result, expected, "owner/repo#num should be converted to a link") test 'replaces gh-Num with github issues link', -> message = 'Solved gh-22hey' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Solved <a href="https://github.com/travis-ci/travis-web/issues/22">gh-22</a>hey' equal(result, expected, "gh-Num should be converted to a link") test 'replaces multiple references with github issues links', -> message = 'Try #1 and test#2 and test/testing#3' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Try <a href="https://github.com/travis-ci/travis-web/issues/1">#1</a> and ' expected += '<a href="https://github.com/test/travis-web/issues/2">test#2</a> and ' expected += '<a href="https://github.com/test/testing/issues/3">test/testing#3</a>' equal(result, expected, "references should be converted to links") test 'replaces multiple references with github issues links', -> message = 'Try #1 and test#2 and test/testing#3' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Try <a href="https://github.com/travis-ci/travis-web/issues/1">#1</a> and ' expected += '<a href="https://github.com/test/travis-web/issues/2">test#2</a> and ' expected += '<a href="https://github.com/test/testing/issues/3">test/testing#3</a>' equal(result, expected, "references should be converted to links") test 'replaces @user with github user link', -> message = 'It is for you @tender_love1' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'It is for you <a href="https://github.com/tender_love1">@tender_love1</a>' equal(result, expected, "@user should be converted to a link") test 'does not replace @user if it is a sign-off', -> message = 'Signed-off-by: GitHub User <<EMAIL>>' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') equal(result, message, "@user should not be converted to a link if it matches an email") test 'replaces one commit reference with github commit link', -> message = 'See travis-ci/travis-core@732fe00' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'See <a href="https://github.com/travis-ci/travis-core/commit/732fe00">travis-ci/travis-core@732fe00</a>' equal(result, expected, "Commit reference should be converted to a link") test 'replaces multiple commit references with github commit links', -> message = 'See travis-ci/travis-core@732fe00 and travis-ci/travis-web@3b6aa17' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'See <a href="https://github.com/travis-ci/travis-core/commit/732fe00">travis-ci/travis-core@732fe00</a> and <a href="https://github.com/travis-ci/travis-web/commit/3b6aa17">travis-ci/travis-web@3b6aa17</a>' equal(result, expected, "Commit references should be converted to links")
true
module "Travis.Helpers.githubify" test 'replaces #Num with github issues link', -> message = 'Solved #11hey' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Solved <a href="https://github.com/travis-ci/travis-web/issues/11">#11</a>hey' equal(result, expected, "#num should be converted to a link") test 'replaces User#Num with github issues link to forked repo', -> message = 'Solved test#11hey' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Solved <a href="https://github.com/test/travis-web/issues/11">test#11</a>hey' equal(result, expected, "user#num should be converted to a link") test 'replaces User/Project#Num with github issues link to another repo', -> message = 'Solved test_1-a2/test-a_11#11hey' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Solved <a href="https://github.com/test_1-a2/test-a_11/issues/11">test_1-a2/test-a_11#11</a>hey' equal(result, expected, "owner/repo#num should be converted to a link") test 'replaces gh-Num with github issues link', -> message = 'Solved gh-22hey' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Solved <a href="https://github.com/travis-ci/travis-web/issues/22">gh-22</a>hey' equal(result, expected, "gh-Num should be converted to a link") test 'replaces multiple references with github issues links', -> message = 'Try #1 and test#2 and test/testing#3' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Try <a href="https://github.com/travis-ci/travis-web/issues/1">#1</a> and ' expected += '<a href="https://github.com/test/travis-web/issues/2">test#2</a> and ' expected += '<a href="https://github.com/test/testing/issues/3">test/testing#3</a>' equal(result, expected, "references should be converted to links") test 'replaces multiple references with github issues links', -> message = 'Try #1 and test#2 and test/testing#3' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'Try <a href="https://github.com/travis-ci/travis-web/issues/1">#1</a> and ' expected += '<a href="https://github.com/test/travis-web/issues/2">test#2</a> and ' expected += '<a href="https://github.com/test/testing/issues/3">test/testing#3</a>' equal(result, expected, "references should be converted to links") test 'replaces @user with github user link', -> message = 'It is for you @tender_love1' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'It is for you <a href="https://github.com/tender_love1">@tender_love1</a>' equal(result, expected, "@user should be converted to a link") test 'does not replace @user if it is a sign-off', -> message = 'Signed-off-by: GitHub User <PI:EMAIL:<EMAIL>END_PI>' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') equal(result, message, "@user should not be converted to a link if it matches an email") test 'replaces one commit reference with github commit link', -> message = 'See travis-ci/travis-core@732fe00' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'See <a href="https://github.com/travis-ci/travis-core/commit/732fe00">travis-ci/travis-core@732fe00</a>' equal(result, expected, "Commit reference should be converted to a link") test 'replaces multiple commit references with github commit links', -> message = 'See travis-ci/travis-core@732fe00 and travis-ci/travis-web@3b6aa17' result = Travis.Helpers.githubify(message, 'travis-ci', 'travis-web') expected = 'See <a href="https://github.com/travis-ci/travis-core/commit/732fe00">travis-ci/travis-core@732fe00</a> and <a href="https://github.com/travis-ci/travis-web/commit/3b6aa17">travis-ci/travis-web@3b6aa17</a>' equal(result, expected, "Commit references should be converted to links")
[ { "context": "test fixture using js-fixtures https://github.com/badunk/js-fixtures\n fixtures.path = 'fixtures'\n ", "end": 848, "score": 0.9993903040885925, "start": 842, "tag": "USERNAME", "value": "badunk" }, { "context": ".g., error msgs\n $f('input.password').val ...
test/views/login-dialog.spec.coffee
OpenSourceFieldlinguistics/dative
7
define (require) -> LoginDialogView = require '../../../scripts/views/login-dialog' ApplicationSettingsModel = require '../../../scripts/models/application-settings' describe 'Login Dialog View', -> before -> # Spy on methods... sinon.spy LoginDialogView::, '_authenticateFail' sinon.spy LoginDialogView::, '_authenticateEnd' sinon.spy LoginDialogView::, '_authenticateSuccess' sinon.spy LoginDialogView::, 'toggle' sinon.spy LoginDialogView::, 'validate' sinon.spy LoginDialogView::, '_submitWithEnter' sinon.spy LoginDialogView::, '_disableButtons' sinon.spy LoginDialogView::, 'login' sinon.spy LoginDialogView::, 'logout' sinon.spy LoginDialogView::, 'forgotPassword' beforeEach (done) -> # Create test fixture using js-fixtures https://github.com/badunk/js-fixtures fixtures.path = 'fixtures' callback = => @$fixture = fixtures.window().$("<div id='js-fixtures-fixture'></div>") @$ = (selector) -> @$fixture.find selector sinon.stub ApplicationSettingsModel::, 'logout' sinon.stub ApplicationSettingsModel::, 'authenticate' @checkIfLoggedInStub = sinon.stub() ApplicationSettingsModel::checkIfLoggedIn = @checkIfLoggedInStub @applicationSettingsModel = new ApplicationSettingsModel() @applicationSettingsModel.set 'loggedIn', false @loginDialogView = new LoginDialogView el: @$fixture model: @applicationSettingsModel @loginDialogView.render() done() fixtures.load('fixture.html', callback) afterEach -> fixtures.cleanUp() @loginDialogView.close() @loginDialogView.remove() # Reset spies & stubs @checkIfLoggedInStub.reset() ApplicationSettingsModel::logout.restore() ApplicationSettingsModel::authenticate.restore() LoginDialogView::_authenticateFail.reset() LoginDialogView::_authenticateEnd.reset() LoginDialogView::_authenticateSuccess.reset() LoginDialogView::toggle.reset() LoginDialogView::validate.reset() LoginDialogView::_submitWithEnter.reset() LoginDialogView::_disableButtons.reset() LoginDialogView::login.reset() LoginDialogView::logout.reset() LoginDialogView::forgotPassword.reset() after -> # Restore spied-on methods LoginDialogView::_authenticateFail.restore() LoginDialogView::_authenticateEnd.restore() LoginDialogView::_authenticateSuccess.restore() LoginDialogView::toggle.restore() LoginDialogView::validate.restore() LoginDialogView::_submitWithEnter.restore() LoginDialogView::_disableButtons.restore() LoginDialogView::login.restore() LoginDialogView::forgotPassword.restore() describe 'Initialization', -> it 'creates a jQueryUI dialog', -> $f = (selector) => @loginDialogView.$target.find(selector) expect($f('.dative-login-dialog-widget')).to.have.prop 'tagName', 'DIV' expect($f('.dative-login-dialog-widget .forgot-password')) .to.have.prop 'tagName', 'BUTTON' expect($f('.dative-login-dialog-widget .login')) .to.have.prop 'tagName', 'BUTTON' expect($f('.dative-login-dialog-widget .logout')) .to.have.prop 'tagName', 'BUTTON' expect($f('.blargon-five')).not.to.have.prop 'tagName' it 'dis/enables buttons according to authentication state', -> $f = (selector) => @loginDialogView.$target.find(selector) expect($f('button.logout')).to.have.class 'ui-state-disabled' expect($f('button.login')).not.to.have.class 'ui-state-disabled' expect($f('button.forgot-password')).not.to.have.class 'ui-state-disabled' expect($f('input.password')).not.to.have.attr 'disabled' expect($f('input.username')).not.to.have.attr 'disabled' @loginDialogView.model.set 'loggedIn', true expect($f('button.logout')).not.to.have.class 'ui-state-disabled' expect($f('button.login')).to.have.class 'ui-state-disabled' expect($f('button.forgot-password')).to.have.class 'ui-state-disabled' expect($f('input.password')).to.have.attr 'disabled' expect($f('input.username')).to.have.attr 'disabled' describe 'Event responsivity', -> it 'responds to Bacbkone-wide events', -> # Need to reset these spies because the app sett model can do unpredictable # things, depending on the state of the local storage app settings ... @loginDialogView._authenticateFail.reset() @loginDialogView._authenticateEnd.reset() @loginDialogView._authenticateSuccess.reset() @loginDialogView.toggle.reset() expect(@loginDialogView._authenticateFail).not.to.have.been.called expect(@loginDialogView._authenticateEnd).not.to.have.been.called expect(@loginDialogView._authenticateSuccess).not.to.have.been.called expect(@loginDialogView.toggle).not.to.have.been.called Backbone.trigger 'authenticate:fail' Backbone.trigger 'authenticate:fail' Backbone.trigger 'authenticate:fail' Backbone.trigger 'authenticate:end' Backbone.trigger 'authenticate:end' Backbone.trigger 'authenticate:success' expect(@loginDialogView._authenticateFail).to.have.been.calledThrice expect(@loginDialogView._authenticateEnd).to.have.been.calledTwice expect(@loginDialogView._authenticateSuccess).to.have.been.calledOnce expect(@loginDialogView.toggle).not.to.have.been.called Backbone.trigger 'loginDialog:toggle' Backbone.trigger 'loginDialog:toggle' Backbone.trigger 'loginDialog:toggle' expect(@loginDialogView._authenticateFail).to.have.been.calledThrice expect(@loginDialogView._authenticateEnd).to.have.been.calledTwice expect(@loginDialogView._authenticateSuccess).to.have.been.calledOnce expect(@loginDialogView.toggle).to.have.been.calledThrice it 'listens to its model', -> @loginDialogView._disableButtons.reset() expect(@loginDialogView._disableButtons).not.to.have.been.called @loginDialogView.model.set 'loggedIn', true expect(@loginDialogView._disableButtons).to.have.been.calledOnce @loginDialogView.model.set 'loggedIn', false expect(@loginDialogView._disableButtons).to.have.been.calledTwice @loginDialogView.model.set 'serverURL', 'http://www.google.com' expect(@loginDialogView._disableButtons).to.have.been.calledTwice it 'responds to button clicks', -> $f = (selector) => @loginDialogView.$target.find(selector) expect(@loginDialogView.login).not.to.have.been.called expect(@loginDialogView.logout).not.to.have.been.called expect(@loginDialogView.forgotPassword).not.to.have.been.called $f('button.login').click() expect(@loginDialogView.login).to.have.been.calledOnce expect(@loginDialogView.logout).not.to.have.been.called expect(@loginDialogView.forgotPassword).not.to.have.been.called $f('button.forgot-password').click() expect(@loginDialogView.login).to.have.been.calledOnce expect(@loginDialogView.logout).not.to.have.been.called expect(@loginDialogView.forgotPassword).to.have.been.calledOnce @loginDialogView.model.set 'loggedIn', true $f('button.logout').click() expect(@loginDialogView.login).to.have.been.calledOnce expect(@loginDialogView.logout).to.have.been.calledOnce expect(@loginDialogView.forgotPassword).to.have.been.calledOnce it.skip 'responds to keyup/down events (???)', -> # NOTE: this test just is not working: the simulated keyup events are not # triggering the expected view methods. I can't figure out why. It's # probably either because there is some glitch involving triggering # keyup/down events on input elements or it has something to do with # the jQueryUI dialog box and/or the fact that the fixture is in a # hidden iframe. I am giving up on this for now. A good reference on # this stuff is http://stackoverflow.com/questions/832059/definitive-way-to-trigger-keypress-events-with-jquery expect(@loginDialogView.validate).not.to.have.been.called expect(@loginDialogView._submitWithEnter).not.to.have.been.called keyupEvent = $.Event 'keyup' keyupEvent.which = 13 @loginDialogView.$el.trigger keyupEvent expect(@loginDialogView.validate).not.to.have.been.called expect(@loginDialogView._submitWithEnter).not.to.have.been.called #@loginDialogView.dialogOpen() # even doing this doesn't help things ... @loginDialogView.$el.find('.dative-login-dialog-widget .username') .trigger keyupEvent # None of the following cause the `validate` method to be called, even # though it should be called (and is when you manually explore the GUI...) @loginDialogView.$source.find('.password').trigger keyupEvent @loginDialogView.$source.find('.password').first().trigger keyupEvent @loginDialogView.$target.find('.password').first().focus().trigger keyupEvent @loginDialogView.$source.find('.password').first().focus() @loginDialogView.$source.find('.password').trigger keyupEvent # This will fail expect(@loginDialogView.validate).to.have.been.calledOnce console.log @loginDialogView.validate.callCount # returns 0, should return 1 describe 'Validation', -> it 'prevents login attempts unless all fields have content', -> $f = (selector) => @loginDialogView.$target.find(selector) authenticateLoginSpy = sinon.spy() Backbone.on 'authenticate:login', authenticateLoginSpy expect(authenticateLoginSpy).not.to.have.been.called expect(@loginDialogView.login).not.to.have.been.called # authenticate:login not called because no values in inputs $f('button.login').click() expect(authenticateLoginSpy).not.to.have.been.called expect(@loginDialogView.login).to.have.been.calledOnce expect($f('.username-error')).to.have.text 'required' expect($f('.password-error')).to.have.text 'required' # authenticate:login not called because no values in username @loginDialogView._initializeDialog() # to reset things, e.g., error msgs $f('input.password').val 'somepassword' $f('button.login').click() expect(authenticateLoginSpy).not.to.have.been.called expect(@loginDialogView.login).to.have.been.calledTwice expect($f('.username-error')).to.have.text 'required' expect($f('.password-error')).to.have.text '' # authenticate:login IS called because there are values in both inputs @loginDialogView._initializeDialog() # to reset things, e.g., error msgs $f('input.password').val 'somepassword' $f('input.username').val 'someusername' $f('button.login').click() expect(authenticateLoginSpy).to.have.been.calledOnce expect(@loginDialogView.login).to.have.been.calledThrice expect($f('.username-error')).to.have.text '' expect($f('.password-error')).to.have.text '' Backbone.off 'authenticate:login', authenticateLoginSpy
208909
define (require) -> LoginDialogView = require '../../../scripts/views/login-dialog' ApplicationSettingsModel = require '../../../scripts/models/application-settings' describe 'Login Dialog View', -> before -> # Spy on methods... sinon.spy LoginDialogView::, '_authenticateFail' sinon.spy LoginDialogView::, '_authenticateEnd' sinon.spy LoginDialogView::, '_authenticateSuccess' sinon.spy LoginDialogView::, 'toggle' sinon.spy LoginDialogView::, 'validate' sinon.spy LoginDialogView::, '_submitWithEnter' sinon.spy LoginDialogView::, '_disableButtons' sinon.spy LoginDialogView::, 'login' sinon.spy LoginDialogView::, 'logout' sinon.spy LoginDialogView::, 'forgotPassword' beforeEach (done) -> # Create test fixture using js-fixtures https://github.com/badunk/js-fixtures fixtures.path = 'fixtures' callback = => @$fixture = fixtures.window().$("<div id='js-fixtures-fixture'></div>") @$ = (selector) -> @$fixture.find selector sinon.stub ApplicationSettingsModel::, 'logout' sinon.stub ApplicationSettingsModel::, 'authenticate' @checkIfLoggedInStub = sinon.stub() ApplicationSettingsModel::checkIfLoggedIn = @checkIfLoggedInStub @applicationSettingsModel = new ApplicationSettingsModel() @applicationSettingsModel.set 'loggedIn', false @loginDialogView = new LoginDialogView el: @$fixture model: @applicationSettingsModel @loginDialogView.render() done() fixtures.load('fixture.html', callback) afterEach -> fixtures.cleanUp() @loginDialogView.close() @loginDialogView.remove() # Reset spies & stubs @checkIfLoggedInStub.reset() ApplicationSettingsModel::logout.restore() ApplicationSettingsModel::authenticate.restore() LoginDialogView::_authenticateFail.reset() LoginDialogView::_authenticateEnd.reset() LoginDialogView::_authenticateSuccess.reset() LoginDialogView::toggle.reset() LoginDialogView::validate.reset() LoginDialogView::_submitWithEnter.reset() LoginDialogView::_disableButtons.reset() LoginDialogView::login.reset() LoginDialogView::logout.reset() LoginDialogView::forgotPassword.reset() after -> # Restore spied-on methods LoginDialogView::_authenticateFail.restore() LoginDialogView::_authenticateEnd.restore() LoginDialogView::_authenticateSuccess.restore() LoginDialogView::toggle.restore() LoginDialogView::validate.restore() LoginDialogView::_submitWithEnter.restore() LoginDialogView::_disableButtons.restore() LoginDialogView::login.restore() LoginDialogView::forgotPassword.restore() describe 'Initialization', -> it 'creates a jQueryUI dialog', -> $f = (selector) => @loginDialogView.$target.find(selector) expect($f('.dative-login-dialog-widget')).to.have.prop 'tagName', 'DIV' expect($f('.dative-login-dialog-widget .forgot-password')) .to.have.prop 'tagName', 'BUTTON' expect($f('.dative-login-dialog-widget .login')) .to.have.prop 'tagName', 'BUTTON' expect($f('.dative-login-dialog-widget .logout')) .to.have.prop 'tagName', 'BUTTON' expect($f('.blargon-five')).not.to.have.prop 'tagName' it 'dis/enables buttons according to authentication state', -> $f = (selector) => @loginDialogView.$target.find(selector) expect($f('button.logout')).to.have.class 'ui-state-disabled' expect($f('button.login')).not.to.have.class 'ui-state-disabled' expect($f('button.forgot-password')).not.to.have.class 'ui-state-disabled' expect($f('input.password')).not.to.have.attr 'disabled' expect($f('input.username')).not.to.have.attr 'disabled' @loginDialogView.model.set 'loggedIn', true expect($f('button.logout')).not.to.have.class 'ui-state-disabled' expect($f('button.login')).to.have.class 'ui-state-disabled' expect($f('button.forgot-password')).to.have.class 'ui-state-disabled' expect($f('input.password')).to.have.attr 'disabled' expect($f('input.username')).to.have.attr 'disabled' describe 'Event responsivity', -> it 'responds to Bacbkone-wide events', -> # Need to reset these spies because the app sett model can do unpredictable # things, depending on the state of the local storage app settings ... @loginDialogView._authenticateFail.reset() @loginDialogView._authenticateEnd.reset() @loginDialogView._authenticateSuccess.reset() @loginDialogView.toggle.reset() expect(@loginDialogView._authenticateFail).not.to.have.been.called expect(@loginDialogView._authenticateEnd).not.to.have.been.called expect(@loginDialogView._authenticateSuccess).not.to.have.been.called expect(@loginDialogView.toggle).not.to.have.been.called Backbone.trigger 'authenticate:fail' Backbone.trigger 'authenticate:fail' Backbone.trigger 'authenticate:fail' Backbone.trigger 'authenticate:end' Backbone.trigger 'authenticate:end' Backbone.trigger 'authenticate:success' expect(@loginDialogView._authenticateFail).to.have.been.calledThrice expect(@loginDialogView._authenticateEnd).to.have.been.calledTwice expect(@loginDialogView._authenticateSuccess).to.have.been.calledOnce expect(@loginDialogView.toggle).not.to.have.been.called Backbone.trigger 'loginDialog:toggle' Backbone.trigger 'loginDialog:toggle' Backbone.trigger 'loginDialog:toggle' expect(@loginDialogView._authenticateFail).to.have.been.calledThrice expect(@loginDialogView._authenticateEnd).to.have.been.calledTwice expect(@loginDialogView._authenticateSuccess).to.have.been.calledOnce expect(@loginDialogView.toggle).to.have.been.calledThrice it 'listens to its model', -> @loginDialogView._disableButtons.reset() expect(@loginDialogView._disableButtons).not.to.have.been.called @loginDialogView.model.set 'loggedIn', true expect(@loginDialogView._disableButtons).to.have.been.calledOnce @loginDialogView.model.set 'loggedIn', false expect(@loginDialogView._disableButtons).to.have.been.calledTwice @loginDialogView.model.set 'serverURL', 'http://www.google.com' expect(@loginDialogView._disableButtons).to.have.been.calledTwice it 'responds to button clicks', -> $f = (selector) => @loginDialogView.$target.find(selector) expect(@loginDialogView.login).not.to.have.been.called expect(@loginDialogView.logout).not.to.have.been.called expect(@loginDialogView.forgotPassword).not.to.have.been.called $f('button.login').click() expect(@loginDialogView.login).to.have.been.calledOnce expect(@loginDialogView.logout).not.to.have.been.called expect(@loginDialogView.forgotPassword).not.to.have.been.called $f('button.forgot-password').click() expect(@loginDialogView.login).to.have.been.calledOnce expect(@loginDialogView.logout).not.to.have.been.called expect(@loginDialogView.forgotPassword).to.have.been.calledOnce @loginDialogView.model.set 'loggedIn', true $f('button.logout').click() expect(@loginDialogView.login).to.have.been.calledOnce expect(@loginDialogView.logout).to.have.been.calledOnce expect(@loginDialogView.forgotPassword).to.have.been.calledOnce it.skip 'responds to keyup/down events (???)', -> # NOTE: this test just is not working: the simulated keyup events are not # triggering the expected view methods. I can't figure out why. It's # probably either because there is some glitch involving triggering # keyup/down events on input elements or it has something to do with # the jQueryUI dialog box and/or the fact that the fixture is in a # hidden iframe. I am giving up on this for now. A good reference on # this stuff is http://stackoverflow.com/questions/832059/definitive-way-to-trigger-keypress-events-with-jquery expect(@loginDialogView.validate).not.to.have.been.called expect(@loginDialogView._submitWithEnter).not.to.have.been.called keyupEvent = $.Event 'keyup' keyupEvent.which = 13 @loginDialogView.$el.trigger keyupEvent expect(@loginDialogView.validate).not.to.have.been.called expect(@loginDialogView._submitWithEnter).not.to.have.been.called #@loginDialogView.dialogOpen() # even doing this doesn't help things ... @loginDialogView.$el.find('.dative-login-dialog-widget .username') .trigger keyupEvent # None of the following cause the `validate` method to be called, even # though it should be called (and is when you manually explore the GUI...) @loginDialogView.$source.find('.password').trigger keyupEvent @loginDialogView.$source.find('.password').first().trigger keyupEvent @loginDialogView.$target.find('.password').first().focus().trigger keyupEvent @loginDialogView.$source.find('.password').first().focus() @loginDialogView.$source.find('.password').trigger keyupEvent # This will fail expect(@loginDialogView.validate).to.have.been.calledOnce console.log @loginDialogView.validate.callCount # returns 0, should return 1 describe 'Validation', -> it 'prevents login attempts unless all fields have content', -> $f = (selector) => @loginDialogView.$target.find(selector) authenticateLoginSpy = sinon.spy() Backbone.on 'authenticate:login', authenticateLoginSpy expect(authenticateLoginSpy).not.to.have.been.called expect(@loginDialogView.login).not.to.have.been.called # authenticate:login not called because no values in inputs $f('button.login').click() expect(authenticateLoginSpy).not.to.have.been.called expect(@loginDialogView.login).to.have.been.calledOnce expect($f('.username-error')).to.have.text 'required' expect($f('.password-error')).to.have.text 'required' # authenticate:login not called because no values in username @loginDialogView._initializeDialog() # to reset things, e.g., error msgs $f('input.password').val '<PASSWORD>' $f('button.login').click() expect(authenticateLoginSpy).not.to.have.been.called expect(@loginDialogView.login).to.have.been.calledTwice expect($f('.username-error')).to.have.text 'required' expect($f('.password-error')).to.have.text '' # authenticate:login IS called because there are values in both inputs @loginDialogView._initializeDialog() # to reset things, e.g., error msgs $f('input.password').val '<PASSWORD>' $f('input.username').val 'someusername' $f('button.login').click() expect(authenticateLoginSpy).to.have.been.calledOnce expect(@loginDialogView.login).to.have.been.calledThrice expect($f('.username-error')).to.have.text '' expect($f('.password-error')).to.have.text '' Backbone.off 'authenticate:login', authenticateLoginSpy
true
define (require) -> LoginDialogView = require '../../../scripts/views/login-dialog' ApplicationSettingsModel = require '../../../scripts/models/application-settings' describe 'Login Dialog View', -> before -> # Spy on methods... sinon.spy LoginDialogView::, '_authenticateFail' sinon.spy LoginDialogView::, '_authenticateEnd' sinon.spy LoginDialogView::, '_authenticateSuccess' sinon.spy LoginDialogView::, 'toggle' sinon.spy LoginDialogView::, 'validate' sinon.spy LoginDialogView::, '_submitWithEnter' sinon.spy LoginDialogView::, '_disableButtons' sinon.spy LoginDialogView::, 'login' sinon.spy LoginDialogView::, 'logout' sinon.spy LoginDialogView::, 'forgotPassword' beforeEach (done) -> # Create test fixture using js-fixtures https://github.com/badunk/js-fixtures fixtures.path = 'fixtures' callback = => @$fixture = fixtures.window().$("<div id='js-fixtures-fixture'></div>") @$ = (selector) -> @$fixture.find selector sinon.stub ApplicationSettingsModel::, 'logout' sinon.stub ApplicationSettingsModel::, 'authenticate' @checkIfLoggedInStub = sinon.stub() ApplicationSettingsModel::checkIfLoggedIn = @checkIfLoggedInStub @applicationSettingsModel = new ApplicationSettingsModel() @applicationSettingsModel.set 'loggedIn', false @loginDialogView = new LoginDialogView el: @$fixture model: @applicationSettingsModel @loginDialogView.render() done() fixtures.load('fixture.html', callback) afterEach -> fixtures.cleanUp() @loginDialogView.close() @loginDialogView.remove() # Reset spies & stubs @checkIfLoggedInStub.reset() ApplicationSettingsModel::logout.restore() ApplicationSettingsModel::authenticate.restore() LoginDialogView::_authenticateFail.reset() LoginDialogView::_authenticateEnd.reset() LoginDialogView::_authenticateSuccess.reset() LoginDialogView::toggle.reset() LoginDialogView::validate.reset() LoginDialogView::_submitWithEnter.reset() LoginDialogView::_disableButtons.reset() LoginDialogView::login.reset() LoginDialogView::logout.reset() LoginDialogView::forgotPassword.reset() after -> # Restore spied-on methods LoginDialogView::_authenticateFail.restore() LoginDialogView::_authenticateEnd.restore() LoginDialogView::_authenticateSuccess.restore() LoginDialogView::toggle.restore() LoginDialogView::validate.restore() LoginDialogView::_submitWithEnter.restore() LoginDialogView::_disableButtons.restore() LoginDialogView::login.restore() LoginDialogView::forgotPassword.restore() describe 'Initialization', -> it 'creates a jQueryUI dialog', -> $f = (selector) => @loginDialogView.$target.find(selector) expect($f('.dative-login-dialog-widget')).to.have.prop 'tagName', 'DIV' expect($f('.dative-login-dialog-widget .forgot-password')) .to.have.prop 'tagName', 'BUTTON' expect($f('.dative-login-dialog-widget .login')) .to.have.prop 'tagName', 'BUTTON' expect($f('.dative-login-dialog-widget .logout')) .to.have.prop 'tagName', 'BUTTON' expect($f('.blargon-five')).not.to.have.prop 'tagName' it 'dis/enables buttons according to authentication state', -> $f = (selector) => @loginDialogView.$target.find(selector) expect($f('button.logout')).to.have.class 'ui-state-disabled' expect($f('button.login')).not.to.have.class 'ui-state-disabled' expect($f('button.forgot-password')).not.to.have.class 'ui-state-disabled' expect($f('input.password')).not.to.have.attr 'disabled' expect($f('input.username')).not.to.have.attr 'disabled' @loginDialogView.model.set 'loggedIn', true expect($f('button.logout')).not.to.have.class 'ui-state-disabled' expect($f('button.login')).to.have.class 'ui-state-disabled' expect($f('button.forgot-password')).to.have.class 'ui-state-disabled' expect($f('input.password')).to.have.attr 'disabled' expect($f('input.username')).to.have.attr 'disabled' describe 'Event responsivity', -> it 'responds to Bacbkone-wide events', -> # Need to reset these spies because the app sett model can do unpredictable # things, depending on the state of the local storage app settings ... @loginDialogView._authenticateFail.reset() @loginDialogView._authenticateEnd.reset() @loginDialogView._authenticateSuccess.reset() @loginDialogView.toggle.reset() expect(@loginDialogView._authenticateFail).not.to.have.been.called expect(@loginDialogView._authenticateEnd).not.to.have.been.called expect(@loginDialogView._authenticateSuccess).not.to.have.been.called expect(@loginDialogView.toggle).not.to.have.been.called Backbone.trigger 'authenticate:fail' Backbone.trigger 'authenticate:fail' Backbone.trigger 'authenticate:fail' Backbone.trigger 'authenticate:end' Backbone.trigger 'authenticate:end' Backbone.trigger 'authenticate:success' expect(@loginDialogView._authenticateFail).to.have.been.calledThrice expect(@loginDialogView._authenticateEnd).to.have.been.calledTwice expect(@loginDialogView._authenticateSuccess).to.have.been.calledOnce expect(@loginDialogView.toggle).not.to.have.been.called Backbone.trigger 'loginDialog:toggle' Backbone.trigger 'loginDialog:toggle' Backbone.trigger 'loginDialog:toggle' expect(@loginDialogView._authenticateFail).to.have.been.calledThrice expect(@loginDialogView._authenticateEnd).to.have.been.calledTwice expect(@loginDialogView._authenticateSuccess).to.have.been.calledOnce expect(@loginDialogView.toggle).to.have.been.calledThrice it 'listens to its model', -> @loginDialogView._disableButtons.reset() expect(@loginDialogView._disableButtons).not.to.have.been.called @loginDialogView.model.set 'loggedIn', true expect(@loginDialogView._disableButtons).to.have.been.calledOnce @loginDialogView.model.set 'loggedIn', false expect(@loginDialogView._disableButtons).to.have.been.calledTwice @loginDialogView.model.set 'serverURL', 'http://www.google.com' expect(@loginDialogView._disableButtons).to.have.been.calledTwice it 'responds to button clicks', -> $f = (selector) => @loginDialogView.$target.find(selector) expect(@loginDialogView.login).not.to.have.been.called expect(@loginDialogView.logout).not.to.have.been.called expect(@loginDialogView.forgotPassword).not.to.have.been.called $f('button.login').click() expect(@loginDialogView.login).to.have.been.calledOnce expect(@loginDialogView.logout).not.to.have.been.called expect(@loginDialogView.forgotPassword).not.to.have.been.called $f('button.forgot-password').click() expect(@loginDialogView.login).to.have.been.calledOnce expect(@loginDialogView.logout).not.to.have.been.called expect(@loginDialogView.forgotPassword).to.have.been.calledOnce @loginDialogView.model.set 'loggedIn', true $f('button.logout').click() expect(@loginDialogView.login).to.have.been.calledOnce expect(@loginDialogView.logout).to.have.been.calledOnce expect(@loginDialogView.forgotPassword).to.have.been.calledOnce it.skip 'responds to keyup/down events (???)', -> # NOTE: this test just is not working: the simulated keyup events are not # triggering the expected view methods. I can't figure out why. It's # probably either because there is some glitch involving triggering # keyup/down events on input elements or it has something to do with # the jQueryUI dialog box and/or the fact that the fixture is in a # hidden iframe. I am giving up on this for now. A good reference on # this stuff is http://stackoverflow.com/questions/832059/definitive-way-to-trigger-keypress-events-with-jquery expect(@loginDialogView.validate).not.to.have.been.called expect(@loginDialogView._submitWithEnter).not.to.have.been.called keyupEvent = $.Event 'keyup' keyupEvent.which = 13 @loginDialogView.$el.trigger keyupEvent expect(@loginDialogView.validate).not.to.have.been.called expect(@loginDialogView._submitWithEnter).not.to.have.been.called #@loginDialogView.dialogOpen() # even doing this doesn't help things ... @loginDialogView.$el.find('.dative-login-dialog-widget .username') .trigger keyupEvent # None of the following cause the `validate` method to be called, even # though it should be called (and is when you manually explore the GUI...) @loginDialogView.$source.find('.password').trigger keyupEvent @loginDialogView.$source.find('.password').first().trigger keyupEvent @loginDialogView.$target.find('.password').first().focus().trigger keyupEvent @loginDialogView.$source.find('.password').first().focus() @loginDialogView.$source.find('.password').trigger keyupEvent # This will fail expect(@loginDialogView.validate).to.have.been.calledOnce console.log @loginDialogView.validate.callCount # returns 0, should return 1 describe 'Validation', -> it 'prevents login attempts unless all fields have content', -> $f = (selector) => @loginDialogView.$target.find(selector) authenticateLoginSpy = sinon.spy() Backbone.on 'authenticate:login', authenticateLoginSpy expect(authenticateLoginSpy).not.to.have.been.called expect(@loginDialogView.login).not.to.have.been.called # authenticate:login not called because no values in inputs $f('button.login').click() expect(authenticateLoginSpy).not.to.have.been.called expect(@loginDialogView.login).to.have.been.calledOnce expect($f('.username-error')).to.have.text 'required' expect($f('.password-error')).to.have.text 'required' # authenticate:login not called because no values in username @loginDialogView._initializeDialog() # to reset things, e.g., error msgs $f('input.password').val 'PI:PASSWORD:<PASSWORD>END_PI' $f('button.login').click() expect(authenticateLoginSpy).not.to.have.been.called expect(@loginDialogView.login).to.have.been.calledTwice expect($f('.username-error')).to.have.text 'required' expect($f('.password-error')).to.have.text '' # authenticate:login IS called because there are values in both inputs @loginDialogView._initializeDialog() # to reset things, e.g., error msgs $f('input.password').val 'PI:PASSWORD:<PASSWORD>END_PI' $f('input.username').val 'someusername' $f('button.login').click() expect(authenticateLoginSpy).to.have.been.calledOnce expect(@loginDialogView.login).to.have.been.calledThrice expect($f('.username-error')).to.have.text '' expect($f('.password-error')).to.have.text '' Backbone.off 'authenticate:login', authenticateLoginSpy
[ { "context": "cs/#info.info\n\nFramer.Info =\n\ttitle: \"\"\n\tauthor: \"Tony\"\n\ttwitter: \"\"\n\tdescription: \"\"\n\n\nFramer.Defaults.", "end": 146, "score": 0.9991326332092285, "start": 142, "tag": "NAME", "value": "Tony" } ]
59appleMusic.framer/app.coffee
gremjua-forks/100daysofframer
26
# Project Info # This info is presented in a widget when you share. # http://framerjs.com/docs/#info.info Framer.Info = title: "" author: "Tony" twitter: "" description: "" Framer.Defaults.Animation = curve: "spring(300,25,0)" bg = new Layer size: Screen, borderRadius: 20, html: "Song Playing Demo" backgroundColor: Color.random().darken(10), scale: 0.99 style: fontSize: "4rem", textAlign: "center" fontWeight: 300, lineHeight: "20rem" bg.states.add song: scale: 0.95, opacity: 0.8 playingBg = new Layer width: Screen.width, height: 300, backgroundColor: "#eee" maxY: Screen.height playingBg.states.add song: height: Screen.height, y: 70, borderRadius: 20 backgroundColor: "#fff" navBar = new Layer width: Screen.width, height: 130, html: "Bottom Navbar" backgroundColor: "#fff", maxY: Screen.height style: fontSize: "3rem", textAlign: "center", color: "#000" fontWeight: 300, lineHeight: "8rem" navBar.states.add song: y: Screen.height + navBar.height navBar.states.animationOptions = curve: "ease", time: 0.2 coverImg = new Layer size: 130, parent: playingBg, x: 10, y: 15 image: "images/album-covers-01.jpg" coverImg.states.add song: scale: 5, x: Align.center, y: 315 controls = new Layer width: Screen.width, height: 400, backgroundColor: "#fff" maxY: Screen.height - 100, scale: 0, originY: 1, parent: playingBg controls.states.add song: scale: 1 controls.states.animationOptions = curve: "ease", time: 0.25 controlsImg = new Layer width: 750, height: 386, parent: controls, maxY: controls.height, scale: 0.88 image: "images/controls.jpg" currentlyPlayingText = new Layer html: "Currently Playing Song Name" backgroundColor: "", width: Screen.width x: 60, parent: playingBg, color: "#333" style: fontSize: "2.3rem", lineHeight: "10rem" textAlign: "center", fontWeight: "600" currentlyPlayingText.states.add song: scale: 1.22, x: 0, y: 742 currentlyPlayingText.states.animationOptions = curve: "ease", time: 0.25 play = new Layer size: Screen, backgroundColor: "" play.onClick -> for layer in [bg, navBar, playingBg, coverImg, controls, currentlyPlayingText] layer.states.next()
103936
# Project Info # This info is presented in a widget when you share. # http://framerjs.com/docs/#info.info Framer.Info = title: "" author: "<NAME>" twitter: "" description: "" Framer.Defaults.Animation = curve: "spring(300,25,0)" bg = new Layer size: Screen, borderRadius: 20, html: "Song Playing Demo" backgroundColor: Color.random().darken(10), scale: 0.99 style: fontSize: "4rem", textAlign: "center" fontWeight: 300, lineHeight: "20rem" bg.states.add song: scale: 0.95, opacity: 0.8 playingBg = new Layer width: Screen.width, height: 300, backgroundColor: "#eee" maxY: Screen.height playingBg.states.add song: height: Screen.height, y: 70, borderRadius: 20 backgroundColor: "#fff" navBar = new Layer width: Screen.width, height: 130, html: "Bottom Navbar" backgroundColor: "#fff", maxY: Screen.height style: fontSize: "3rem", textAlign: "center", color: "#000" fontWeight: 300, lineHeight: "8rem" navBar.states.add song: y: Screen.height + navBar.height navBar.states.animationOptions = curve: "ease", time: 0.2 coverImg = new Layer size: 130, parent: playingBg, x: 10, y: 15 image: "images/album-covers-01.jpg" coverImg.states.add song: scale: 5, x: Align.center, y: 315 controls = new Layer width: Screen.width, height: 400, backgroundColor: "#fff" maxY: Screen.height - 100, scale: 0, originY: 1, parent: playingBg controls.states.add song: scale: 1 controls.states.animationOptions = curve: "ease", time: 0.25 controlsImg = new Layer width: 750, height: 386, parent: controls, maxY: controls.height, scale: 0.88 image: "images/controls.jpg" currentlyPlayingText = new Layer html: "Currently Playing Song Name" backgroundColor: "", width: Screen.width x: 60, parent: playingBg, color: "#333" style: fontSize: "2.3rem", lineHeight: "10rem" textAlign: "center", fontWeight: "600" currentlyPlayingText.states.add song: scale: 1.22, x: 0, y: 742 currentlyPlayingText.states.animationOptions = curve: "ease", time: 0.25 play = new Layer size: Screen, backgroundColor: "" play.onClick -> for layer in [bg, navBar, playingBg, coverImg, controls, currentlyPlayingText] layer.states.next()
true
# Project Info # This info is presented in a widget when you share. # http://framerjs.com/docs/#info.info Framer.Info = title: "" author: "PI:NAME:<NAME>END_PI" twitter: "" description: "" Framer.Defaults.Animation = curve: "spring(300,25,0)" bg = new Layer size: Screen, borderRadius: 20, html: "Song Playing Demo" backgroundColor: Color.random().darken(10), scale: 0.99 style: fontSize: "4rem", textAlign: "center" fontWeight: 300, lineHeight: "20rem" bg.states.add song: scale: 0.95, opacity: 0.8 playingBg = new Layer width: Screen.width, height: 300, backgroundColor: "#eee" maxY: Screen.height playingBg.states.add song: height: Screen.height, y: 70, borderRadius: 20 backgroundColor: "#fff" navBar = new Layer width: Screen.width, height: 130, html: "Bottom Navbar" backgroundColor: "#fff", maxY: Screen.height style: fontSize: "3rem", textAlign: "center", color: "#000" fontWeight: 300, lineHeight: "8rem" navBar.states.add song: y: Screen.height + navBar.height navBar.states.animationOptions = curve: "ease", time: 0.2 coverImg = new Layer size: 130, parent: playingBg, x: 10, y: 15 image: "images/album-covers-01.jpg" coverImg.states.add song: scale: 5, x: Align.center, y: 315 controls = new Layer width: Screen.width, height: 400, backgroundColor: "#fff" maxY: Screen.height - 100, scale: 0, originY: 1, parent: playingBg controls.states.add song: scale: 1 controls.states.animationOptions = curve: "ease", time: 0.25 controlsImg = new Layer width: 750, height: 386, parent: controls, maxY: controls.height, scale: 0.88 image: "images/controls.jpg" currentlyPlayingText = new Layer html: "Currently Playing Song Name" backgroundColor: "", width: Screen.width x: 60, parent: playingBg, color: "#333" style: fontSize: "2.3rem", lineHeight: "10rem" textAlign: "center", fontWeight: "600" currentlyPlayingText.states.add song: scale: 1.22, x: 0, y: 742 currentlyPlayingText.states.animationOptions = curve: "ease", time: 0.25 play = new Layer size: Screen, backgroundColor: "" play.onClick -> for layer in [bg, navBar, playingBg, coverImg, controls, currentlyPlayingText] layer.states.next()
[ { "context": "ivity.camelizeKeys = yes\nApp.Activity.primaryKey = '_id'\nApp.Activity.collectionKey = 'activities'\nApp.Ac", "end": 1170, "score": 0.7105882167816162, "start": 1166, "tag": "KEY", "value": "'_id" } ]
app/models/activity.coffee
robinandeer/scout
4
NewRESTAdapter = require 'adapters/new-rest' MomentDate = require 'helpers/moment-date' App.Activity = Ember.Model.extend _id: Em.attr() activityId: Em.attr() category: Em.attr() context: Em.attr() contextId: Em.attr() ecosystem: Em.attr() userId: Em.attr() user: Em.belongsTo 'App.User', {key: 'user_id'} createdAt: Em.attr(MomentDate) updatedAt: Em.attr(MomentDate) title: Em.attr() caption: Em.attr() content: Em.attr() tags: Em.attr() firstTag: (-> return @get 'tags.0' ).property 'tags' entypoIcon: (-> tag = @get 'firstTag' if tag is 'action' return 'icon-alert' else if tag is 'conclusion' return 'icon-check' else # 'finding' by default return 'icon-search' ).property 'firstTag' ActivityAdapter = NewRESTAdapter.extend find: (record, id) -> url = @buildURL record.constructor, id return @ajax(url).then (data) => @didFind record, id, data return record didFind: (record, id, data) -> Ember.run record, record.load, id, data.activities Ember.run App.User, App.User.load, data.user App.Activity.camelizeKeys = yes App.Activity.primaryKey = '_id' App.Activity.collectionKey = 'activities' App.Activity.url = '/api/v1/activities' App.Activity.adapter = ActivityAdapter.create() module.exports = App.Activity
42409
NewRESTAdapter = require 'adapters/new-rest' MomentDate = require 'helpers/moment-date' App.Activity = Ember.Model.extend _id: Em.attr() activityId: Em.attr() category: Em.attr() context: Em.attr() contextId: Em.attr() ecosystem: Em.attr() userId: Em.attr() user: Em.belongsTo 'App.User', {key: 'user_id'} createdAt: Em.attr(MomentDate) updatedAt: Em.attr(MomentDate) title: Em.attr() caption: Em.attr() content: Em.attr() tags: Em.attr() firstTag: (-> return @get 'tags.0' ).property 'tags' entypoIcon: (-> tag = @get 'firstTag' if tag is 'action' return 'icon-alert' else if tag is 'conclusion' return 'icon-check' else # 'finding' by default return 'icon-search' ).property 'firstTag' ActivityAdapter = NewRESTAdapter.extend find: (record, id) -> url = @buildURL record.constructor, id return @ajax(url).then (data) => @didFind record, id, data return record didFind: (record, id, data) -> Ember.run record, record.load, id, data.activities Ember.run App.User, App.User.load, data.user App.Activity.camelizeKeys = yes App.Activity.primaryKey = <KEY>' App.Activity.collectionKey = 'activities' App.Activity.url = '/api/v1/activities' App.Activity.adapter = ActivityAdapter.create() module.exports = App.Activity
true
NewRESTAdapter = require 'adapters/new-rest' MomentDate = require 'helpers/moment-date' App.Activity = Ember.Model.extend _id: Em.attr() activityId: Em.attr() category: Em.attr() context: Em.attr() contextId: Em.attr() ecosystem: Em.attr() userId: Em.attr() user: Em.belongsTo 'App.User', {key: 'user_id'} createdAt: Em.attr(MomentDate) updatedAt: Em.attr(MomentDate) title: Em.attr() caption: Em.attr() content: Em.attr() tags: Em.attr() firstTag: (-> return @get 'tags.0' ).property 'tags' entypoIcon: (-> tag = @get 'firstTag' if tag is 'action' return 'icon-alert' else if tag is 'conclusion' return 'icon-check' else # 'finding' by default return 'icon-search' ).property 'firstTag' ActivityAdapter = NewRESTAdapter.extend find: (record, id) -> url = @buildURL record.constructor, id return @ajax(url).then (data) => @didFind record, id, data return record didFind: (record, id, data) -> Ember.run record, record.load, id, data.activities Ember.run App.User, App.User.load, data.user App.Activity.camelizeKeys = yes App.Activity.primaryKey = PI:KEY:<KEY>END_PI' App.Activity.collectionKey = 'activities' App.Activity.url = '/api/v1/activities' App.Activity.adapter = ActivityAdapter.create() module.exports = App.Activity
[ { "context": "-noise-in-javascript_31.html\r\n// This is a port of Ken Perlin's Java code. The\r\n// original Java code is at htt", "end": 114, "score": 0.996938169002533, "start": 104, "tag": "NAME", "value": "Ken Perlin" } ]
src/perlin.coffee
vjeux/jsRayTracer
55
` // http://asserttrue.blogspot.com/2011/12/perlin-noise-in-javascript_31.html // This is a port of Ken Perlin's Java code. The // original Java code is at http://cs.nyu.edu/%7Eperlin/noise/. // Note that in this version, a number from 0 to 1 is returned. PerlinNoise = new function() { this.noise = function(x, y, z) { var p = new Array(512) var permutation = [ 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 ]; for (var i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; var X = Math.floor(x) & 255, // FIND UNIT CUBE THAT Y = Math.floor(y) & 255, // CONTAINS POINT. Z = Math.floor(z) & 255; x -= Math.floor(x); // FIND RELATIVE X,Y,Z y -= Math.floor(y); // OF POINT IN CUBE. z -= Math.floor(z); var u = fade(x), // COMPUTE FADE CURVES v = fade(y), // FOR EACH OF X,Y,Z. w = fade(z); var A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, // HASH COORDINATES OF B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; // THE 8 CUBE CORNERS, return scale(lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), // AND ADD grad(p[BA ], x-1, y , z )), // BLENDED lerp(u, grad(p[AB ], x , y-1, z ), // RESULTS grad(p[BB ], x-1, y-1, z ))),// FROM 8 lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), // CORNERS grad(p[BA+1], x-1, y , z-1 )), // OF CUBE lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 ))))); } function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); } function lerp( t, a, b) { return a + t * (b - a); } function grad(hash, x, y, z) { var h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE var u = h<8 ? x : y, // INTO 12 GRADIENT DIRECTIONS. v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } function scale(n) { return n; /*return (1 + n)/2;*/ } } ` clamp = (x, min, max) -> return min if x < min return max if x > max x self.perlin = (pos, id, persistence, octaves, frequence) -> pos = vec3.scale pos, frequence, vec3.create() noise = 0 frequency = 1 amplitude = 1 for i in [0 ... octaves] noise += amplitude * PerlinNoise.noise pos[0] * frequency, pos[1] * frequency, pos[2] * frequency frequency *= 2 amplitude *= persistence if id == 2 noise *= 20 noise = noise - Math.floor noise if id == 3 noise = Math.cos noise (clamp(noise, -1, 1) + 1) / 2
169739
` // http://asserttrue.blogspot.com/2011/12/perlin-noise-in-javascript_31.html // This is a port of <NAME>'s Java code. The // original Java code is at http://cs.nyu.edu/%7Eperlin/noise/. // Note that in this version, a number from 0 to 1 is returned. PerlinNoise = new function() { this.noise = function(x, y, z) { var p = new Array(512) var permutation = [ 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 ]; for (var i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; var X = Math.floor(x) & 255, // FIND UNIT CUBE THAT Y = Math.floor(y) & 255, // CONTAINS POINT. Z = Math.floor(z) & 255; x -= Math.floor(x); // FIND RELATIVE X,Y,Z y -= Math.floor(y); // OF POINT IN CUBE. z -= Math.floor(z); var u = fade(x), // COMPUTE FADE CURVES v = fade(y), // FOR EACH OF X,Y,Z. w = fade(z); var A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, // HASH COORDINATES OF B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; // THE 8 CUBE CORNERS, return scale(lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), // AND ADD grad(p[BA ], x-1, y , z )), // BLENDED lerp(u, grad(p[AB ], x , y-1, z ), // RESULTS grad(p[BB ], x-1, y-1, z ))),// FROM 8 lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), // CORNERS grad(p[BA+1], x-1, y , z-1 )), // OF CUBE lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 ))))); } function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); } function lerp( t, a, b) { return a + t * (b - a); } function grad(hash, x, y, z) { var h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE var u = h<8 ? x : y, // INTO 12 GRADIENT DIRECTIONS. v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } function scale(n) { return n; /*return (1 + n)/2;*/ } } ` clamp = (x, min, max) -> return min if x < min return max if x > max x self.perlin = (pos, id, persistence, octaves, frequence) -> pos = vec3.scale pos, frequence, vec3.create() noise = 0 frequency = 1 amplitude = 1 for i in [0 ... octaves] noise += amplitude * PerlinNoise.noise pos[0] * frequency, pos[1] * frequency, pos[2] * frequency frequency *= 2 amplitude *= persistence if id == 2 noise *= 20 noise = noise - Math.floor noise if id == 3 noise = Math.cos noise (clamp(noise, -1, 1) + 1) / 2
true
` // http://asserttrue.blogspot.com/2011/12/perlin-noise-in-javascript_31.html // This is a port of PI:NAME:<NAME>END_PI's Java code. The // original Java code is at http://cs.nyu.edu/%7Eperlin/noise/. // Note that in this version, a number from 0 to 1 is returned. PerlinNoise = new function() { this.noise = function(x, y, z) { var p = new Array(512) var permutation = [ 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 ]; for (var i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; var X = Math.floor(x) & 255, // FIND UNIT CUBE THAT Y = Math.floor(y) & 255, // CONTAINS POINT. Z = Math.floor(z) & 255; x -= Math.floor(x); // FIND RELATIVE X,Y,Z y -= Math.floor(y); // OF POINT IN CUBE. z -= Math.floor(z); var u = fade(x), // COMPUTE FADE CURVES v = fade(y), // FOR EACH OF X,Y,Z. w = fade(z); var A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, // HASH COORDINATES OF B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; // THE 8 CUBE CORNERS, return scale(lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), // AND ADD grad(p[BA ], x-1, y , z )), // BLENDED lerp(u, grad(p[AB ], x , y-1, z ), // RESULTS grad(p[BB ], x-1, y-1, z ))),// FROM 8 lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), // CORNERS grad(p[BA+1], x-1, y , z-1 )), // OF CUBE lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 ))))); } function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); } function lerp( t, a, b) { return a + t * (b - a); } function grad(hash, x, y, z) { var h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE var u = h<8 ? x : y, // INTO 12 GRADIENT DIRECTIONS. v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } function scale(n) { return n; /*return (1 + n)/2;*/ } } ` clamp = (x, min, max) -> return min if x < min return max if x > max x self.perlin = (pos, id, persistence, octaves, frequence) -> pos = vec3.scale pos, frequence, vec3.create() noise = 0 frequency = 1 amplitude = 1 for i in [0 ... octaves] noise += amplitude * PerlinNoise.noise pos[0] * frequency, pos[1] * frequency, pos[2] * frequency frequency *= 2 amplitude *= persistence if id == 2 noise *= 20 noise = noise - Math.floor noise if id == 3 noise = Math.cos noise (clamp(noise, -1, 1) + 1) / 2
[ { "context": ": InputHelper.makeRadioToggle attr, 'lastname', ['Hans', 'Franz'] \n @makeRadioToggle = (attr, label,", "end": 1644, "score": 0.9992735385894775, "start": 1640, "tag": "NAME", "value": "Hans" }, { "context": "elper.makeRadioToggle attr, 'lastname', ['Hans', 'Franz']...
client/app/scripts/components/util/ui/InputHelper.coffee
softwarerero/protothril
0
module.exports = class InputHelper # use like: InputHelper.makeInput attr, 'lastname', {mask: '####-##-___-# $'} @makeInput = (attr, field, params) -> changeHandler = if params.mask setMaskValue(attr[field]) else m.withAttr("value", attr[field]) [ LABEL {for: field}, t9n field input = INPUT {config: applyDataMask, id: field, onchange: changeHandler, value: attr[field]?(), 'data-mask': params.mask} ] applyDataMask = (element, isInitialized, context) -> if isInitialized then return mask = element.dataset.mask if not mask then return # Replace `#` characters with characters from `data` applyMask = (data) -> newMask = for char in mask if char isnt '#' char else if data.length is 0 char else data.shift() newMask.join('') reapplyMask = (data) -> applyMask(stripMask(data)) changed = () -> oldStart = element.selectionStart oldEnd = element.selectionEnd element.value = reapplyMask(element.value) element.selectionStart = oldStart element.selectionEnd = oldEnd element.addEventListener('click', changed) element.addEventListener('keyup', changed) # For now, this just strips everything that's not a number stripMask = (maskedData) -> isDigit = (char) -> /\d/.test(char) maskedData.split('').filter(isDigit) setMaskValue = (field) -> (e) -> value = e.currentTarget.value value = stripMask value value = value.join '' field value #use: InputHelper.makeRadioToggle attr, 'lastname', ['Hans', 'Franz'] @makeRadioToggle = (attr, label, values) -> field = attr[label] changed = () -> value = document.querySelector('input[name="mx"]:checked').id # console.log 'changed: ' + value # console.log label + ': ' + field() field(value) config = (element, isInitialized, context) -> if isInitialized then return element.addEventListener('click', changed) m "div", [ m "label", t9n label for v in values options = {type: 'radio', id: v, name: 'mx', config: config} if (v is field()) options.checked = 'checked' m "span", {class: "mx-button"}, [ m "input", options m "label", {class: "", for: v}, t9n v ] ]
121353
module.exports = class InputHelper # use like: InputHelper.makeInput attr, 'lastname', {mask: '####-##-___-# $'} @makeInput = (attr, field, params) -> changeHandler = if params.mask setMaskValue(attr[field]) else m.withAttr("value", attr[field]) [ LABEL {for: field}, t9n field input = INPUT {config: applyDataMask, id: field, onchange: changeHandler, value: attr[field]?(), 'data-mask': params.mask} ] applyDataMask = (element, isInitialized, context) -> if isInitialized then return mask = element.dataset.mask if not mask then return # Replace `#` characters with characters from `data` applyMask = (data) -> newMask = for char in mask if char isnt '#' char else if data.length is 0 char else data.shift() newMask.join('') reapplyMask = (data) -> applyMask(stripMask(data)) changed = () -> oldStart = element.selectionStart oldEnd = element.selectionEnd element.value = reapplyMask(element.value) element.selectionStart = oldStart element.selectionEnd = oldEnd element.addEventListener('click', changed) element.addEventListener('keyup', changed) # For now, this just strips everything that's not a number stripMask = (maskedData) -> isDigit = (char) -> /\d/.test(char) maskedData.split('').filter(isDigit) setMaskValue = (field) -> (e) -> value = e.currentTarget.value value = stripMask value value = value.join '' field value #use: InputHelper.makeRadioToggle attr, 'lastname', ['<NAME>', '<NAME>'] @makeRadioToggle = (attr, label, values) -> field = attr[label] changed = () -> value = document.querySelector('input[name="mx"]:checked').id # console.log 'changed: ' + value # console.log label + ': ' + field() field(value) config = (element, isInitialized, context) -> if isInitialized then return element.addEventListener('click', changed) m "div", [ m "label", t9n label for v in values options = {type: 'radio', id: v, name: 'mx', config: config} if (v is field()) options.checked = 'checked' m "span", {class: "mx-button"}, [ m "input", options m "label", {class: "", for: v}, t9n v ] ]
true
module.exports = class InputHelper # use like: InputHelper.makeInput attr, 'lastname', {mask: '####-##-___-# $'} @makeInput = (attr, field, params) -> changeHandler = if params.mask setMaskValue(attr[field]) else m.withAttr("value", attr[field]) [ LABEL {for: field}, t9n field input = INPUT {config: applyDataMask, id: field, onchange: changeHandler, value: attr[field]?(), 'data-mask': params.mask} ] applyDataMask = (element, isInitialized, context) -> if isInitialized then return mask = element.dataset.mask if not mask then return # Replace `#` characters with characters from `data` applyMask = (data) -> newMask = for char in mask if char isnt '#' char else if data.length is 0 char else data.shift() newMask.join('') reapplyMask = (data) -> applyMask(stripMask(data)) changed = () -> oldStart = element.selectionStart oldEnd = element.selectionEnd element.value = reapplyMask(element.value) element.selectionStart = oldStart element.selectionEnd = oldEnd element.addEventListener('click', changed) element.addEventListener('keyup', changed) # For now, this just strips everything that's not a number stripMask = (maskedData) -> isDigit = (char) -> /\d/.test(char) maskedData.split('').filter(isDigit) setMaskValue = (field) -> (e) -> value = e.currentTarget.value value = stripMask value value = value.join '' field value #use: InputHelper.makeRadioToggle attr, 'lastname', ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] @makeRadioToggle = (attr, label, values) -> field = attr[label] changed = () -> value = document.querySelector('input[name="mx"]:checked').id # console.log 'changed: ' + value # console.log label + ': ' + field() field(value) config = (element, isInitialized, context) -> if isInitialized then return element.addEventListener('click', changed) m "div", [ m "label", t9n label for v in values options = {type: 'radio', id: v, name: 'mx', config: config} if (v is field()) options.checked = 'checked' m "span", {class: "mx-button"}, [ m "input", options m "label", {class: "", for: v}, t9n v ] ]
[ { "context": "#\n# Copyright 2014 Carsten Klein\n#\n# Licensed under the Apache License, Version 2.", "end": 32, "score": 0.9998666644096375, "start": 19, "tag": "NAME", "value": "Carsten Klein" } ]
src/monkeypatch.coffee
vibejs/vibejs-subclassof
0
# # Copyright 2014 Carsten Klein # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # We require some monkey patching to make standard classes # work with subclassof # Standard Exceptions # guard preventing us from installing twice unless EvalError.super_? EvalError.super_ = Error RangeError.super_ = Error ReferenceError.super_ = Error SyntaxError.super_ = Error TypeError.super_ = Error URIError.super_ = Error
87565
# # Copyright 2014 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # We require some monkey patching to make standard classes # work with subclassof # Standard Exceptions # guard preventing us from installing twice unless EvalError.super_? EvalError.super_ = Error RangeError.super_ = Error ReferenceError.super_ = Error SyntaxError.super_ = Error TypeError.super_ = Error URIError.super_ = Error
true
# # Copyright 2014 PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # We require some monkey patching to make standard classes # work with subclassof # Standard Exceptions # guard preventing us from installing twice unless EvalError.super_? EvalError.super_ = Error RangeError.super_ = Error ReferenceError.super_ = Error SyntaxError.super_ = Error TypeError.super_ = Error URIError.super_ = Error
[ { "context": "um-set-1-label'\n ,\n key: 'enum-set-2-key'\n label: 'enum-set-2-label'\n ", "end": 1818, "score": 0.5461097955703735, "start": 1818, "tag": "KEY", "value": "" }, { "context": "-set-1-label'\n ,\n key: 'enum-set-2-key'\n ...
test/enum-validator.spec.coffee
sphereio/sphere-product-import
5
debug = require('debug')('spec:enum-validator') _ = require 'underscore' _.mixin require 'underscore-mixins' {EnumValidator} = require '../lib' Promise = require 'bluebird' slugify = require 'underscore.string/slugify' {ExtendedLogger} = require 'sphere-node-utils' package_json = require '../package.json' sampleVariant = sku: 'sample_sku' attributes: [ name: 'sample-localized-text-attribute' value: en: 'sample localized text value' , name: 'sample-lenum-attribute' value: 'lenum-key-2' , name: 'sample-enum-attribute' value: 'enum-1-key' , name: 'sample-set-enum-attribute' value: 'enum-set-2-key' ] sampleProductType = id: 'sample_product_type_id' version: 1 name: 'sample product type name' attributes: [ name: 'sample-localized-text-attribute' label: en: 'Sample Localized Text Attribute' isRequired: true type: name: 'text' , name: 'sample-lenum-attribute' label: en: 'Sample Lenum Attribute' type: name: 'lenum' values: [ key: 'lenum-key-1' label: en: 'lenum-1-label-en' de: 'lenum-1-label-de' , key: 'lenum-key-2' label: en: 'lenum-2-label-en' de: 'lenum-2-label-de' ] , name: 'sample-enum-attribute' label: en: 'Sample Enum Attribute' type: name: 'enum' values: [ key: 'enum-1-key' label: 'enum-1-label' , key: 'enum-2-key' label: 'enum-2-label' ] , name: 'sample-set-enum-attribute' label: en: 'Sample Set Enum Attribute' type: name: 'set' elementType: name: 'enum' values: [ key: 'enum-set-1-key' label: 'enum-set-1-label' , key: 'enum-set-2-key' label: 'enum-set-2-label' ] , name: 'sample-set-lenum-attribute' label: en: 'Sample Set Lenum Attribute' type: name: 'set' elementType: name: 'lenum' values: [ key: 'lenum-set-1-key' label: en: 'lenum-set-1-label-en' de: 'lenum-set-1-label-de' , key: 'lenum-set-2-key' label: en: 'lenum-set-2-label-en' de: 'lenum-set-2-label-de' ] ] describe 'Enum Validator unit tests', -> beforeEach -> @logger = new ExtendedLogger additionalFields: project_key: 'enumValidator' logConfig: name: "#{package_json.name}-#{package_json.version}" streams: [ { level: 'info', stream: process.stdout } ] @import = new EnumValidator @logger, null it ' should initialize', -> expect(@import).toBeDefined() it ' should filter enum and lenum attributes', -> enums = _.filter(sampleProductType.attributes, @import._enumLenumFilterPredicate) expect(_.size enums).toBe 2 it ' should filter set of enum attributes', -> enums = _.filter(sampleProductType.attributes, @import._enumSetFilterPredicate) expect(_.size enums).toBe 1 it ' should filter set of lenum attributes', -> enums = _.filter(sampleProductType.attributes, @import._lenumSetFilterPredicate) expect(_.size enums).toBe 1 it ' should extract enum attributes from product type', -> enums = @import._extractEnumAttributesFromProductType(sampleProductType) expect(_.size enums).toBe 4 it ' should fetch enum attributes from sample product type', -> enums = @import._fetchEnumAttributesOfProductType(sampleProductType) expect(_.size enums).toBe 4 it ' should fetch enum attribute names of sample product type', -> expectedNames = ['sample-lenum-attribute', 'sample-enum-attribute', 'sample-set-enum-attribute', 'sample-set-lenum-attribute'] enumNames = @import._fetchEnumAttributeNamesOfProductType(sampleProductType) expect(enumNames).toEqual expectedNames it ' should fetch enum attribute names of sample product type from cache', -> spyOn(@import, '_fetchEnumAttributesOfProductType').andCallThrough() @import._fetchEnumAttributeNamesOfProductType(sampleProductType) enumNames = @import._fetchEnumAttributeNamesOfProductType(sampleProductType) expect(_.size enumNames).toBe 4 expect(@import._fetchEnumAttributesOfProductType.calls.length).toEqual 1 expect(@import._cache.productTypeEnumMap["#{sampleProductType.id}_names"]).toBeDefined() it ' should detect enum attribute', -> sampleEnumAttribute = name: 'sample-enum-attribute' sampleAttribute = name: 'sample-text-attribute' enumAttributeNames = ['sample-lenum-attribute', 'sample-enum-attribute', 'sample-set-enum-attribute', 'sample-set-lenum-attribute'] expect(@import._isEnumVariantAttribute(sampleEnumAttribute, enumAttributeNames)).toBeTruthy() expect(@import._isEnumVariantAttribute(sampleAttribute, enumAttributeNames)).toBeFalsy() it ' should fetch enum attributes from sample variant', -> enums = @import._fetchEnumAttributesFromVariant(sampleVariant,sampleProductType) expect(_.size enums).toBe 3 it ' should fetch all enum attributes from all product variants', -> sampleProduct = name: 'sample Product' productType: id: 'sample_product_type_id' masterVariant: _.deepClone sampleVariant variants: [ _.deepClone sampleVariant , _.deepClone sampleVariant ] enums = @import._fetchEnumAttributesFromProduct(sampleProduct, sampleProductType) expect(_.size enums).toBe 9 it ' should detect enum key correctly', -> enumAttributeTrue = name: 'sample-enum-attribute' value: 'enum-2-key' enumAttributeFalse = name: 'sample-enum-attribute' value: 'enum-3-key' lenumAttributeTrue = name: 'sample-lenum-attribute' value: 'lenum-key-2' lenumAttributeFalse = name: 'sample-lenum-attribute' value: 'lenum-key-3' lenumSetAttributeTrue = name: 'sample-set-lenum-attribute' value: 'lenum-set-1-key' lenumSetAttributeFalse = name: 'sample-set-lenum-attribute' value: 'lenum-set-5-key' enumSetAttributeTrue = name: 'sample-set-enum-attribute' value: 'enum-set-1-key' enumSetAttributeFalse = name: 'sample-set-enum-attribute' value: 'enum-set-5-key' expect(@import._isEnumKeyPresent(enumAttributeTrue, sampleProductType.attributes[2])).toBeDefined() expect(@import._isEnumKeyPresent(enumAttributeFalse, sampleProductType.attributes[2])).toBeUndefined() expect(@import._isEnumKeyPresent(lenumAttributeTrue, sampleProductType.attributes[1])).toBeDefined() expect(@import._isEnumKeyPresent(lenumAttributeFalse, sampleProductType.attributes[1])).toBeUndefined() expect(@import._isEnumKeyPresent(lenumSetAttributeTrue, sampleProductType.attributes[4])).toBeDefined() expect(@import._isEnumKeyPresent(lenumSetAttributeFalse, sampleProductType.attributes[4])).toBeUndefined() expect(@import._isEnumKeyPresent(enumSetAttributeTrue, sampleProductType.attributes[3])).toBeDefined() expect(@import._isEnumKeyPresent(enumSetAttributeFalse, sampleProductType.attributes[3])).toBeUndefined() it ' should generate correct enum update action', -> enumAttribute = name: 'sample-enum-attribute' value: 'enum-3-key' expectedUpdateAction = action: 'addPlainEnumValue' attributeName: 'sample-enum-attribute' value: key: 'enum-3-key' label: 'enum-3-key' expect(@import._generateUpdateAction(enumAttribute, sampleProductType.attributes[2])).toEqual expectedUpdateAction it ' should generate correct lenum update action', -> lenumAttribute = name: 'sample-lenum-attribute' value: 'lenum-3-key' expectedUpdateAction = action: 'addLocalizedEnumValue' attributeName: 'sample-lenum-attribute' value: key: 'lenum-3-key' label: en: 'lenum-3-key' de: 'lenum-3-key' fr: 'lenum-3-key' it: 'lenum-3-key' es: 'lenum-3-key' expect(@import._generateUpdateAction(lenumAttribute, sampleProductType.attributes[1])).toEqual expectedUpdateAction it ' should generate correct enum set update action', -> enumSetAttributeMultiValue = name: 'sample-set-enum-attribute' value: [ 'enum-set-5-key' , 'enum-set-6-key' ] expectedUpdateActionMultiValue = [ action: 'addPlainEnumValue' attributeName: 'sample-set-enum-attribute' value: key: 'enum-set-5-key' label: 'enum-set-5-key' , action: 'addPlainEnumValue' attributeName: 'sample-set-enum-attribute' value: key: 'enum-set-6-key' label: 'enum-set-6-key' ] enumSetAttribute = name: 'sample-set-enum-attribute' value: 'enum-set-5-key' expectedUpdateAction = action: 'addPlainEnumValue' attributeName: 'sample-set-enum-attribute' value: key: 'enum-set-5-key' label: 'enum-set-5-key' expect(@import._generateUpdateAction(enumSetAttributeMultiValue, sampleProductType.attributes[3])).toEqual expectedUpdateActionMultiValue expect(@import._generateUpdateAction(enumSetAttribute, sampleProductType.attributes[3])).toEqual expectedUpdateAction it ' should generate correct list of update actions', -> enumAttributes = [ name: 'sample-lenum-attribute' value: 'lenum-key-2' , name: 'sample-enum-attribute' value: 'enum-1-key' , name: 'sample-set-enum-attribute' value: 'enum-set-2-key' , name: 'sample-lenum-attribute' value: 'lenum-3-key' , name: 'sample-enum-attribute' value: 'enum-3-key' , name: 'sample-set-enum-attribute' value: 'enum-set-5-key' ] expectedUpdateActions = [ action: 'addLocalizedEnumValue' attributeName: 'sample-lenum-attribute' value: key: 'lenum-3-key' label: en: 'lenum-3-key' de: 'lenum-3-key' fr: 'lenum-3-key' it: 'lenum-3-key' es: 'lenum-3-key' , action: 'addPlainEnumValue' attributeName: 'sample-enum-attribute' value: key: 'enum-3-key' label: 'enum-3-key' , action: 'addPlainEnumValue' attributeName: 'sample-set-enum-attribute' value: key: 'enum-set-5-key' label: 'enum-set-5-key' ] updateActions = @import._validateEnums(enumAttributes, sampleProductType) expect(updateActions).toEqual expectedUpdateActions it ' should detect already generated enums', -> @import._cache.generatedEnums['sample-lenum-attribute-lenum-key-2'] = 'lenum-key-2' @import._cache.generatedEnums['sample-set-enum-attribute-enum-set-2-key'] = 'enum-set-2-key' @import._cache.generatedEnums['sample-lenum-attribute-lenum-3-key'] = 'lenum-3-key' sampleEnumAttributeTrue = name: 'sample-lenum-attribute' value: 'lenum-3-key' sampleEnumAttributeFalse = name: 'sample-lenum-attribute' value: 'lenum-4-key' expect(@import._isEnumGenerated(sampleEnumAttributeTrue)).toBeDefined() expect(@import._isEnumGenerated(sampleEnumAttributeFalse)).toBeUndefined()
152988
debug = require('debug')('spec:enum-validator') _ = require 'underscore' _.mixin require 'underscore-mixins' {EnumValidator} = require '../lib' Promise = require 'bluebird' slugify = require 'underscore.string/slugify' {ExtendedLogger} = require 'sphere-node-utils' package_json = require '../package.json' sampleVariant = sku: 'sample_sku' attributes: [ name: 'sample-localized-text-attribute' value: en: 'sample localized text value' , name: 'sample-lenum-attribute' value: 'lenum-key-2' , name: 'sample-enum-attribute' value: 'enum-1-key' , name: 'sample-set-enum-attribute' value: 'enum-set-2-key' ] sampleProductType = id: 'sample_product_type_id' version: 1 name: 'sample product type name' attributes: [ name: 'sample-localized-text-attribute' label: en: 'Sample Localized Text Attribute' isRequired: true type: name: 'text' , name: 'sample-lenum-attribute' label: en: 'Sample Lenum Attribute' type: name: 'lenum' values: [ key: 'lenum-key-1' label: en: 'lenum-1-label-en' de: 'lenum-1-label-de' , key: 'lenum-key-2' label: en: 'lenum-2-label-en' de: 'lenum-2-label-de' ] , name: 'sample-enum-attribute' label: en: 'Sample Enum Attribute' type: name: 'enum' values: [ key: 'enum-1-key' label: 'enum-1-label' , key: 'enum-2-key' label: 'enum-2-label' ] , name: 'sample-set-enum-attribute' label: en: 'Sample Set Enum Attribute' type: name: 'set' elementType: name: 'enum' values: [ key: 'enum-set-1-key' label: 'enum-set-1-label' , key: 'enum-set<KEY>-2<KEY>-key' label: 'enum-set-2-label' ] , name: 'sample-set-lenum-attribute' label: en: 'Sample Set Lenum Attribute' type: name: 'set' elementType: name: 'lenum' values: [ key: 'lenum-set-1-key' label: en: 'lenum-set-1-label-en' de: 'lenum-set-1-label-de' , key: '<KEY>' label: en: 'lenum-set-2-label-en' de: 'lenum-set-2-label-de' ] ] describe 'Enum Validator unit tests', -> beforeEach -> @logger = new ExtendedLogger additionalFields: project_key: 'enum<KEY>' logConfig: name: "#{package_json.name}-#{package_json.version}" streams: [ { level: 'info', stream: process.stdout } ] @import = new EnumValidator @logger, null it ' should initialize', -> expect(@import).toBeDefined() it ' should filter enum and lenum attributes', -> enums = _.filter(sampleProductType.attributes, @import._enumLenumFilterPredicate) expect(_.size enums).toBe 2 it ' should filter set of enum attributes', -> enums = _.filter(sampleProductType.attributes, @import._enumSetFilterPredicate) expect(_.size enums).toBe 1 it ' should filter set of lenum attributes', -> enums = _.filter(sampleProductType.attributes, @import._lenumSetFilterPredicate) expect(_.size enums).toBe 1 it ' should extract enum attributes from product type', -> enums = @import._extractEnumAttributesFromProductType(sampleProductType) expect(_.size enums).toBe 4 it ' should fetch enum attributes from sample product type', -> enums = @import._fetchEnumAttributesOfProductType(sampleProductType) expect(_.size enums).toBe 4 it ' should fetch enum attribute names of sample product type', -> expectedNames = ['sample-lenum-attribute', 'sample-enum-attribute', 'sample-set-enum-attribute', 'sample-set-lenum-attribute'] enumNames = @import._fetchEnumAttributeNamesOfProductType(sampleProductType) expect(enumNames).toEqual expectedNames it ' should fetch enum attribute names of sample product type from cache', -> spyOn(@import, '_fetchEnumAttributesOfProductType').andCallThrough() @import._fetchEnumAttributeNamesOfProductType(sampleProductType) enumNames = @import._fetchEnumAttributeNamesOfProductType(sampleProductType) expect(_.size enumNames).toBe 4 expect(@import._fetchEnumAttributesOfProductType.calls.length).toEqual 1 expect(@import._cache.productTypeEnumMap["#{sampleProductType.id}_names"]).toBeDefined() it ' should detect enum attribute', -> sampleEnumAttribute = name: 'sample-enum-attribute' sampleAttribute = name: 'sample-text-attribute' enumAttributeNames = ['sample-lenum-attribute', 'sample-enum-attribute', 'sample-set-enum-attribute', 'sample-set-lenum-attribute'] expect(@import._isEnumVariantAttribute(sampleEnumAttribute, enumAttributeNames)).toBeTruthy() expect(@import._isEnumVariantAttribute(sampleAttribute, enumAttributeNames)).toBeFalsy() it ' should fetch enum attributes from sample variant', -> enums = @import._fetchEnumAttributesFromVariant(sampleVariant,sampleProductType) expect(_.size enums).toBe 3 it ' should fetch all enum attributes from all product variants', -> sampleProduct = name: 'sample Product' productType: id: 'sample_product_type_id' masterVariant: _.deepClone sampleVariant variants: [ _.deepClone sampleVariant , _.deepClone sampleVariant ] enums = @import._fetchEnumAttributesFromProduct(sampleProduct, sampleProductType) expect(_.size enums).toBe 9 it ' should detect enum key correctly', -> enumAttributeTrue = name: 'sample-enum-attribute' value: 'enum-2-key' enumAttributeFalse = name: 'sample-enum-attribute' value: 'enum-3-key' lenumAttributeTrue = name: 'sample-lenum-attribute' value: 'lenum-key-2' lenumAttributeFalse = name: 'sample-lenum-attribute' value: 'lenum-key-3' lenumSetAttributeTrue = name: 'sample-set-lenum-attribute' value: 'lenum-set-1-key' lenumSetAttributeFalse = name: 'sample-set-lenum-attribute' value: 'lenum-set-5-key' enumSetAttributeTrue = name: 'sample-set-enum-attribute' value: 'enum-set-1-key' enumSetAttributeFalse = name: 'sample-set-enum-attribute' value: 'enum-set-5-key' expect(@import._isEnumKeyPresent(enumAttributeTrue, sampleProductType.attributes[2])).toBeDefined() expect(@import._isEnumKeyPresent(enumAttributeFalse, sampleProductType.attributes[2])).toBeUndefined() expect(@import._isEnumKeyPresent(lenumAttributeTrue, sampleProductType.attributes[1])).toBeDefined() expect(@import._isEnumKeyPresent(lenumAttributeFalse, sampleProductType.attributes[1])).toBeUndefined() expect(@import._isEnumKeyPresent(lenumSetAttributeTrue, sampleProductType.attributes[4])).toBeDefined() expect(@import._isEnumKeyPresent(lenumSetAttributeFalse, sampleProductType.attributes[4])).toBeUndefined() expect(@import._isEnumKeyPresent(enumSetAttributeTrue, sampleProductType.attributes[3])).toBeDefined() expect(@import._isEnumKeyPresent(enumSetAttributeFalse, sampleProductType.attributes[3])).toBeUndefined() it ' should generate correct enum update action', -> enumAttribute = name: 'sample-enum-attribute' value: 'enum-3-key' expectedUpdateAction = action: 'addPlainEnumValue' attributeName: 'sample-enum-attribute' value: key: 'enum-3-key' label: 'enum-3-key' expect(@import._generateUpdateAction(enumAttribute, sampleProductType.attributes[2])).toEqual expectedUpdateAction it ' should generate correct lenum update action', -> lenumAttribute = name: 'sample-lenum-attribute' value: 'lenum-3-key' expectedUpdateAction = action: 'addLocalizedEnumValue' attributeName: 'sample-lenum-attribute' value: key: 'lenum-3-key' label: en: 'lenum-3-key' de: 'lenum-3-key' fr: 'lenum-3-key' it: 'lenum-3-key' es: 'lenum-3-key' expect(@import._generateUpdateAction(lenumAttribute, sampleProductType.attributes[1])).toEqual expectedUpdateAction it ' should generate correct enum set update action', -> enumSetAttributeMultiValue = name: 'sample-set-enum-attribute' value: [ 'enum-set-5-key' , 'enum-set-6-key' ] expectedUpdateActionMultiValue = [ action: 'addPlainEnumValue' attributeName: 'sample-set-enum-attribute' value: key: 'enum-set-5-key' label: 'enum-set-5-key' , action: 'addPlainEnumValue' attributeName: 'sample-set-enum-attribute' value: key: 'enum-set-6-key' label: 'enum-set-6-key' ] enumSetAttribute = name: 'sample-set-enum-attribute' value: 'enum-set-5-key' expectedUpdateAction = action: 'addPlainEnumValue' attributeName: 'sample-set-enum-attribute' value: key: 'enum-set-5-key' label: 'enum-set-5-key' expect(@import._generateUpdateAction(enumSetAttributeMultiValue, sampleProductType.attributes[3])).toEqual expectedUpdateActionMultiValue expect(@import._generateUpdateAction(enumSetAttribute, sampleProductType.attributes[3])).toEqual expectedUpdateAction it ' should generate correct list of update actions', -> enumAttributes = [ name: 'sample-lenum-attribute' value: 'lenum-key-2' , name: 'sample-enum-attribute' value: 'enum-1-key' , name: 'sample-set-enum-attribute' value: 'enum-set-2-key' , name: 'sample-lenum-attribute' value: 'lenum-3-key' , name: 'sample-enum-attribute' value: 'enum-3-key' , name: 'sample-set-enum-attribute' value: 'enum-set-5-key' ] expectedUpdateActions = [ action: 'addLocalizedEnumValue' attributeName: 'sample-lenum-attribute' value: key: 'len<KEY>key' label: en: 'lenum-3-key' de: 'lenum-3-key' fr: 'lenum-3-key' it: 'lenum-3-key' es: 'lenum-3-key' , action: 'addPlainEnumValue' attributeName: 'sample-enum-attribute' value: key: 'enum-3-key' label: 'enum-3-key' , action: 'addPlainEnumValue' attributeName: 'sample-set-enum-attribute' value: key: 'enum-set-5-key' label: 'enum-set-5-key' ] updateActions = @import._validateEnums(enumAttributes, sampleProductType) expect(updateActions).toEqual expectedUpdateActions it ' should detect already generated enums', -> @import._cache.generatedEnums['sample-lenum-attribute-lenum-key-2'] = 'lenum-key-2' @import._cache.generatedEnums['sample-set-enum-attribute-enum-set-2-key'] = 'enum-set-2-key' @import._cache.generatedEnums['sample-lenum-attribute-lenum-3-key'] = 'lenum-3-key' sampleEnumAttributeTrue = name: 'sample-lenum-attribute' value: 'lenum-3-key' sampleEnumAttributeFalse = name: 'sample-lenum-attribute' value: 'lenum-4-key' expect(@import._isEnumGenerated(sampleEnumAttributeTrue)).toBeDefined() expect(@import._isEnumGenerated(sampleEnumAttributeFalse)).toBeUndefined()
true
debug = require('debug')('spec:enum-validator') _ = require 'underscore' _.mixin require 'underscore-mixins' {EnumValidator} = require '../lib' Promise = require 'bluebird' slugify = require 'underscore.string/slugify' {ExtendedLogger} = require 'sphere-node-utils' package_json = require '../package.json' sampleVariant = sku: 'sample_sku' attributes: [ name: 'sample-localized-text-attribute' value: en: 'sample localized text value' , name: 'sample-lenum-attribute' value: 'lenum-key-2' , name: 'sample-enum-attribute' value: 'enum-1-key' , name: 'sample-set-enum-attribute' value: 'enum-set-2-key' ] sampleProductType = id: 'sample_product_type_id' version: 1 name: 'sample product type name' attributes: [ name: 'sample-localized-text-attribute' label: en: 'Sample Localized Text Attribute' isRequired: true type: name: 'text' , name: 'sample-lenum-attribute' label: en: 'Sample Lenum Attribute' type: name: 'lenum' values: [ key: 'lenum-key-1' label: en: 'lenum-1-label-en' de: 'lenum-1-label-de' , key: 'lenum-key-2' label: en: 'lenum-2-label-en' de: 'lenum-2-label-de' ] , name: 'sample-enum-attribute' label: en: 'Sample Enum Attribute' type: name: 'enum' values: [ key: 'enum-1-key' label: 'enum-1-label' , key: 'enum-2-key' label: 'enum-2-label' ] , name: 'sample-set-enum-attribute' label: en: 'Sample Set Enum Attribute' type: name: 'set' elementType: name: 'enum' values: [ key: 'enum-set-1-key' label: 'enum-set-1-label' , key: 'enum-setPI:KEY:<KEY>END_PI-2PI:KEY:<KEY>END_PI-key' label: 'enum-set-2-label' ] , name: 'sample-set-lenum-attribute' label: en: 'Sample Set Lenum Attribute' type: name: 'set' elementType: name: 'lenum' values: [ key: 'lenum-set-1-key' label: en: 'lenum-set-1-label-en' de: 'lenum-set-1-label-de' , key: 'PI:KEY:<KEY>END_PI' label: en: 'lenum-set-2-label-en' de: 'lenum-set-2-label-de' ] ] describe 'Enum Validator unit tests', -> beforeEach -> @logger = new ExtendedLogger additionalFields: project_key: 'enumPI:KEY:<KEY>END_PI' logConfig: name: "#{package_json.name}-#{package_json.version}" streams: [ { level: 'info', stream: process.stdout } ] @import = new EnumValidator @logger, null it ' should initialize', -> expect(@import).toBeDefined() it ' should filter enum and lenum attributes', -> enums = _.filter(sampleProductType.attributes, @import._enumLenumFilterPredicate) expect(_.size enums).toBe 2 it ' should filter set of enum attributes', -> enums = _.filter(sampleProductType.attributes, @import._enumSetFilterPredicate) expect(_.size enums).toBe 1 it ' should filter set of lenum attributes', -> enums = _.filter(sampleProductType.attributes, @import._lenumSetFilterPredicate) expect(_.size enums).toBe 1 it ' should extract enum attributes from product type', -> enums = @import._extractEnumAttributesFromProductType(sampleProductType) expect(_.size enums).toBe 4 it ' should fetch enum attributes from sample product type', -> enums = @import._fetchEnumAttributesOfProductType(sampleProductType) expect(_.size enums).toBe 4 it ' should fetch enum attribute names of sample product type', -> expectedNames = ['sample-lenum-attribute', 'sample-enum-attribute', 'sample-set-enum-attribute', 'sample-set-lenum-attribute'] enumNames = @import._fetchEnumAttributeNamesOfProductType(sampleProductType) expect(enumNames).toEqual expectedNames it ' should fetch enum attribute names of sample product type from cache', -> spyOn(@import, '_fetchEnumAttributesOfProductType').andCallThrough() @import._fetchEnumAttributeNamesOfProductType(sampleProductType) enumNames = @import._fetchEnumAttributeNamesOfProductType(sampleProductType) expect(_.size enumNames).toBe 4 expect(@import._fetchEnumAttributesOfProductType.calls.length).toEqual 1 expect(@import._cache.productTypeEnumMap["#{sampleProductType.id}_names"]).toBeDefined() it ' should detect enum attribute', -> sampleEnumAttribute = name: 'sample-enum-attribute' sampleAttribute = name: 'sample-text-attribute' enumAttributeNames = ['sample-lenum-attribute', 'sample-enum-attribute', 'sample-set-enum-attribute', 'sample-set-lenum-attribute'] expect(@import._isEnumVariantAttribute(sampleEnumAttribute, enumAttributeNames)).toBeTruthy() expect(@import._isEnumVariantAttribute(sampleAttribute, enumAttributeNames)).toBeFalsy() it ' should fetch enum attributes from sample variant', -> enums = @import._fetchEnumAttributesFromVariant(sampleVariant,sampleProductType) expect(_.size enums).toBe 3 it ' should fetch all enum attributes from all product variants', -> sampleProduct = name: 'sample Product' productType: id: 'sample_product_type_id' masterVariant: _.deepClone sampleVariant variants: [ _.deepClone sampleVariant , _.deepClone sampleVariant ] enums = @import._fetchEnumAttributesFromProduct(sampleProduct, sampleProductType) expect(_.size enums).toBe 9 it ' should detect enum key correctly', -> enumAttributeTrue = name: 'sample-enum-attribute' value: 'enum-2-key' enumAttributeFalse = name: 'sample-enum-attribute' value: 'enum-3-key' lenumAttributeTrue = name: 'sample-lenum-attribute' value: 'lenum-key-2' lenumAttributeFalse = name: 'sample-lenum-attribute' value: 'lenum-key-3' lenumSetAttributeTrue = name: 'sample-set-lenum-attribute' value: 'lenum-set-1-key' lenumSetAttributeFalse = name: 'sample-set-lenum-attribute' value: 'lenum-set-5-key' enumSetAttributeTrue = name: 'sample-set-enum-attribute' value: 'enum-set-1-key' enumSetAttributeFalse = name: 'sample-set-enum-attribute' value: 'enum-set-5-key' expect(@import._isEnumKeyPresent(enumAttributeTrue, sampleProductType.attributes[2])).toBeDefined() expect(@import._isEnumKeyPresent(enumAttributeFalse, sampleProductType.attributes[2])).toBeUndefined() expect(@import._isEnumKeyPresent(lenumAttributeTrue, sampleProductType.attributes[1])).toBeDefined() expect(@import._isEnumKeyPresent(lenumAttributeFalse, sampleProductType.attributes[1])).toBeUndefined() expect(@import._isEnumKeyPresent(lenumSetAttributeTrue, sampleProductType.attributes[4])).toBeDefined() expect(@import._isEnumKeyPresent(lenumSetAttributeFalse, sampleProductType.attributes[4])).toBeUndefined() expect(@import._isEnumKeyPresent(enumSetAttributeTrue, sampleProductType.attributes[3])).toBeDefined() expect(@import._isEnumKeyPresent(enumSetAttributeFalse, sampleProductType.attributes[3])).toBeUndefined() it ' should generate correct enum update action', -> enumAttribute = name: 'sample-enum-attribute' value: 'enum-3-key' expectedUpdateAction = action: 'addPlainEnumValue' attributeName: 'sample-enum-attribute' value: key: 'enum-3-key' label: 'enum-3-key' expect(@import._generateUpdateAction(enumAttribute, sampleProductType.attributes[2])).toEqual expectedUpdateAction it ' should generate correct lenum update action', -> lenumAttribute = name: 'sample-lenum-attribute' value: 'lenum-3-key' expectedUpdateAction = action: 'addLocalizedEnumValue' attributeName: 'sample-lenum-attribute' value: key: 'lenum-3-key' label: en: 'lenum-3-key' de: 'lenum-3-key' fr: 'lenum-3-key' it: 'lenum-3-key' es: 'lenum-3-key' expect(@import._generateUpdateAction(lenumAttribute, sampleProductType.attributes[1])).toEqual expectedUpdateAction it ' should generate correct enum set update action', -> enumSetAttributeMultiValue = name: 'sample-set-enum-attribute' value: [ 'enum-set-5-key' , 'enum-set-6-key' ] expectedUpdateActionMultiValue = [ action: 'addPlainEnumValue' attributeName: 'sample-set-enum-attribute' value: key: 'enum-set-5-key' label: 'enum-set-5-key' , action: 'addPlainEnumValue' attributeName: 'sample-set-enum-attribute' value: key: 'enum-set-6-key' label: 'enum-set-6-key' ] enumSetAttribute = name: 'sample-set-enum-attribute' value: 'enum-set-5-key' expectedUpdateAction = action: 'addPlainEnumValue' attributeName: 'sample-set-enum-attribute' value: key: 'enum-set-5-key' label: 'enum-set-5-key' expect(@import._generateUpdateAction(enumSetAttributeMultiValue, sampleProductType.attributes[3])).toEqual expectedUpdateActionMultiValue expect(@import._generateUpdateAction(enumSetAttribute, sampleProductType.attributes[3])).toEqual expectedUpdateAction it ' should generate correct list of update actions', -> enumAttributes = [ name: 'sample-lenum-attribute' value: 'lenum-key-2' , name: 'sample-enum-attribute' value: 'enum-1-key' , name: 'sample-set-enum-attribute' value: 'enum-set-2-key' , name: 'sample-lenum-attribute' value: 'lenum-3-key' , name: 'sample-enum-attribute' value: 'enum-3-key' , name: 'sample-set-enum-attribute' value: 'enum-set-5-key' ] expectedUpdateActions = [ action: 'addLocalizedEnumValue' attributeName: 'sample-lenum-attribute' value: key: 'lenPI:KEY:<KEY>END_PIkey' label: en: 'lenum-3-key' de: 'lenum-3-key' fr: 'lenum-3-key' it: 'lenum-3-key' es: 'lenum-3-key' , action: 'addPlainEnumValue' attributeName: 'sample-enum-attribute' value: key: 'enum-3-key' label: 'enum-3-key' , action: 'addPlainEnumValue' attributeName: 'sample-set-enum-attribute' value: key: 'enum-set-5-key' label: 'enum-set-5-key' ] updateActions = @import._validateEnums(enumAttributes, sampleProductType) expect(updateActions).toEqual expectedUpdateActions it ' should detect already generated enums', -> @import._cache.generatedEnums['sample-lenum-attribute-lenum-key-2'] = 'lenum-key-2' @import._cache.generatedEnums['sample-set-enum-attribute-enum-set-2-key'] = 'enum-set-2-key' @import._cache.generatedEnums['sample-lenum-attribute-lenum-3-key'] = 'lenum-3-key' sampleEnumAttributeTrue = name: 'sample-lenum-attribute' value: 'lenum-3-key' sampleEnumAttributeFalse = name: 'sample-lenum-attribute' value: 'lenum-4-key' expect(@import._isEnumGenerated(sampleEnumAttributeTrue)).toBeDefined() expect(@import._isEnumGenerated(sampleEnumAttributeFalse)).toBeUndefined()
[ { "context": "ncodeData(\"shell:am start\n --eia 'key1' '2,3'\n --ela 'key2' '20,30'\n --ei 'k", "end": 10556, "score": 0.8186745643615723, "start": 10553, "tag": "KEY", "value": "2,3" }, { "context": " --eia 'key1' '2,3'\n --ela 'key2' '20,3...
test/adb/command/host-transport/startactivity.coffee
DeedleFake/adbkit
642
Stream = require 'stream' Sinon = require 'sinon' Chai = require 'chai' Chai.use require 'sinon-chai' {expect} = Chai MockConnection = require '../../../mock/connection' Protocol = require '../../../../src/adb/protocol' StartActivityCommand = require \ '../../../../src/adb/command/host-transport/startactivity' describe 'StartActivityCommand', -> it "should succeed when 'Success' returned", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' cmd.execute options .then -> done() it "should fail when 'Error' returned", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Error: foo\n' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' cmd.execute options .catch (err) -> expect(err).to.be.be.an.instanceOf Error done() it "should send 'am start -n <pkg>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' cmd.execute options .then -> done() it "should send 'am start -W -D --user 0 -n <pkg>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -n 'com.dummy.component/.Main' -D -W --user 0").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' user: 0 wait: true debug: true cmd.execute options .then -> done() it "should send 'am start -a <action>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -a 'foo.ACTION_BAR'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = action: "foo.ACTION_BAR" cmd.execute options .then -> done() it "should send 'am start -d <data>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -d 'foo://bar'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = data: "foo://bar" cmd.execute options .then -> done() it "should send 'am start -t <mimeType>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -t 'text/plain'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = mimeType: "text/plain" cmd.execute options .then -> done() it "should send 'am start -c <category>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -c 'android.intent.category.LAUNCHER'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = category: "android.intent.category.LAUNCHER" cmd.execute options .then -> done() it "should send 'am start -c <category1> -c <category2>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -c 'android.intent.category.LAUNCHER' -c 'android.intent.category.DEFAULT'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = category: [ "android.intent.category.LAUNCHER" "android.intent.category.DEFAULT" ] cmd.execute options .then -> done() it "should send 'am start -f <flags>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -f #{0x10210000}").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = flags: 0x10210000 cmd.execute options .then -> done() it "should send 'am start -n <pgk> --es <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --es 'key1' 'value1' --es 'key2' 'value2' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = component: "com.dummy.component/.Main" extras: [ key: 'key1' value: 'value1' , key: 'key2' value: 'value2' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --ei <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --ei 'key1' 1 --ei 'key2' 2 -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 1 type: 'int' , key: 'key2' value: 2 type: 'int' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --ez <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --ez 'key1' 'true' --ez 'key2' 'false' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: "com.dummy.component/.Main" extras: [ key: 'key1' value: true type: 'bool' , key: 'key2' value: false type: 'bool' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --el <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --el 'key1' 1 --el 'key2' '2' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 1 type: 'long' , key: 'key2' value: '2' type: 'long' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --eu <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --eu 'key1' 'http://example.org' --eu 'key2' 'http://example.org' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 'http://example.org' type: 'uri' , key: 'key2' value: 'http://example.org' type: 'uri' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --es <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --es 'key1' 'a' --es 'key2' 'b' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 'a' type: 'string' , key: 'key2' value: 'b' type: 'string' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --eia <extras with arr>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --eia 'key1' '2,3' --ela 'key2' '20,30' --ei 'key3' 5 -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: [ 2 3 ] type: 'int' , key: 'key2' value: [ 20 30 ] type: 'long' , key: 'key3' value: 5 type: 'int' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --esn <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --esn 'key1' --esn 'key2' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' type: 'null' , key: 'key2' type: 'null' ] cmd.execute options .then -> done() it "should throw when calling with an unknown extra type", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 'value1' type: 'nonexisting' ] expect(-> cmd.execute(options, ->)).to.throw done() it "should accept mixed types of extras", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --ez 'key1' 'true' --es 'key2' 'somestr' --es 'key3' 'defaultType' --ei 'key4' 3 --el 'key5' '4' --eu 'key6' 'http://example.org' --esn 'key7' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: true type: 'bool' , key: 'key2' value: 'somestr' type: 'string' , key: 'key3' value: 'defaultType' , key: 'key4' value: 3 type: 'int' , key: 'key5' value: '4' type: 'long' , key: 'key6' value: 'http://example.org' type: 'uri' , key: 'key7' type: 'null' ] cmd.execute options .then -> done() it "should map short extras to long extras", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn short = cmd._formatExtras someString: 'bar' someInt: 5 someUrl: type: 'uri' value: 'http://example.org' someArray: type: 'int' value: [1, 2] someNull: null long = cmd._formatExtras [ key: 'someString' value: 'bar' type: 'string' , key: 'someInt' value: 5 type: 'int' , key: 'someUrl' value: 'http://example.org' type: 'uri' , key: 'someArray' value: [1, 2] type: 'int' , key: 'someNull' type: 'null' ] expect(short).to.eql long done()
66913
Stream = require 'stream' Sinon = require 'sinon' Chai = require 'chai' Chai.use require 'sinon-chai' {expect} = Chai MockConnection = require '../../../mock/connection' Protocol = require '../../../../src/adb/protocol' StartActivityCommand = require \ '../../../../src/adb/command/host-transport/startactivity' describe 'StartActivityCommand', -> it "should succeed when 'Success' returned", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' cmd.execute options .then -> done() it "should fail when 'Error' returned", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Error: foo\n' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' cmd.execute options .catch (err) -> expect(err).to.be.be.an.instanceOf Error done() it "should send 'am start -n <pkg>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' cmd.execute options .then -> done() it "should send 'am start -W -D --user 0 -n <pkg>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -n 'com.dummy.component/.Main' -D -W --user 0").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' user: 0 wait: true debug: true cmd.execute options .then -> done() it "should send 'am start -a <action>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -a 'foo.ACTION_BAR'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = action: "foo.ACTION_BAR" cmd.execute options .then -> done() it "should send 'am start -d <data>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -d 'foo://bar'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = data: "foo://bar" cmd.execute options .then -> done() it "should send 'am start -t <mimeType>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -t 'text/plain'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = mimeType: "text/plain" cmd.execute options .then -> done() it "should send 'am start -c <category>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -c 'android.intent.category.LAUNCHER'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = category: "android.intent.category.LAUNCHER" cmd.execute options .then -> done() it "should send 'am start -c <category1> -c <category2>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -c 'android.intent.category.LAUNCHER' -c 'android.intent.category.DEFAULT'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = category: [ "android.intent.category.LAUNCHER" "android.intent.category.DEFAULT" ] cmd.execute options .then -> done() it "should send 'am start -f <flags>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -f #{0x10210000}").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = flags: 0x10210000 cmd.execute options .then -> done() it "should send 'am start -n <pgk> --es <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --es 'key1' 'value1' --es 'key2' 'value2' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = component: "com.dummy.component/.Main" extras: [ key: 'key1' value: 'value1' , key: 'key2' value: 'value2' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --ei <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --ei 'key1' 1 --ei 'key2' 2 -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 1 type: 'int' , key: 'key2' value: 2 type: 'int' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --ez <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --ez 'key1' 'true' --ez 'key2' 'false' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: "com.dummy.component/.Main" extras: [ key: 'key1' value: true type: 'bool' , key: 'key2' value: false type: 'bool' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --el <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --el 'key1' 1 --el 'key2' '2' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 1 type: 'long' , key: 'key2' value: '2' type: 'long' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --eu <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --eu 'key1' 'http://example.org' --eu 'key2' 'http://example.org' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 'http://example.org' type: 'uri' , key: 'key2' value: 'http://example.org' type: 'uri' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --es <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --es 'key1' 'a' --es 'key2' 'b' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 'a' type: 'string' , key: 'key2' value: 'b' type: 'string' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --eia <extras with arr>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --eia 'key1' '<KEY>' --ela 'key2' '<KEY>' --ei 'key3' 5 -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: [ 2 3 ] type: 'int' , key: 'key2' value: [ 20 30 ] type: 'long' , key: 'key3' value: 5 type: 'int' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --esn <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --esn 'key1' --esn 'key2' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' type: 'null' , key: 'key2' type: 'null' ] cmd.execute options .then -> done() it "should throw when calling with an unknown extra type", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 'value1' type: 'nonexisting' ] expect(-> cmd.execute(options, ->)).to.throw done() it "should accept mixed types of extras", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --ez 'key1' 'true' --es 'key2' 'somestr' --es 'key3' 'defaultType' --ei 'key4' 3 --el 'key5' '4' --eu 'key6' 'http://example.org' --esn 'key7' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: true type: 'bool' , key: 'key2' value: 'somestr' type: 'string' , key: 'key3' value: 'defaultType' , key: 'key4' value: 3 type: 'int' , key: 'key5' value: '4' type: 'long' , key: 'key6' value: 'http://example.org' type: 'uri' , key: 'key7' type: 'null' ] cmd.execute options .then -> done() it "should map short extras to long extras", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn short = cmd._formatExtras someString: 'bar' someInt: 5 someUrl: type: 'uri' value: 'http://example.org' someArray: type: 'int' value: [1, 2] someNull: null long = cmd._formatExtras [ key: '<KEY>' value: 'bar' type: 'string' , key: '<KEY>' value: 5 type: 'int' , key: '<KEY>' value: 'http://example.org' type: 'uri' , key: '<KEY>' value: [1, 2] type: 'int' , key: '<KEY>' type: 'null' ] expect(short).to.eql long done()
true
Stream = require 'stream' Sinon = require 'sinon' Chai = require 'chai' Chai.use require 'sinon-chai' {expect} = Chai MockConnection = require '../../../mock/connection' Protocol = require '../../../../src/adb/protocol' StartActivityCommand = require \ '../../../../src/adb/command/host-transport/startactivity' describe 'StartActivityCommand', -> it "should succeed when 'Success' returned", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' cmd.execute options .then -> done() it "should fail when 'Error' returned", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Error: foo\n' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' cmd.execute options .catch (err) -> expect(err).to.be.be.an.instanceOf Error done() it "should send 'am start -n <pkg>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' cmd.execute options .then -> done() it "should send 'am start -W -D --user 0 -n <pkg>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -n 'com.dummy.component/.Main' -D -W --user 0").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' user: 0 wait: true debug: true cmd.execute options .then -> done() it "should send 'am start -a <action>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -a 'foo.ACTION_BAR'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = action: "foo.ACTION_BAR" cmd.execute options .then -> done() it "should send 'am start -d <data>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -d 'foo://bar'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = data: "foo://bar" cmd.execute options .then -> done() it "should send 'am start -t <mimeType>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -t 'text/plain'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = mimeType: "text/plain" cmd.execute options .then -> done() it "should send 'am start -c <category>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -c 'android.intent.category.LAUNCHER'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = category: "android.intent.category.LAUNCHER" cmd.execute options .then -> done() it "should send 'am start -c <category1> -c <category2>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -c 'android.intent.category.LAUNCHER' -c 'android.intent.category.DEFAULT'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = category: [ "android.intent.category.LAUNCHER" "android.intent.category.DEFAULT" ] cmd.execute options .then -> done() it "should send 'am start -f <flags>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start -f #{0x10210000}").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = flags: 0x10210000 cmd.execute options .then -> done() it "should send 'am start -n <pgk> --es <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --es 'key1' 'value1' --es 'key2' 'value2' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = component: "com.dummy.component/.Main" extras: [ key: 'key1' value: 'value1' , key: 'key2' value: 'value2' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --ei <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --ei 'key1' 1 --ei 'key2' 2 -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success\n' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 1 type: 'int' , key: 'key2' value: 2 type: 'int' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --ez <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --ez 'key1' 'true' --ez 'key2' 'false' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: "com.dummy.component/.Main" extras: [ key: 'key1' value: true type: 'bool' , key: 'key2' value: false type: 'bool' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --el <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --el 'key1' 1 --el 'key2' '2' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 1 type: 'long' , key: 'key2' value: '2' type: 'long' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --eu <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --eu 'key1' 'http://example.org' --eu 'key2' 'http://example.org' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 'http://example.org' type: 'uri' , key: 'key2' value: 'http://example.org' type: 'uri' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --es <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --es 'key1' 'a' --es 'key2' 'b' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 'a' type: 'string' , key: 'key2' value: 'b' type: 'string' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --eia <extras with arr>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --eia 'key1' 'PI:KEY:<KEY>END_PI' --ela 'key2' 'PI:KEY:<KEY>END_PI' --ei 'key3' 5 -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: [ 2 3 ] type: 'int' , key: 'key2' value: [ 20 30 ] type: 'long' , key: 'key3' value: 5 type: 'int' ] cmd.execute options .then -> done() it "should send 'am start -n <pgk> --esn <extras>'", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --esn 'key1' --esn 'key2' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' type: 'null' , key: 'key2' type: 'null' ] cmd.execute options .then -> done() it "should throw when calling with an unknown extra type", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: 'value1' type: 'nonexisting' ] expect(-> cmd.execute(options, ->)).to.throw done() it "should accept mixed types of extras", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn conn.socket.on 'write', (chunk) -> expect(chunk.toString()).to.equal \ Protocol.encodeData("shell:am start --ez 'key1' 'true' --es 'key2' 'somestr' --es 'key3' 'defaultType' --ei 'key4' 3 --el 'key5' '4' --eu 'key6' 'http://example.org' --esn 'key7' -n 'com.dummy.component/.Main'").toString() setImmediate -> conn.socket.causeRead Protocol.OKAY conn.socket.causeRead 'Success' conn.socket.causeEnd() options = component: 'com.dummy.component/.Main' extras: [ key: 'key1' value: true type: 'bool' , key: 'key2' value: 'somestr' type: 'string' , key: 'key3' value: 'defaultType' , key: 'key4' value: 3 type: 'int' , key: 'key5' value: '4' type: 'long' , key: 'key6' value: 'http://example.org' type: 'uri' , key: 'key7' type: 'null' ] cmd.execute options .then -> done() it "should map short extras to long extras", (done) -> conn = new MockConnection cmd = new StartActivityCommand conn short = cmd._formatExtras someString: 'bar' someInt: 5 someUrl: type: 'uri' value: 'http://example.org' someArray: type: 'int' value: [1, 2] someNull: null long = cmd._formatExtras [ key: 'PI:KEY:<KEY>END_PI' value: 'bar' type: 'string' , key: 'PI:KEY:<KEY>END_PI' value: 5 type: 'int' , key: 'PI:KEY:<KEY>END_PI' value: 'http://example.org' type: 'uri' , key: 'PI:KEY:<KEY>END_PI' value: [1, 2] type: 'int' , key: 'PI:KEY:<KEY>END_PI' type: 'null' ] expect(short).to.eql long done()
[ { "context": " it 'shows confirmation and a mailto link to schools@codecombat.com', ->\n if not @view.$('#request-sent-btn'", "end": 6032, "score": 0.9999243021011353, "start": 6010, "tag": "EMAIL", "value": "schools@codecombat.com" }, { "context": " locale\n # ...
test/app/views/courses/EnrollmentsView.spec.coffee
toivomattila/codecombat
1
EnrollmentsView = require 'views/courses/EnrollmentsView' Courses = require 'collections/Courses' Prepaids = require 'collections/Prepaids' Users = require 'collections/Users' Classrooms = require 'collections/Classrooms' factories = require 'test/app/factories' TeachersContactModal = require 'views/teachers/TeachersContactModal' describe 'EnrollmentsView', -> beforeEach -> me.set('anonymous', false) me.set('role', 'teacher') me.set('enrollmentRequestSent', false) @view = new EnrollmentsView() # Make three classrooms, sharing users from a pool of 10, 5 of which are enrolled prepaid = factories.makePrepaid() students = new Users(_.times(10, (i) -> factories.makeUser({}, { prepaid: if i%2 then prepaid else null })) ) userSlices = [ new Users(students.slice(0, 5)) new Users(students.slice(3, 8)) new Users(students.slice(7, 10)) ] classrooms = new Classrooms(factories.makeClassroom({}, {members: userSlice}) for userSlice in userSlices) @view.classrooms.fakeRequests[0].respondWith({ status: 200, responseText: classrooms.stringify() }) for request, i in @view.members.fakeRequests request.respondWith({status: 200, responseText: userSlices[i].stringify()}) # Make prepaids of various status prepaids = new Prepaids([ factories.makePrepaid({}, {redeemers: new Users(_.times(5, -> factories.makeUser()))}) factories.makePrepaid() factories.makePrepaid({ # pending startDate: moment().add(2, 'months').toISOString() endDate: moment().add(14, 'months').toISOString() }) factories.makePrepaid( # empty { maxRedeemers: 2 }, {redeemers: new Users(_.times(2, -> factories.makeUser()))} ) ]) @view.prepaids.fakeRequests[0].respondWith({ status: 200, responseText: prepaids.stringify() }) # Make a few courses, one free courses = new Courses([ factories.makeCourse({free: true}) factories.makeCourse({free: false}) factories.makeCourse({free: false}) factories.makeCourse({free: false}) ]) @view.courses.fakeRequests[0].respondWith({ status: 200, responseText: courses.stringify() }) jasmine.demoEl(@view.$el) window.view = @view describe 'For low priority leads', -> beforeEach -> leadPriorityRequest = jasmine.Ajax.requests.filter((r)-> r.url == '/db/user/-/lead-priority')[0] leadPriorityRequest.respondWith({status: 200, responseText: JSON.stringify({ priority: 'low' })}) describe 'shows the starter license upsell', -> it 'when only subscription prepaids exist', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ type: 'subscription' startDate: moment().subtract(3, 'weeks').toISOString() endDate: moment().add(2, 'weeks').toISOString() })) @view.prepaids.trigger('sync') @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(1) it 'when active starter licenses exist', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ type: 'starter_license' startDate: moment().subtract(3, 'weeks').toISOString() endDate: moment().add(2, 'weeks').toISOString() })) @view.prepaids.trigger('sync') @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(1) it 'when expired starter licenses exist', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ type: 'starter_license' startDate: moment().subtract(3, 'week').toISOString() endDate: moment().subtract(1, 'week').toISOString() })) @view.prepaids.trigger('sync') @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(1) it 'when no prepaids exist', -> @view.prepaids.set([]) @view.prepaids.trigger('sync') @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(1) describe 'does not show the starter license upsell', -> it 'when full licenses have existed', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ startDate: moment().subtract(2, 'month').toISOString() endDate: moment().subtract(1, 'month').toISOString() })) @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(0) it 'when full licenses currently exist', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ startDate: moment().subtract(2, 'month').toISOString() endDate: moment().add(1, 'month').toISOString() })) @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(0) describe 'For high priority leads', -> beforeEach -> leadPriorityRequest = jasmine.Ajax.requests.filter((r)-> r.url == '/db/user/-/lead-priority')[0] leadPriorityRequest.respondWith({status: 200, responseText: JSON.stringify({ priority: 'high' })}) @view.render() it "doesn't show the Starter License upsell", -> expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(0) describe 'For no priority leads', -> beforeEach -> leadPriorityRequest = jasmine.Ajax.requests.filter((r)-> r.url == '/db/user/-/lead-priority')[0] leadPriorityRequest.respondWith({status: 200, responseText: JSON.stringify({ priority: undefined })}) @view.render() it "doesn't show the Starter License upsell", -> expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(0) describe '"Get Licenses" area', -> describe 'when the teacher has made contact', -> beforeEach -> @view.enrollmentRequestSent = true @view.render() it 'shows confirmation and a mailto link to schools@codecombat.com', -> if not @view.$('#request-sent-btn').length fail('Request button not found.') if not @view.$('#enrollment-request-sent-blurb').length fail('License request sent blurb not found.') # TODO: Figure out why this fails in Travis. Seems like it's not loading en locale # if not @view.$('a[href="mailto:schools@codecombat.com"]').length # fail('Mailto: link not found.') describe 'when there are no prepaids to show', -> beforeEach (done) -> @view.prepaids.reset([]) @view.updatePrepaidGroups() _.defer(done) it 'fills the void with the rest of the page content', -> expect(@view.$('#actions-col').length).toBe(0)
173002
EnrollmentsView = require 'views/courses/EnrollmentsView' Courses = require 'collections/Courses' Prepaids = require 'collections/Prepaids' Users = require 'collections/Users' Classrooms = require 'collections/Classrooms' factories = require 'test/app/factories' TeachersContactModal = require 'views/teachers/TeachersContactModal' describe 'EnrollmentsView', -> beforeEach -> me.set('anonymous', false) me.set('role', 'teacher') me.set('enrollmentRequestSent', false) @view = new EnrollmentsView() # Make three classrooms, sharing users from a pool of 10, 5 of which are enrolled prepaid = factories.makePrepaid() students = new Users(_.times(10, (i) -> factories.makeUser({}, { prepaid: if i%2 then prepaid else null })) ) userSlices = [ new Users(students.slice(0, 5)) new Users(students.slice(3, 8)) new Users(students.slice(7, 10)) ] classrooms = new Classrooms(factories.makeClassroom({}, {members: userSlice}) for userSlice in userSlices) @view.classrooms.fakeRequests[0].respondWith({ status: 200, responseText: classrooms.stringify() }) for request, i in @view.members.fakeRequests request.respondWith({status: 200, responseText: userSlices[i].stringify()}) # Make prepaids of various status prepaids = new Prepaids([ factories.makePrepaid({}, {redeemers: new Users(_.times(5, -> factories.makeUser()))}) factories.makePrepaid() factories.makePrepaid({ # pending startDate: moment().add(2, 'months').toISOString() endDate: moment().add(14, 'months').toISOString() }) factories.makePrepaid( # empty { maxRedeemers: 2 }, {redeemers: new Users(_.times(2, -> factories.makeUser()))} ) ]) @view.prepaids.fakeRequests[0].respondWith({ status: 200, responseText: prepaids.stringify() }) # Make a few courses, one free courses = new Courses([ factories.makeCourse({free: true}) factories.makeCourse({free: false}) factories.makeCourse({free: false}) factories.makeCourse({free: false}) ]) @view.courses.fakeRequests[0].respondWith({ status: 200, responseText: courses.stringify() }) jasmine.demoEl(@view.$el) window.view = @view describe 'For low priority leads', -> beforeEach -> leadPriorityRequest = jasmine.Ajax.requests.filter((r)-> r.url == '/db/user/-/lead-priority')[0] leadPriorityRequest.respondWith({status: 200, responseText: JSON.stringify({ priority: 'low' })}) describe 'shows the starter license upsell', -> it 'when only subscription prepaids exist', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ type: 'subscription' startDate: moment().subtract(3, 'weeks').toISOString() endDate: moment().add(2, 'weeks').toISOString() })) @view.prepaids.trigger('sync') @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(1) it 'when active starter licenses exist', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ type: 'starter_license' startDate: moment().subtract(3, 'weeks').toISOString() endDate: moment().add(2, 'weeks').toISOString() })) @view.prepaids.trigger('sync') @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(1) it 'when expired starter licenses exist', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ type: 'starter_license' startDate: moment().subtract(3, 'week').toISOString() endDate: moment().subtract(1, 'week').toISOString() })) @view.prepaids.trigger('sync') @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(1) it 'when no prepaids exist', -> @view.prepaids.set([]) @view.prepaids.trigger('sync') @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(1) describe 'does not show the starter license upsell', -> it 'when full licenses have existed', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ startDate: moment().subtract(2, 'month').toISOString() endDate: moment().subtract(1, 'month').toISOString() })) @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(0) it 'when full licenses currently exist', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ startDate: moment().subtract(2, 'month').toISOString() endDate: moment().add(1, 'month').toISOString() })) @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(0) describe 'For high priority leads', -> beforeEach -> leadPriorityRequest = jasmine.Ajax.requests.filter((r)-> r.url == '/db/user/-/lead-priority')[0] leadPriorityRequest.respondWith({status: 200, responseText: JSON.stringify({ priority: 'high' })}) @view.render() it "doesn't show the Starter License upsell", -> expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(0) describe 'For no priority leads', -> beforeEach -> leadPriorityRequest = jasmine.Ajax.requests.filter((r)-> r.url == '/db/user/-/lead-priority')[0] leadPriorityRequest.respondWith({status: 200, responseText: JSON.stringify({ priority: undefined })}) @view.render() it "doesn't show the Starter License upsell", -> expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(0) describe '"Get Licenses" area', -> describe 'when the teacher has made contact', -> beforeEach -> @view.enrollmentRequestSent = true @view.render() it 'shows confirmation and a mailto link to <EMAIL>', -> if not @view.$('#request-sent-btn').length fail('Request button not found.') if not @view.$('#enrollment-request-sent-blurb').length fail('License request sent blurb not found.') # TODO: Figure out why this fails in Travis. Seems like it's not loading en locale # if not @view.$('a[href="mailto:<EMAIL>"]').length # fail('Mailto: link not found.') describe 'when there are no prepaids to show', -> beforeEach (done) -> @view.prepaids.reset([]) @view.updatePrepaidGroups() _.defer(done) it 'fills the void with the rest of the page content', -> expect(@view.$('#actions-col').length).toBe(0)
true
EnrollmentsView = require 'views/courses/EnrollmentsView' Courses = require 'collections/Courses' Prepaids = require 'collections/Prepaids' Users = require 'collections/Users' Classrooms = require 'collections/Classrooms' factories = require 'test/app/factories' TeachersContactModal = require 'views/teachers/TeachersContactModal' describe 'EnrollmentsView', -> beforeEach -> me.set('anonymous', false) me.set('role', 'teacher') me.set('enrollmentRequestSent', false) @view = new EnrollmentsView() # Make three classrooms, sharing users from a pool of 10, 5 of which are enrolled prepaid = factories.makePrepaid() students = new Users(_.times(10, (i) -> factories.makeUser({}, { prepaid: if i%2 then prepaid else null })) ) userSlices = [ new Users(students.slice(0, 5)) new Users(students.slice(3, 8)) new Users(students.slice(7, 10)) ] classrooms = new Classrooms(factories.makeClassroom({}, {members: userSlice}) for userSlice in userSlices) @view.classrooms.fakeRequests[0].respondWith({ status: 200, responseText: classrooms.stringify() }) for request, i in @view.members.fakeRequests request.respondWith({status: 200, responseText: userSlices[i].stringify()}) # Make prepaids of various status prepaids = new Prepaids([ factories.makePrepaid({}, {redeemers: new Users(_.times(5, -> factories.makeUser()))}) factories.makePrepaid() factories.makePrepaid({ # pending startDate: moment().add(2, 'months').toISOString() endDate: moment().add(14, 'months').toISOString() }) factories.makePrepaid( # empty { maxRedeemers: 2 }, {redeemers: new Users(_.times(2, -> factories.makeUser()))} ) ]) @view.prepaids.fakeRequests[0].respondWith({ status: 200, responseText: prepaids.stringify() }) # Make a few courses, one free courses = new Courses([ factories.makeCourse({free: true}) factories.makeCourse({free: false}) factories.makeCourse({free: false}) factories.makeCourse({free: false}) ]) @view.courses.fakeRequests[0].respondWith({ status: 200, responseText: courses.stringify() }) jasmine.demoEl(@view.$el) window.view = @view describe 'For low priority leads', -> beforeEach -> leadPriorityRequest = jasmine.Ajax.requests.filter((r)-> r.url == '/db/user/-/lead-priority')[0] leadPriorityRequest.respondWith({status: 200, responseText: JSON.stringify({ priority: 'low' })}) describe 'shows the starter license upsell', -> it 'when only subscription prepaids exist', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ type: 'subscription' startDate: moment().subtract(3, 'weeks').toISOString() endDate: moment().add(2, 'weeks').toISOString() })) @view.prepaids.trigger('sync') @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(1) it 'when active starter licenses exist', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ type: 'starter_license' startDate: moment().subtract(3, 'weeks').toISOString() endDate: moment().add(2, 'weeks').toISOString() })) @view.prepaids.trigger('sync') @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(1) it 'when expired starter licenses exist', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ type: 'starter_license' startDate: moment().subtract(3, 'week').toISOString() endDate: moment().subtract(1, 'week').toISOString() })) @view.prepaids.trigger('sync') @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(1) it 'when no prepaids exist', -> @view.prepaids.set([]) @view.prepaids.trigger('sync') @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(1) describe 'does not show the starter license upsell', -> it 'when full licenses have existed', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ startDate: moment().subtract(2, 'month').toISOString() endDate: moment().subtract(1, 'month').toISOString() })) @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(0) it 'when full licenses currently exist', -> @view.prepaids.set([]) @view.prepaids.add(factories.makePrepaid({ startDate: moment().subtract(2, 'month').toISOString() endDate: moment().add(1, 'month').toISOString() })) @view.render() expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(0) describe 'For high priority leads', -> beforeEach -> leadPriorityRequest = jasmine.Ajax.requests.filter((r)-> r.url == '/db/user/-/lead-priority')[0] leadPriorityRequest.respondWith({status: 200, responseText: JSON.stringify({ priority: 'high' })}) @view.render() it "doesn't show the Starter License upsell", -> expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(0) describe 'For no priority leads', -> beforeEach -> leadPriorityRequest = jasmine.Ajax.requests.filter((r)-> r.url == '/db/user/-/lead-priority')[0] leadPriorityRequest.respondWith({status: 200, responseText: JSON.stringify({ priority: undefined })}) @view.render() it "doesn't show the Starter License upsell", -> expect(@view.$('a[href="/teachers/starter-licenses"]').length).toBe(0) describe '"Get Licenses" area', -> describe 'when the teacher has made contact', -> beforeEach -> @view.enrollmentRequestSent = true @view.render() it 'shows confirmation and a mailto link to PI:EMAIL:<EMAIL>END_PI', -> if not @view.$('#request-sent-btn').length fail('Request button not found.') if not @view.$('#enrollment-request-sent-blurb').length fail('License request sent blurb not found.') # TODO: Figure out why this fails in Travis. Seems like it's not loading en locale # if not @view.$('a[href="mailto:PI:EMAIL:<EMAIL>END_PI"]').length # fail('Mailto: link not found.') describe 'when there are no prepaids to show', -> beforeEach (done) -> @view.prepaids.reset([]) @view.updatePrepaidGroups() _.defer(done) it 'fills the void with the rest of the page content', -> expect(@view.$('#actions-col').length).toBe(0)
[ { "context": "### Copyright (c) 2015 Magnus Leo. All rights reserved. ###\n\ncore = require('../mod", "end": 33, "score": 0.9998688697814941, "start": 23, "tag": "NAME", "value": "Magnus Leo" } ]
src/classes/Shape.coffee
magnusleo/Leo-Engine
1
### Copyright (c) 2015 Magnus Leo. All rights reserved. ### core = require('../modules/core') background = require('../modules/background') util = require('../modules/util') view = require('../modules/view') module.exports = class Shape constructor: (data) -> # Shape::constructor defaultData = fillStyle: 'rgba(255,0,0,0.4)' strokeStyle: 'rgba(255,0,0,0.7)' h: 1 w: 1 x: 0 y: 0 data = util.merge(defaultData, data) for name, val of data this[name] = val core.shapes.push this draw: -> # Shape::draw if not @isVisible return false @drawX = view.posToPx(@x, 'x') @drawY = view.posToPx(@y, 'y') @drawW = @w * background.tileSize @drawH = @h * background.tileSize core.frameBufferCtx.fillStyle = @fillStyle core.frameBufferCtx.strokeStyle = @strokeStyle # Shape specific drawing in subclass (e.g. Rect) return true
34115
### Copyright (c) 2015 <NAME>. All rights reserved. ### core = require('../modules/core') background = require('../modules/background') util = require('../modules/util') view = require('../modules/view') module.exports = class Shape constructor: (data) -> # Shape::constructor defaultData = fillStyle: 'rgba(255,0,0,0.4)' strokeStyle: 'rgba(255,0,0,0.7)' h: 1 w: 1 x: 0 y: 0 data = util.merge(defaultData, data) for name, val of data this[name] = val core.shapes.push this draw: -> # Shape::draw if not @isVisible return false @drawX = view.posToPx(@x, 'x') @drawY = view.posToPx(@y, 'y') @drawW = @w * background.tileSize @drawH = @h * background.tileSize core.frameBufferCtx.fillStyle = @fillStyle core.frameBufferCtx.strokeStyle = @strokeStyle # Shape specific drawing in subclass (e.g. Rect) return true
true
### Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved. ### core = require('../modules/core') background = require('../modules/background') util = require('../modules/util') view = require('../modules/view') module.exports = class Shape constructor: (data) -> # Shape::constructor defaultData = fillStyle: 'rgba(255,0,0,0.4)' strokeStyle: 'rgba(255,0,0,0.7)' h: 1 w: 1 x: 0 y: 0 data = util.merge(defaultData, data) for name, val of data this[name] = val core.shapes.push this draw: -> # Shape::draw if not @isVisible return false @drawX = view.posToPx(@x, 'x') @drawY = view.posToPx(@y, 'y') @drawW = @w * background.tileSize @drawH = @h * background.tileSize core.frameBufferCtx.fillStyle = @fillStyle core.frameBufferCtx.strokeStyle = @strokeStyle # Shape specific drawing in subclass (e.g. Rect) return true
[ { "context": "base64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\"\n\n", "end": 27, "score": 0.750749409198761, "start": 16, "tag": "KEY", "value": "GHIJKLMNOPQ" }, { "context": "base64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\"\n\...
js/convert.coffee
bernikr/L64
0
base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" locationToL64 = (lat, lon, length) -> # normalize the coordinates to be in the range 0..1 x = (lon / 360 + 0.5) y = (lat / 180 + 0.5) # transform the coordinates to a binary tree per coordinate [x,y] = (pad(c.toString(2).substr(2), length*3) for c in [x,y]) # combine the binary trees into a single one by alternating digits binaryTree = '' for i in [0...length*3] binaryTree += y.charAt(i) + x.charAt(i) # split the binary tree in 6 bit chunks and convert them to base64 splitBT = (binaryTree.substr(x, 6) for x in [0...binaryTree.length] by 6) base64Location = (base64.charAt(parseInt(x, 2)) for x in splitBT).join('') l64ToLocation = (base64Location) -> # convert the L64 location into the binary tree by changing the basis chars = base64Location.split('') numericKey = (base64.indexOf(char) for char in chars) binaryTree = (pad(num.toString(2),6, true) for num in numericKey).join('') # split the binary tree into the trees for x and y [x, y] = ['',''] for i in [0...binaryTree.length] by 2 y += binaryTree.charAt(i) x += binaryTree.charAt(i+1) # convert the binary tree into coordinates between 0 and 1 [x,y] = ((parseInt(c, 2)+0.5)/Math.pow(2, binaryTree.length/2) for c in [x,y]) # transform the normalized coordinates back into lat and lon location = lon: (x - 0.5) * 360 lat: (y - 0.5) * 180 # function to left or right pad numbers with 0s to a wished length pad = (str, length, padLeft) -> padding = '0'.repeat(length) if padLeft (padding + str).slice(-length) else (str + padding).substring(0, length)
186901
base64 = "ABCDEF<KEY>RSTUV<KEY> locationToL64 = (lat, lon, length) -> # normalize the coordinates to be in the range 0..1 x = (lon / 360 + 0.5) y = (lat / 180 + 0.5) # transform the coordinates to a binary tree per coordinate [x,y] = (pad(c.toString(2).substr(2), length*3) for c in [x,y]) # combine the binary trees into a single one by alternating digits binaryTree = '' for i in [0...length*3] binaryTree += y.charAt(i) + x.charAt(i) # split the binary tree in 6 bit chunks and convert them to base64 splitBT = (binaryTree.substr(x, 6) for x in [0...binaryTree.length] by 6) base64Location = (base64.charAt(parseInt(x, 2)) for x in splitBT).join('') l64ToLocation = (base64Location) -> # convert the L64 location into the binary tree by changing the basis chars = base64Location.split('') numericKey = (base64.indexOf(char) for char in chars) binaryTree = (pad(num.toString(2),6, true) for num in numericKey).join('') # split the binary tree into the trees for x and y [x, y] = ['',''] for i in [0...binaryTree.length] by 2 y += binaryTree.charAt(i) x += binaryTree.charAt(i+1) # convert the binary tree into coordinates between 0 and 1 [x,y] = ((parseInt(c, 2)+0.5)/Math.pow(2, binaryTree.length/2) for c in [x,y]) # transform the normalized coordinates back into lat and lon location = lon: (x - 0.5) * 360 lat: (y - 0.5) * 180 # function to left or right pad numbers with 0s to a wished length pad = (str, length, padLeft) -> padding = '0'.repeat(length) if padLeft (padding + str).slice(-length) else (str + padding).substring(0, length)
true
base64 = "ABCDEFPI:KEY:<KEY>END_PIRSTUVPI:KEY:<KEY>END_PI locationToL64 = (lat, lon, length) -> # normalize the coordinates to be in the range 0..1 x = (lon / 360 + 0.5) y = (lat / 180 + 0.5) # transform the coordinates to a binary tree per coordinate [x,y] = (pad(c.toString(2).substr(2), length*3) for c in [x,y]) # combine the binary trees into a single one by alternating digits binaryTree = '' for i in [0...length*3] binaryTree += y.charAt(i) + x.charAt(i) # split the binary tree in 6 bit chunks and convert them to base64 splitBT = (binaryTree.substr(x, 6) for x in [0...binaryTree.length] by 6) base64Location = (base64.charAt(parseInt(x, 2)) for x in splitBT).join('') l64ToLocation = (base64Location) -> # convert the L64 location into the binary tree by changing the basis chars = base64Location.split('') numericKey = (base64.indexOf(char) for char in chars) binaryTree = (pad(num.toString(2),6, true) for num in numericKey).join('') # split the binary tree into the trees for x and y [x, y] = ['',''] for i in [0...binaryTree.length] by 2 y += binaryTree.charAt(i) x += binaryTree.charAt(i+1) # convert the binary tree into coordinates between 0 and 1 [x,y] = ((parseInt(c, 2)+0.5)/Math.pow(2, binaryTree.length/2) for c in [x,y]) # transform the normalized coordinates back into lat and lon location = lon: (x - 0.5) * 360 lat: (y - 0.5) * 180 # function to left or right pad numbers with 0s to a wished length pad = (str, length, padLeft) -> padding = '0'.repeat(length) if padLeft (padding + str).slice(-length) else (str + padding).substring(0, length)
[ { "context": "52960\n# Type: 'A'\n# Name: 'abbyy-0'\n# Target: '176.58.107.125'\n# TTL_sec: 3600\n# , ->\n\n#client.call 'avail.Lin", "end": 351, "score": 0.999734103679657, "start": 337, "tag": "IP_ADDRESS", "value": "176.58.107.125" }, { "context": " 'Label': 'system'\n# 'Size...
test_util/linodinator.coffee
scraperwiki/lithium
0
#!/usr/bin/env coffee nock = require 'nock' nock.recorder.rec() LinodeClient = (require 'linode-api').LinodeClient client = new LinodeClient process.env['LINODE_API_KEY'] #client.call 'linode.ip.list', # LinodeID: 206102 # , -> #client.call 'domain.resource.create', # DomainID: 352960 # Type: 'A' # Name: 'abbyy-0' # Target: '176.58.107.125' # TTL_sec: 3600 # , -> #client.call 'avail.LinodePlans',null, -> #client.call 'avail.kernels',null, -> #client.call 'avail.distributions',null, -> # #client.call 'linode.delete', # 'LinodeID': 206912 # 'skipChecks': true # , -> #client.call 'linode.disk.createfromdistribution', #client.call 'linode.create', # 'DatacenterID': 7 # 'PlanID': 1 # 'PaymentTerm': 1 # , -> # #client.call 'linode.list',null, -> #client.call 'domain.resource.list', # DomainID: 352960 # , -> client.call 'domain.resource.delete', DomainID: 352960 ResourceID: 2455909 , -> #client.call 'linode.ip.addprivate', # 'LinodeID': 222837 # , -> #client.call 'linode.list', # 'LinodeID': 206097 # 'asdasdsad': 'asasda' # , -> # #client.call 'linode.update', # 'LinodeID': 206097 # 'Label': 'test' # , -> # #client.call 'linode.disk.createfromdistribution', # 'LinodeID': 206097 # 'DistributionID': 98 #ubuntu 12.04 # 'Label': 'system' # 'Size': 5048 # 'rootPass':'r00ter' # , -> # #client.call 'linode.disk.create', # 'LinodeID': 206097 # 'Label': 'data' # 'Type': 'ext3' # 'Size': 10000 # , -> # #client.call 'linode.config.create', # 'LinodeID': 206097 # 'KernelID': 121 # 'Label': 'test' # 'Comments': 'decription' # 'DiskList': '953010,953011' # 'RootDeviceNum': 1 # , -> #client.call 'linode.boot', # 'LinodeID': 206097 # , -> # #client.call 'linode.ip.list', # 'LinodeID': 206097 # , -> #client.call 'linode.reboot', # 'LinodeID': 206097 # , -> # #client.call 'linode.shutdown', # 'LinodeID': 206097 # , ->
151225
#!/usr/bin/env coffee nock = require 'nock' nock.recorder.rec() LinodeClient = (require 'linode-api').LinodeClient client = new LinodeClient process.env['LINODE_API_KEY'] #client.call 'linode.ip.list', # LinodeID: 206102 # , -> #client.call 'domain.resource.create', # DomainID: 352960 # Type: 'A' # Name: 'abbyy-0' # Target: '172.16.17.32' # TTL_sec: 3600 # , -> #client.call 'avail.LinodePlans',null, -> #client.call 'avail.kernels',null, -> #client.call 'avail.distributions',null, -> # #client.call 'linode.delete', # 'LinodeID': 206912 # 'skipChecks': true # , -> #client.call 'linode.disk.createfromdistribution', #client.call 'linode.create', # 'DatacenterID': 7 # 'PlanID': 1 # 'PaymentTerm': 1 # , -> # #client.call 'linode.list',null, -> #client.call 'domain.resource.list', # DomainID: 352960 # , -> client.call 'domain.resource.delete', DomainID: 352960 ResourceID: 2455909 , -> #client.call 'linode.ip.addprivate', # 'LinodeID': 222837 # , -> #client.call 'linode.list', # 'LinodeID': 206097 # 'asdasdsad': 'asasda' # , -> # #client.call 'linode.update', # 'LinodeID': 206097 # 'Label': 'test' # , -> # #client.call 'linode.disk.createfromdistribution', # 'LinodeID': 206097 # 'DistributionID': 98 #ubuntu 12.04 # 'Label': 'system' # 'Size': 5048 # 'rootPass':'<PASSWORD>' # , -> # #client.call 'linode.disk.create', # 'LinodeID': 206097 # 'Label': 'data' # 'Type': 'ext3' # 'Size': 10000 # , -> # #client.call 'linode.config.create', # 'LinodeID': 206097 # 'KernelID': 121 # 'Label': 'test' # 'Comments': 'decription' # 'DiskList': '953010,953011' # 'RootDeviceNum': 1 # , -> #client.call 'linode.boot', # 'LinodeID': 206097 # , -> # #client.call 'linode.ip.list', # 'LinodeID': 206097 # , -> #client.call 'linode.reboot', # 'LinodeID': 206097 # , -> # #client.call 'linode.shutdown', # 'LinodeID': 206097 # , ->
true
#!/usr/bin/env coffee nock = require 'nock' nock.recorder.rec() LinodeClient = (require 'linode-api').LinodeClient client = new LinodeClient process.env['LINODE_API_KEY'] #client.call 'linode.ip.list', # LinodeID: 206102 # , -> #client.call 'domain.resource.create', # DomainID: 352960 # Type: 'A' # Name: 'abbyy-0' # Target: 'PI:IP_ADDRESS:172.16.17.32END_PI' # TTL_sec: 3600 # , -> #client.call 'avail.LinodePlans',null, -> #client.call 'avail.kernels',null, -> #client.call 'avail.distributions',null, -> # #client.call 'linode.delete', # 'LinodeID': 206912 # 'skipChecks': true # , -> #client.call 'linode.disk.createfromdistribution', #client.call 'linode.create', # 'DatacenterID': 7 # 'PlanID': 1 # 'PaymentTerm': 1 # , -> # #client.call 'linode.list',null, -> #client.call 'domain.resource.list', # DomainID: 352960 # , -> client.call 'domain.resource.delete', DomainID: 352960 ResourceID: 2455909 , -> #client.call 'linode.ip.addprivate', # 'LinodeID': 222837 # , -> #client.call 'linode.list', # 'LinodeID': 206097 # 'asdasdsad': 'asasda' # , -> # #client.call 'linode.update', # 'LinodeID': 206097 # 'Label': 'test' # , -> # #client.call 'linode.disk.createfromdistribution', # 'LinodeID': 206097 # 'DistributionID': 98 #ubuntu 12.04 # 'Label': 'system' # 'Size': 5048 # 'rootPass':'PI:PASSWORD:<PASSWORD>END_PI' # , -> # #client.call 'linode.disk.create', # 'LinodeID': 206097 # 'Label': 'data' # 'Type': 'ext3' # 'Size': 10000 # , -> # #client.call 'linode.config.create', # 'LinodeID': 206097 # 'KernelID': 121 # 'Label': 'test' # 'Comments': 'decription' # 'DiskList': '953010,953011' # 'RootDeviceNum': 1 # , -> #client.call 'linode.boot', # 'LinodeID': 206097 # , -> # #client.call 'linode.ip.list', # 'LinodeID': 206097 # , -> #client.call 'linode.reboot', # 'LinodeID': 206097 # , -> # #client.call 'linode.shutdown', # 'LinodeID': 206097 # , ->
[ { "context": "y('standard', 'cookie', {\n\t password: 'hardToGuessCookieSecret',\n\t cookie: 'app-cookie',\n\t ", "end": 330, "score": 0.9992437362670898, "start": 307, "tag": "PASSWORD", "value": "hardToGuessCookieSecret" } ]
modules/auth/index.coffee
scotthathaway/hapifw
4
Promise = require('bluebird') exports.register = (server, options, next) -> server.register([{register: require('hapi-auth-cookie')}], (err) -> if err throw err # server authentication strategy server.auth.strategy('standard', 'cookie', { password: 'hardToGuessCookieSecret', cookie: 'app-cookie', isSecure: false, ttl: 24 * 60 * 60 * 1000 # 1 day }) ) views_config = { engines: html: require('handlebars') relativeTo: __dirname path: 'templates' } server.views(views_config) server.auth.default({ strategy: 'standard', scope: ['admin'] }) server.route({ method: 'GET', path: '/login', config: { auth: false, handler: require('./login') } }) server.route({ method: 'POST', path: '/login', config: { auth: false, handler: (request, reply) -> getUser(request.payload.username, request.payload.password).then((user) -> if user request.auth.session.set(user) return reply.redirect('/home') else return reply('Bad email or password') ) .catch((err) -> return reply('Login Failed') ) } }) server.route({ method: 'GET', path: '/logout', config: { auth: false, handler: (request, reply) -> request.auth.session.clear() return reply('Logout Successful!') } }) next() exports.register.attributes = { name: 'auth' } getUser = (email, password) -> sql = "select id,name,email,scope from people where email='#{email}' and password='#{password}'" r = new Promise((fulfill, reject) -> db = Promise.promisifyAll(require("../../libs/db")) return db.query(sql).then((rs)-> if rs.length > 0 rs[0].scope = [rs[0].scope] return fulfill(rs[0]) else return reject(null) ) ) return r
158517
Promise = require('bluebird') exports.register = (server, options, next) -> server.register([{register: require('hapi-auth-cookie')}], (err) -> if err throw err # server authentication strategy server.auth.strategy('standard', 'cookie', { password: '<PASSWORD>', cookie: 'app-cookie', isSecure: false, ttl: 24 * 60 * 60 * 1000 # 1 day }) ) views_config = { engines: html: require('handlebars') relativeTo: __dirname path: 'templates' } server.views(views_config) server.auth.default({ strategy: 'standard', scope: ['admin'] }) server.route({ method: 'GET', path: '/login', config: { auth: false, handler: require('./login') } }) server.route({ method: 'POST', path: '/login', config: { auth: false, handler: (request, reply) -> getUser(request.payload.username, request.payload.password).then((user) -> if user request.auth.session.set(user) return reply.redirect('/home') else return reply('Bad email or password') ) .catch((err) -> return reply('Login Failed') ) } }) server.route({ method: 'GET', path: '/logout', config: { auth: false, handler: (request, reply) -> request.auth.session.clear() return reply('Logout Successful!') } }) next() exports.register.attributes = { name: 'auth' } getUser = (email, password) -> sql = "select id,name,email,scope from people where email='#{email}' and password='#{password}'" r = new Promise((fulfill, reject) -> db = Promise.promisifyAll(require("../../libs/db")) return db.query(sql).then((rs)-> if rs.length > 0 rs[0].scope = [rs[0].scope] return fulfill(rs[0]) else return reject(null) ) ) return r
true
Promise = require('bluebird') exports.register = (server, options, next) -> server.register([{register: require('hapi-auth-cookie')}], (err) -> if err throw err # server authentication strategy server.auth.strategy('standard', 'cookie', { password: 'PI:PASSWORD:<PASSWORD>END_PI', cookie: 'app-cookie', isSecure: false, ttl: 24 * 60 * 60 * 1000 # 1 day }) ) views_config = { engines: html: require('handlebars') relativeTo: __dirname path: 'templates' } server.views(views_config) server.auth.default({ strategy: 'standard', scope: ['admin'] }) server.route({ method: 'GET', path: '/login', config: { auth: false, handler: require('./login') } }) server.route({ method: 'POST', path: '/login', config: { auth: false, handler: (request, reply) -> getUser(request.payload.username, request.payload.password).then((user) -> if user request.auth.session.set(user) return reply.redirect('/home') else return reply('Bad email or password') ) .catch((err) -> return reply('Login Failed') ) } }) server.route({ method: 'GET', path: '/logout', config: { auth: false, handler: (request, reply) -> request.auth.session.clear() return reply('Logout Successful!') } }) next() exports.register.attributes = { name: 'auth' } getUser = (email, password) -> sql = "select id,name,email,scope from people where email='#{email}' and password='#{password}'" r = new Promise((fulfill, reject) -> db = Promise.promisifyAll(require("../../libs/db")) return db.query(sql).then((rs)-> if rs.length > 0 rs[0].scope = [rs[0].scope] return fulfill(rs[0]) else return reject(null) ) ) return r
[ { "context": " Code from [`groc/lib/utils`][1]\n\n @copyright Ian MacLeod and groc contributors\n\n [1]: https://github.", "end": 3877, "score": 0.9998866319656372, "start": 3866, "tag": "NAME", "value": "Ian MacLeod" }, { "context": " groc contributors\n\n [1]: https:...
test/utils/processDocTags_spec.coffee
vitkarpov/grock
1
expect = require('chai').expect Buffer = require('buffer').Buffer marked = require('marked') process = require '../../lib/utils/processDocTags' # ## Fake data # # Parsing starts with one empty description tag, so add that one to `tagCount`. docTagsValid = code: """ # @method Parse Doc Tags # @description Parses comments of segment for doc tags. Adds `tags` and # `tagSections` to each segment. # @param {Array} segments `[{code, comments}]` # @param {String} segments.code # @return {Promise} Resolves when segment comments have been processed """.trim(), tagCount: 5 + 1, keys: ['description', 'params', 'returns'] docTagsInvalid = code: """ # ## Parse Doc Tags # @description Parses comments of segment for doc tags. Adds `tags` and # `tagSections` to each segment. # @param # @ # @return Resolves when segment comments have been processed """.trim(), tagCount: 4, keys: ['description', 'params', 'returns'] describe "Documentation Tags", -> describe "Parsing", -> it "should work for correct doc tags", (done) -> process .parseDocTags [{code: "", comments: docTagsValid.code.split('\n')}] .then ([segment]) -> expect(segment.tags).to.be.an('array') expect(segment.tags.length).to.eql docTagsValid.tagCount expect(segment.tagSections).to.be.an('object') expect(segment.tagSections).to.contain.keys(docTagsValid.keys) expect(segment.tagSections.returns.length).to.eql 1 .then -> done() .then null, done it "should not throw when incorrent tags are present", (done) -> process .parseDocTags [{code: "", comments: docTagsInvalid.code.split('\n')}] .then ([segment]) -> expect(segment.tags).to.be.an('array') expect(segment.tags.length).to.eql docTagsInvalid.tagCount expect(segment.tagSections).to.be.an('object') expect(segment.tagSections).to.contain.keys(docTagsInvalid.keys) expect(segment.tagSections.returns.length).to.eql 1 .then -> done() .then null, done describe "Convert to Markdown", -> it "should work for correct doc tags", (done) -> process .parseDocTags [{code: "", comments: docTagsValid.code.split('\n')}] .then process.markdownDocTags .then ([{tags}]) -> expect(tags).to.be.an('array') expect(tags.length).to.be.above 0 tags.forEach (tag) -> expect(tag.markdown).to.exist .then -> done() .then null, done it "should not throw when incorrent tags are present", (done) -> process .parseDocTags [{code: "", comments: docTagsInvalid.code.split('\n')}] .then process.markdownDocTags .then ([{tags}]) -> expect(tags).to.be.an('array') expect(tags.length).to.be.above 0 tags.forEach (tag) -> expect(tag.markdown).to.exist .then -> done() .then null, done describe "Combine to HTML", -> it "should write all doc tags to segment comments", (done) -> process .parseDocTags [{code: "", comments: docTagsValid.code.split('\n')}] .then process.markdownDocTags .then process.renderDocTags .then ([{comments}]) -> # Actually, it's an array of lines for some reason expect(comments).to.be.an('array') expect(comment = comments.join('\n')).to.be.a('string') # Some values from the fake data above expect(comment).to.contain('Parse Doc Tags') expect(comment).to.contain('Parameters:') expect(comment).to.contain('Parses comments of segment for') expect(comment).to.contain('Promise') .then -> done() .then null, done describe "Issues", -> it "DocTag order shouldn't destroy URLs (#7)", (done) -> crazyMarkdown = """ # Seperate Code and Comments into Segments Code from [`groc/lib/utils`][1] @copyright Ian MacLeod and groc contributors [1]: https://github.com/nevir/groc/blob/b626e45ebf/lib/utils.coffee """.trim() process .parseDocTags [{code: "", comments: crazyMarkdown.split('\n')}] .then process.markdownDocTags .then process.renderDocTags .then ([segment]) -> comments = segment.comments.join('\n') expect(marked comments).to.not.contain '<a href="https://github.com/nevir/groc/blob/b626e45ebf/lib/utils.coffee&lt;/span">' .then -> done() .then null, done
213682
expect = require('chai').expect Buffer = require('buffer').Buffer marked = require('marked') process = require '../../lib/utils/processDocTags' # ## Fake data # # Parsing starts with one empty description tag, so add that one to `tagCount`. docTagsValid = code: """ # @method Parse Doc Tags # @description Parses comments of segment for doc tags. Adds `tags` and # `tagSections` to each segment. # @param {Array} segments `[{code, comments}]` # @param {String} segments.code # @return {Promise} Resolves when segment comments have been processed """.trim(), tagCount: 5 + 1, keys: ['description', 'params', 'returns'] docTagsInvalid = code: """ # ## Parse Doc Tags # @description Parses comments of segment for doc tags. Adds `tags` and # `tagSections` to each segment. # @param # @ # @return Resolves when segment comments have been processed """.trim(), tagCount: 4, keys: ['description', 'params', 'returns'] describe "Documentation Tags", -> describe "Parsing", -> it "should work for correct doc tags", (done) -> process .parseDocTags [{code: "", comments: docTagsValid.code.split('\n')}] .then ([segment]) -> expect(segment.tags).to.be.an('array') expect(segment.tags.length).to.eql docTagsValid.tagCount expect(segment.tagSections).to.be.an('object') expect(segment.tagSections).to.contain.keys(docTagsValid.keys) expect(segment.tagSections.returns.length).to.eql 1 .then -> done() .then null, done it "should not throw when incorrent tags are present", (done) -> process .parseDocTags [{code: "", comments: docTagsInvalid.code.split('\n')}] .then ([segment]) -> expect(segment.tags).to.be.an('array') expect(segment.tags.length).to.eql docTagsInvalid.tagCount expect(segment.tagSections).to.be.an('object') expect(segment.tagSections).to.contain.keys(docTagsInvalid.keys) expect(segment.tagSections.returns.length).to.eql 1 .then -> done() .then null, done describe "Convert to Markdown", -> it "should work for correct doc tags", (done) -> process .parseDocTags [{code: "", comments: docTagsValid.code.split('\n')}] .then process.markdownDocTags .then ([{tags}]) -> expect(tags).to.be.an('array') expect(tags.length).to.be.above 0 tags.forEach (tag) -> expect(tag.markdown).to.exist .then -> done() .then null, done it "should not throw when incorrent tags are present", (done) -> process .parseDocTags [{code: "", comments: docTagsInvalid.code.split('\n')}] .then process.markdownDocTags .then ([{tags}]) -> expect(tags).to.be.an('array') expect(tags.length).to.be.above 0 tags.forEach (tag) -> expect(tag.markdown).to.exist .then -> done() .then null, done describe "Combine to HTML", -> it "should write all doc tags to segment comments", (done) -> process .parseDocTags [{code: "", comments: docTagsValid.code.split('\n')}] .then process.markdownDocTags .then process.renderDocTags .then ([{comments}]) -> # Actually, it's an array of lines for some reason expect(comments).to.be.an('array') expect(comment = comments.join('\n')).to.be.a('string') # Some values from the fake data above expect(comment).to.contain('Parse Doc Tags') expect(comment).to.contain('Parameters:') expect(comment).to.contain('Parses comments of segment for') expect(comment).to.contain('Promise') .then -> done() .then null, done describe "Issues", -> it "DocTag order shouldn't destroy URLs (#7)", (done) -> crazyMarkdown = """ # Seperate Code and Comments into Segments Code from [`groc/lib/utils`][1] @copyright <NAME> and groc contributors [1]: https://github.com/nevir/groc/blob/b626e45ebf/lib/utils.coffee """.trim() process .parseDocTags [{code: "", comments: crazyMarkdown.split('\n')}] .then process.markdownDocTags .then process.renderDocTags .then ([segment]) -> comments = segment.comments.join('\n') expect(marked comments).to.not.contain '<a href="https://github.com/nevir/groc/blob/b626e45ebf/lib/utils.coffee&lt;/span">' .then -> done() .then null, done
true
expect = require('chai').expect Buffer = require('buffer').Buffer marked = require('marked') process = require '../../lib/utils/processDocTags' # ## Fake data # # Parsing starts with one empty description tag, so add that one to `tagCount`. docTagsValid = code: """ # @method Parse Doc Tags # @description Parses comments of segment for doc tags. Adds `tags` and # `tagSections` to each segment. # @param {Array} segments `[{code, comments}]` # @param {String} segments.code # @return {Promise} Resolves when segment comments have been processed """.trim(), tagCount: 5 + 1, keys: ['description', 'params', 'returns'] docTagsInvalid = code: """ # ## Parse Doc Tags # @description Parses comments of segment for doc tags. Adds `tags` and # `tagSections` to each segment. # @param # @ # @return Resolves when segment comments have been processed """.trim(), tagCount: 4, keys: ['description', 'params', 'returns'] describe "Documentation Tags", -> describe "Parsing", -> it "should work for correct doc tags", (done) -> process .parseDocTags [{code: "", comments: docTagsValid.code.split('\n')}] .then ([segment]) -> expect(segment.tags).to.be.an('array') expect(segment.tags.length).to.eql docTagsValid.tagCount expect(segment.tagSections).to.be.an('object') expect(segment.tagSections).to.contain.keys(docTagsValid.keys) expect(segment.tagSections.returns.length).to.eql 1 .then -> done() .then null, done it "should not throw when incorrent tags are present", (done) -> process .parseDocTags [{code: "", comments: docTagsInvalid.code.split('\n')}] .then ([segment]) -> expect(segment.tags).to.be.an('array') expect(segment.tags.length).to.eql docTagsInvalid.tagCount expect(segment.tagSections).to.be.an('object') expect(segment.tagSections).to.contain.keys(docTagsInvalid.keys) expect(segment.tagSections.returns.length).to.eql 1 .then -> done() .then null, done describe "Convert to Markdown", -> it "should work for correct doc tags", (done) -> process .parseDocTags [{code: "", comments: docTagsValid.code.split('\n')}] .then process.markdownDocTags .then ([{tags}]) -> expect(tags).to.be.an('array') expect(tags.length).to.be.above 0 tags.forEach (tag) -> expect(tag.markdown).to.exist .then -> done() .then null, done it "should not throw when incorrent tags are present", (done) -> process .parseDocTags [{code: "", comments: docTagsInvalid.code.split('\n')}] .then process.markdownDocTags .then ([{tags}]) -> expect(tags).to.be.an('array') expect(tags.length).to.be.above 0 tags.forEach (tag) -> expect(tag.markdown).to.exist .then -> done() .then null, done describe "Combine to HTML", -> it "should write all doc tags to segment comments", (done) -> process .parseDocTags [{code: "", comments: docTagsValid.code.split('\n')}] .then process.markdownDocTags .then process.renderDocTags .then ([{comments}]) -> # Actually, it's an array of lines for some reason expect(comments).to.be.an('array') expect(comment = comments.join('\n')).to.be.a('string') # Some values from the fake data above expect(comment).to.contain('Parse Doc Tags') expect(comment).to.contain('Parameters:') expect(comment).to.contain('Parses comments of segment for') expect(comment).to.contain('Promise') .then -> done() .then null, done describe "Issues", -> it "DocTag order shouldn't destroy URLs (#7)", (done) -> crazyMarkdown = """ # Seperate Code and Comments into Segments Code from [`groc/lib/utils`][1] @copyright PI:NAME:<NAME>END_PI and groc contributors [1]: https://github.com/nevir/groc/blob/b626e45ebf/lib/utils.coffee """.trim() process .parseDocTags [{code: "", comments: crazyMarkdown.split('\n')}] .then process.markdownDocTags .then process.renderDocTags .then ([segment]) -> comments = segment.comments.join('\n') expect(marked comments).to.not.contain '<a href="https://github.com/nevir/groc/blob/b626e45ebf/lib/utils.coffee&lt;/span">' .then -> done() .then null, done
[ { "context": "ame='row'>\n <span className='col-md-6'>by Anonymous:</span>\n &nbsp;\n <span c", "end": 183, "score": 0.648270308971405, "start": 181, "tag": "NAME", "value": "An" }, { "context": "='row'>\n <span className='col-md-6'>by Anonymous:</...
app/assets/javascripts/components/description.jsx.coffee
gaiax-asia/describe_me
0
jQuery -> Component.Description = React.createClass render: -> return `<div className='container'> <div className='row'> <span className='col-md-6'>by Anonymous:</span> &nbsp; <span className='col-md-6'>{this.props.description}</span> </div> </div>`
115320
jQuery -> Component.Description = React.createClass render: -> return `<div className='container'> <div className='row'> <span className='col-md-6'>by <NAME> <NAME>:</span> &nbsp; <span className='col-md-6'>{this.props.description}</span> </div> </div>`
true
jQuery -> Component.Description = React.createClass render: -> return `<div className='container'> <div className='row'> <span className='col-md-6'>by PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI:</span> &nbsp; <span className='col-md-6'>{this.props.description}</span> </div> </div>`
[ { "context": "---------------------------------\n# Copyright 2013 I.B.M.\n# \n# Licensed under the Apache License, Version 2", "end": 547, "score": 0.9946846961975098, "start": 542, "tag": "NAME", "value": "I.B.M" } ]
samples/time-waster.coffee
pmuellr/nodprof
6
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" exports.run = (times) -> console.log "running #{__filename}" for i in [0..times] setTimeout (-> runOuter times), 100 * i runOuter = (times) -> runInner (times) runInner = (times) -> for i in [0..times] entries = fs.readdirSync "." if require.main is module or global.nodprofProfiling exports.run 50 #------------------------------------------------------------------------------- # Copyright 2013 I.B.M. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
71
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" exports.run = (times) -> console.log "running #{__filename}" for i in [0..times] setTimeout (-> runOuter times), 100 * i runOuter = (times) -> runInner (times) runInner = (times) -> for i in [0..times] entries = fs.readdirSync "." if require.main is module or global.nodprofProfiling exports.run 50 #------------------------------------------------------------------------------- # Copyright 2013 <NAME>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
true
# Licensed under the Apache License. See footer for details. fs = require "fs" path = require "path" exports.run = (times) -> console.log "running #{__filename}" for i in [0..times] setTimeout (-> runOuter times), 100 * i runOuter = (times) -> runInner (times) runInner = (times) -> for i in [0..times] entries = fs.readdirSync "." if require.main is module or global.nodprofProfiling exports.run 50 #------------------------------------------------------------------------------- # Copyright 2013 PI:NAME:<NAME>END_PI. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
[ { "context": "###\njbfilereader.coffee\n\nCopyright (c) 2015 Jeongbin Park\n\nPermission is hereby granted, free of charge, to", "end": 57, "score": 0.9997449517250061, "start": 44, "tag": "NAME", "value": "Jeongbin Park" } ]
jbfilereader.coffee
pjb7687/jbfilereader
0
### jbfilereader.coffee Copyright (c) 2015 Jeongbin Park 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. ### class _inflater constructor: -> window_bits = 15 enable_windows_gzip = 32 @inflater_pako = new pako.Inflate({to: 'string', chunkSize: 16384, windowBits: window_bits|enable_windows_gzip}) @inflating_buffer = '' that = this @inflater_pako.onData = (chunk) -> that.inflating_buffer += chunk return return decompress: (chunk, islastchunk) -> @inflating_buffer = '' @inflater_pako.push(chunk, islastchunk) @ended = @inflater_pako.ended @strm = @inflater_pako.strm return @inflating_buffer class jbfilereadersync constructor: (@file, @gzipped) -> @buffer = '' @filesize = @file.size @chunksize = 1024 * 512 @reader = new FileReaderSync() if @gzipped @inflater = new _inflater() @islastchunk = false @fpos = 0 @endpos = 0 @eof = false return _getchunk: -> if @fpos + @chunksize >= @filesize @endpos = @filesize @islastchunk = true else @endpos = @fpos + @chunksize blob = @file.slice(@fpos, @endpos) @fpos += @endpos - @fpos if @gzipped raw_array = new Uint8Array(@reader.readAsArrayBuffer(blob)) s = @inflater.decompress(raw_array, @islastchunk) if s if @inflater.ended and (@inflater.strm.avail_in or !@islastchunk) # Non-standard gzip. See http://www.gzip.org/#faq8 remaining_bytes = @inflater.strm.avail_in rel_pos = 0 while raw_array[raw_array.byteLength-remaining_bytes+rel_pos] == 0 rel_pos++ @fpos -= remaining_bytes-rel_pos @inflater = new _inflater() # Renew Pako else throw 'Something wrong with the gzipped file!' else s = @reader.readAsText(blob) return s readline: () -> if @eof return "" lfpos = @buffer.indexOf("\n") while lfpos == -1 if @fpos >= @filesize result = @buffer @buffer = "" @fpos = @filesize @eof = true return result @buffer += @_getchunk() lfpos = @buffer.indexOf("\n") if @buffer[lfpos-1] == "\r" result = @buffer[...lfpos-1] else result = @buffer[...lfpos] @buffer = @buffer[lfpos+1...] return result class jbfilereader constructor: (@file, @gzipped) -> @buffer = '' @filesize = @file.size @chunksize = 1024 * 512 @reader = new FileReader() if @gzipped @inflater = new _inflater() @islastchunk = false @fpos = 0 @endpos = 0 @eof = false return _readblob: (blob) -> that = this readpromise = new Promise( (resolve, reject) -> that.reader.onload = (e) -> resolve(e.target.result) that.reader.onerror = -> reject() return ) if @gzipped @reader.readAsArrayBuffer(blob) else @reader.readAsText(blob) return readpromise _getchunk: -> if @fpos + @chunksize >= @filesize @endpos = @filesize @islastchunk = true else @endpos = @fpos + @chunksize blob = @file.slice(@fpos, @endpos) that = this chunkpromise = new Promise( (resolve, reject) -> readpromise = that._readblob(blob) readpromise.then( (s) -> that.fpos += that.endpos - that.fpos if that.gzipped raw_array = new Uint8Array(s) s = that.inflater.decompress(raw_array, that.islastchunk) if s if that.inflater.ended and (that.inflater.strm.avail_in or !that.islastchunk) # Non-standard gzip. See http://www.gzip.org/#faq8 remaining_bytes = that.inflater.strm.avail_in rel_pos = 0 while raw_array[raw_array.byteLength-remaining_bytes+rel_pos] == 0 rel_pos++ that.fpos -= remaining_bytes-rel_pos that.inflater = new _inflater() # Renew Pako else alert('Something wrong with the gzipped file!') reject() that.buffer += s resolve() return ).catch( (s) -> alert('Something wrong while reading file!') reject() return ) ) return chunkpromise readline: (callback) -> if @eof callback("") lfpos = @buffer.indexOf("\n") if lfpos == -1 if @fpos >= @filesize result = @buffer @buffer = "" @eof = true callback(result) else that = this datapromise = @_getchunk() datapromise.then( -> that.readline(callback) ) else if @buffer[lfpos] == "\r" result = @buffer[...lfpos-1] else result = @buffer[...lfpos] @buffer = @buffer[lfpos+1...] callback(result) return
94491
### jbfilereader.coffee Copyright (c) 2015 <NAME> 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. ### class _inflater constructor: -> window_bits = 15 enable_windows_gzip = 32 @inflater_pako = new pako.Inflate({to: 'string', chunkSize: 16384, windowBits: window_bits|enable_windows_gzip}) @inflating_buffer = '' that = this @inflater_pako.onData = (chunk) -> that.inflating_buffer += chunk return return decompress: (chunk, islastchunk) -> @inflating_buffer = '' @inflater_pako.push(chunk, islastchunk) @ended = @inflater_pako.ended @strm = @inflater_pako.strm return @inflating_buffer class jbfilereadersync constructor: (@file, @gzipped) -> @buffer = '' @filesize = @file.size @chunksize = 1024 * 512 @reader = new FileReaderSync() if @gzipped @inflater = new _inflater() @islastchunk = false @fpos = 0 @endpos = 0 @eof = false return _getchunk: -> if @fpos + @chunksize >= @filesize @endpos = @filesize @islastchunk = true else @endpos = @fpos + @chunksize blob = @file.slice(@fpos, @endpos) @fpos += @endpos - @fpos if @gzipped raw_array = new Uint8Array(@reader.readAsArrayBuffer(blob)) s = @inflater.decompress(raw_array, @islastchunk) if s if @inflater.ended and (@inflater.strm.avail_in or !@islastchunk) # Non-standard gzip. See http://www.gzip.org/#faq8 remaining_bytes = @inflater.strm.avail_in rel_pos = 0 while raw_array[raw_array.byteLength-remaining_bytes+rel_pos] == 0 rel_pos++ @fpos -= remaining_bytes-rel_pos @inflater = new _inflater() # Renew Pako else throw 'Something wrong with the gzipped file!' else s = @reader.readAsText(blob) return s readline: () -> if @eof return "" lfpos = @buffer.indexOf("\n") while lfpos == -1 if @fpos >= @filesize result = @buffer @buffer = "" @fpos = @filesize @eof = true return result @buffer += @_getchunk() lfpos = @buffer.indexOf("\n") if @buffer[lfpos-1] == "\r" result = @buffer[...lfpos-1] else result = @buffer[...lfpos] @buffer = @buffer[lfpos+1...] return result class jbfilereader constructor: (@file, @gzipped) -> @buffer = '' @filesize = @file.size @chunksize = 1024 * 512 @reader = new FileReader() if @gzipped @inflater = new _inflater() @islastchunk = false @fpos = 0 @endpos = 0 @eof = false return _readblob: (blob) -> that = this readpromise = new Promise( (resolve, reject) -> that.reader.onload = (e) -> resolve(e.target.result) that.reader.onerror = -> reject() return ) if @gzipped @reader.readAsArrayBuffer(blob) else @reader.readAsText(blob) return readpromise _getchunk: -> if @fpos + @chunksize >= @filesize @endpos = @filesize @islastchunk = true else @endpos = @fpos + @chunksize blob = @file.slice(@fpos, @endpos) that = this chunkpromise = new Promise( (resolve, reject) -> readpromise = that._readblob(blob) readpromise.then( (s) -> that.fpos += that.endpos - that.fpos if that.gzipped raw_array = new Uint8Array(s) s = that.inflater.decompress(raw_array, that.islastchunk) if s if that.inflater.ended and (that.inflater.strm.avail_in or !that.islastchunk) # Non-standard gzip. See http://www.gzip.org/#faq8 remaining_bytes = that.inflater.strm.avail_in rel_pos = 0 while raw_array[raw_array.byteLength-remaining_bytes+rel_pos] == 0 rel_pos++ that.fpos -= remaining_bytes-rel_pos that.inflater = new _inflater() # Renew Pako else alert('Something wrong with the gzipped file!') reject() that.buffer += s resolve() return ).catch( (s) -> alert('Something wrong while reading file!') reject() return ) ) return chunkpromise readline: (callback) -> if @eof callback("") lfpos = @buffer.indexOf("\n") if lfpos == -1 if @fpos >= @filesize result = @buffer @buffer = "" @eof = true callback(result) else that = this datapromise = @_getchunk() datapromise.then( -> that.readline(callback) ) else if @buffer[lfpos] == "\r" result = @buffer[...lfpos-1] else result = @buffer[...lfpos] @buffer = @buffer[lfpos+1...] callback(result) return
true
### jbfilereader.coffee Copyright (c) 2015 PI:NAME:<NAME>END_PI 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. ### class _inflater constructor: -> window_bits = 15 enable_windows_gzip = 32 @inflater_pako = new pako.Inflate({to: 'string', chunkSize: 16384, windowBits: window_bits|enable_windows_gzip}) @inflating_buffer = '' that = this @inflater_pako.onData = (chunk) -> that.inflating_buffer += chunk return return decompress: (chunk, islastchunk) -> @inflating_buffer = '' @inflater_pako.push(chunk, islastchunk) @ended = @inflater_pako.ended @strm = @inflater_pako.strm return @inflating_buffer class jbfilereadersync constructor: (@file, @gzipped) -> @buffer = '' @filesize = @file.size @chunksize = 1024 * 512 @reader = new FileReaderSync() if @gzipped @inflater = new _inflater() @islastchunk = false @fpos = 0 @endpos = 0 @eof = false return _getchunk: -> if @fpos + @chunksize >= @filesize @endpos = @filesize @islastchunk = true else @endpos = @fpos + @chunksize blob = @file.slice(@fpos, @endpos) @fpos += @endpos - @fpos if @gzipped raw_array = new Uint8Array(@reader.readAsArrayBuffer(blob)) s = @inflater.decompress(raw_array, @islastchunk) if s if @inflater.ended and (@inflater.strm.avail_in or !@islastchunk) # Non-standard gzip. See http://www.gzip.org/#faq8 remaining_bytes = @inflater.strm.avail_in rel_pos = 0 while raw_array[raw_array.byteLength-remaining_bytes+rel_pos] == 0 rel_pos++ @fpos -= remaining_bytes-rel_pos @inflater = new _inflater() # Renew Pako else throw 'Something wrong with the gzipped file!' else s = @reader.readAsText(blob) return s readline: () -> if @eof return "" lfpos = @buffer.indexOf("\n") while lfpos == -1 if @fpos >= @filesize result = @buffer @buffer = "" @fpos = @filesize @eof = true return result @buffer += @_getchunk() lfpos = @buffer.indexOf("\n") if @buffer[lfpos-1] == "\r" result = @buffer[...lfpos-1] else result = @buffer[...lfpos] @buffer = @buffer[lfpos+1...] return result class jbfilereader constructor: (@file, @gzipped) -> @buffer = '' @filesize = @file.size @chunksize = 1024 * 512 @reader = new FileReader() if @gzipped @inflater = new _inflater() @islastchunk = false @fpos = 0 @endpos = 0 @eof = false return _readblob: (blob) -> that = this readpromise = new Promise( (resolve, reject) -> that.reader.onload = (e) -> resolve(e.target.result) that.reader.onerror = -> reject() return ) if @gzipped @reader.readAsArrayBuffer(blob) else @reader.readAsText(blob) return readpromise _getchunk: -> if @fpos + @chunksize >= @filesize @endpos = @filesize @islastchunk = true else @endpos = @fpos + @chunksize blob = @file.slice(@fpos, @endpos) that = this chunkpromise = new Promise( (resolve, reject) -> readpromise = that._readblob(blob) readpromise.then( (s) -> that.fpos += that.endpos - that.fpos if that.gzipped raw_array = new Uint8Array(s) s = that.inflater.decompress(raw_array, that.islastchunk) if s if that.inflater.ended and (that.inflater.strm.avail_in or !that.islastchunk) # Non-standard gzip. See http://www.gzip.org/#faq8 remaining_bytes = that.inflater.strm.avail_in rel_pos = 0 while raw_array[raw_array.byteLength-remaining_bytes+rel_pos] == 0 rel_pos++ that.fpos -= remaining_bytes-rel_pos that.inflater = new _inflater() # Renew Pako else alert('Something wrong with the gzipped file!') reject() that.buffer += s resolve() return ).catch( (s) -> alert('Something wrong while reading file!') reject() return ) ) return chunkpromise readline: (callback) -> if @eof callback("") lfpos = @buffer.indexOf("\n") if lfpos == -1 if @fpos >= @filesize result = @buffer @buffer = "" @eof = true callback(result) else that = this datapromise = @_getchunk() datapromise.then( -> that.readline(callback) ) else if @buffer[lfpos] == "\r" result = @buffer[...lfpos-1] else result = @buffer[...lfpos] @buffer = @buffer[lfpos+1...] callback(result) return
[ { "context": "view Enforce html element has lang prop.\n# @author Ethan Cohen\n###\n\n# ------------------------------------------", "end": 102, "score": 0.9998745918273926, "start": 91, "tag": "NAME", "value": "Ethan Cohen" } ]
src/tests/rules/html-has-lang.coffee
danielbayley/eslint-plugin-coffee
21
### eslint-env jest ### ###* # @fileoverview Enforce html element has lang prop. # @author Ethan Cohen ### # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- path = require 'path' {RuleTester} = require 'eslint' { default: parserOptionsMapper } = require '../eslint-plugin-jsx-a11y-parser-options-mapper' rule = require 'eslint-plugin-jsx-a11y/lib/rules/html-has-lang' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedError = message: '<html> elements must have the lang prop.' type: 'JSXOpeningElement' ruleTester.run 'html-has-lang', rule, valid: [ code: '<div />' , code: '<html lang="en" />' , code: '<html lang="en-US" />' , code: '<html lang={foo} />' , code: '<html lang />' , code: '<HTML />' ].map parserOptionsMapper invalid: [ code: '<html />', errors: [expectedError] , code: '<html {...props} />', errors: [expectedError] , code: '<html lang={undefined} />', errors: [expectedError] ].map parserOptionsMapper
157506
### eslint-env jest ### ###* # @fileoverview Enforce html element has lang prop. # @author <NAME> ### # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- path = require 'path' {RuleTester} = require 'eslint' { default: parserOptionsMapper } = require '../eslint-plugin-jsx-a11y-parser-options-mapper' rule = require 'eslint-plugin-jsx-a11y/lib/rules/html-has-lang' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedError = message: '<html> elements must have the lang prop.' type: 'JSXOpeningElement' ruleTester.run 'html-has-lang', rule, valid: [ code: '<div />' , code: '<html lang="en" />' , code: '<html lang="en-US" />' , code: '<html lang={foo} />' , code: '<html lang />' , code: '<HTML />' ].map parserOptionsMapper invalid: [ code: '<html />', errors: [expectedError] , code: '<html {...props} />', errors: [expectedError] , code: '<html lang={undefined} />', errors: [expectedError] ].map parserOptionsMapper
true
### eslint-env jest ### ###* # @fileoverview Enforce html element has lang prop. # @author PI:NAME:<NAME>END_PI ### # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- path = require 'path' {RuleTester} = require 'eslint' { default: parserOptionsMapper } = require '../eslint-plugin-jsx-a11y-parser-options-mapper' rule = require 'eslint-plugin-jsx-a11y/lib/rules/html-has-lang' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedError = message: '<html> elements must have the lang prop.' type: 'JSXOpeningElement' ruleTester.run 'html-has-lang', rule, valid: [ code: '<div />' , code: '<html lang="en" />' , code: '<html lang="en-US" />' , code: '<html lang={foo} />' , code: '<html lang />' , code: '<HTML />' ].map parserOptionsMapper invalid: [ code: '<html />', errors: [expectedError] , code: '<html {...props} />', errors: [expectedError] , code: '<html lang={undefined} />', errors: [expectedError] ].map parserOptionsMapper
[ { "context": "just showing the html description.\n#\n# Author:\n# brianmichel\n\nexec = require('child_process').exec\n\nuser = pro", "end": 541, "score": 0.9994847774505615, "start": 530, "tag": "USERNAME", "value": "brianmichel" }, { "context": "ec\n\nuser = process.env.HUBOT_RAL...
src/scripts/rally.coffee
contolini/hubot-scripts
1,450
# Description: # Rally information for artifacts # # Dependencies: # None # # Configuration: # HUBOT_RALLY_USERNAME # HUBOT_RALLY_PASSWORD # # Commands: # hubot rally me <formattedID> - Lookup a task, story, defect, etc. from Rally # # Notes: # Since Rally supports rich text for description fields, it will come back as HTML # to pretty print this we can run it through lynx. Make sure you have lynx installed # and PATH accessible, otherwise we will degrade to just showing the html description. # # Author: # brianmichel exec = require('child_process').exec user = process.env.HUBOT_RALLY_USERNAME pass = process.env.HUBOT_RALLY_PASSWORD api_version = 'v2.0' logger = null typeInfoByPrefix = DE: name: 'defect' extraOutputFields: [ 'State' 'ScheduleState' 'Severity' ] DS: name: 'defectsuite' extraOutputFields: [ 'ScheduleState' ] F: name: 'feature' queryName: 'portfolioitem/feature' linkName: 'portfolioitem/feature' extraOutputFields: [ 'State._refObjectName' 'Parent._refObjectName' ] I: name: 'initiative' queryName: 'portfolioitem/initiative' linkName: 'portfolioitem/initiative' extraOutputFields: [ 'State._refObjectName' 'Parent._refObjectName' ] T: name: 'theme' queryName: 'portfolioitem/theme' linkName: 'portfolioitem/theme' extraOutputFields: [ 'State._refObjectName' 'Parent._refObjectName' ] TA: name: 'task' extraOutputFields: [ 'State' 'WorkProduct._refObjectName' ] TC: name: 'testcase' extraOutputFields: [ 'WorkProduct._refObjectName' 'Type' ] US: name: 'story' queryName: 'hierarchicalrequirement' linkName: 'userstory' extraOutputFields: [ 'ScheduleState' 'Parent._refObjectName' 'Feature._refObjectName' ] module.exports = (robot) -> logger = robot.logger robot.respond /(rally)( me)? ([a-z]+)(\d+)/i, (msg) -> if user && pass idPrefix = msg.match[3].toUpperCase() idNumber = msg.match[4] if typeInfoByPrefix.hasOwnProperty(idPrefix) queryRequest msg, typeInfoByPrefix[idPrefix], idNumber, (string) -> msg.send string else msg.send "Uhh, I don't know that formatted ID prefix" else msg.send 'You need to set HUBOT_RALLY_USERNAME & HUBOT_RALLY_PASSWORD before making requests!' queryRequest = (msg, typeInfo, idNumber, cb) -> queryName = typeInfo.queryName || typeInfo.name queryString = "/#{queryName}.js?query=(FormattedID = #{idNumber})&fetch=true" rallyRequest msg, queryString, (json) -> if json && json.QueryResult.TotalResultCount > 0 result = json.QueryResult.Results[0] linkName = typeInfo.linkName || typeInfo.name getLinkToItem msg, result, linkName description = 'No Description' prettifyDescription result.Description, (output) -> description = output || description returnArray = [ "#{result.FormattedID} - #{result.Name}" labeledField(result, 'Owner._refObjectName') labeledField(result, 'Project._refObjectName') ] returnArray.push(labeledField(result, field)) for field in typeInfo.extraOutputFields returnArray.push("Description:") returnArray.push("#{description}") cb returnArray.join("\n") else cb "Aww snap, I couldn't find that #{typeInfo.name}!" labeledField = (result, field) -> match = field.match(/^(\w+)\._refObjectName$/) if match "#{match[1]}: #{refObjectName(result, match[1])}" else "#{field}: #{result[field]}" refObjectName = (result, field) -> if result[field] then result[field]._refObjectName else "No #{field}" rallyRequest = (msg, query, cb) -> rally_url = 'https://rally1.rallydev.com/slm/webservice/' + api_version + query # logger.debug "rally_url = #{rally_url}" basicAuthRequest msg, rally_url, (json) -> # if json # logger.debug "json = #{JSON.stringify(json)}" cb json basicAuthRequest = (msg, url, cb) -> auth = 'Basic ' + new Buffer(user + ':' + pass).toString('base64'); msg.http(url) .headers(Authorization: auth, Accept: 'application/json') .get() (err, res, body) -> json_body = null switch res.statusCode when 200 then json_body = JSON.parse(body) else json_body = null cb json_body getLinkToItem = (msg, object, type) -> project = if object && object.Project then object.Project else null if project objectId = object.ObjectID jsPos = project._ref.lastIndexOf '.js' lastSlashPos = project._ref.lastIndexOf '/' projectId = project._ref[(lastSlashPos+1)..(jsPos)] msg.send "https://rally1.rallydev.com/#/#{projectId}/detail/#{type}/#{objectId}" else #do nothing stripHtml = (html, cb) -> return_text = html.replace(/<style.+\/style>/g, '') return_text = return_text.replace(/<br ?\/?>/g, "\n\n").replace(/&nbsp;/g, ' ').replace(/[ ]+/g, ' ').replace(/%22/g, '"').replace(/&amp;/g, '&').replace(/<\/?.+?>/g, '') return_text = return_text.replace(/&gt;/g, '>').replace(/&lt;/g, '<') cb return_text prettifyDescription = (html_description, cb) -> child = exec "echo \"#{html_description}\" | lynx -dump -stdin", (error, stdout, stderr) -> return_text = html_description if !error return_text = stdout else stripHtml return_text, (cleaned) -> return_text = cleaned cb return_text
168741
# Description: # Rally information for artifacts # # Dependencies: # None # # Configuration: # HUBOT_RALLY_USERNAME # HUBOT_RALLY_PASSWORD # # Commands: # hubot rally me <formattedID> - Lookup a task, story, defect, etc. from Rally # # Notes: # Since Rally supports rich text for description fields, it will come back as HTML # to pretty print this we can run it through lynx. Make sure you have lynx installed # and PATH accessible, otherwise we will degrade to just showing the html description. # # Author: # brianmichel exec = require('child_process').exec user = process.env.HUBOT_RALLY_USERNAME pass = <PASSWORD>.HUB<PASSWORD>ALLY_<PASSWORD> api_version = 'v2.0' logger = null typeInfoByPrefix = DE: name: 'defect' extraOutputFields: [ 'State' 'ScheduleState' 'Severity' ] DS: name: 'defectsuite' extraOutputFields: [ 'ScheduleState' ] F: name: 'feature' queryName: 'portfolioitem/feature' linkName: 'portfolioitem/feature' extraOutputFields: [ 'State._refObjectName' 'Parent._refObjectName' ] I: name: 'initiative' queryName: 'portfolioitem/initiative' linkName: 'portfolioitem/initiative' extraOutputFields: [ 'State._refObjectName' 'Parent._refObjectName' ] T: name: 'theme' queryName: 'portfolioitem/theme' linkName: 'portfolioitem/theme' extraOutputFields: [ 'State._refObjectName' 'Parent._refObjectName' ] TA: name: 'task' extraOutputFields: [ 'State' 'WorkProduct._refObjectName' ] TC: name: 'testcase' extraOutputFields: [ 'WorkProduct._refObjectName' 'Type' ] US: name: 'story' queryName: 'hierarchicalrequirement' linkName: 'userstory' extraOutputFields: [ 'ScheduleState' 'Parent._refObjectName' 'Feature._refObjectName' ] module.exports = (robot) -> logger = robot.logger robot.respond /(rally)( me)? ([a-z]+)(\d+)/i, (msg) -> if user && pass idPrefix = msg.match[3].toUpperCase() idNumber = msg.match[4] if typeInfoByPrefix.hasOwnProperty(idPrefix) queryRequest msg, typeInfoByPrefix[idPrefix], idNumber, (string) -> msg.send string else msg.send "Uhh, I don't know that formatted ID prefix" else msg.send 'You need to set HUBOT_RALLY_USERNAME & HUBOT_RALLY_PASSWORD before making requests!' queryRequest = (msg, typeInfo, idNumber, cb) -> queryName = typeInfo.queryName || typeInfo.name queryString = "/#{queryName}.js?query=(FormattedID = #{idNumber})&fetch=true" rallyRequest msg, queryString, (json) -> if json && json.QueryResult.TotalResultCount > 0 result = json.QueryResult.Results[0] linkName = typeInfo.linkName || typeInfo.name getLinkToItem msg, result, linkName description = 'No Description' prettifyDescription result.Description, (output) -> description = output || description returnArray = [ "#{result.FormattedID} - #{result.Name}" labeledField(result, 'Owner._refObjectName') labeledField(result, 'Project._refObjectName') ] returnArray.push(labeledField(result, field)) for field in typeInfo.extraOutputFields returnArray.push("Description:") returnArray.push("#{description}") cb returnArray.join("\n") else cb "Aww snap, I couldn't find that #{typeInfo.name}!" labeledField = (result, field) -> match = field.match(/^(\w+)\._refObjectName$/) if match "#{match[1]}: #{refObjectName(result, match[1])}" else "#{field}: #{result[field]}" refObjectName = (result, field) -> if result[field] then result[field]._refObjectName else "No #{field}" rallyRequest = (msg, query, cb) -> rally_url = 'https://rally1.rallydev.com/slm/webservice/' + api_version + query # logger.debug "rally_url = #{rally_url}" basicAuthRequest msg, rally_url, (json) -> # if json # logger.debug "json = #{JSON.stringify(json)}" cb json basicAuthRequest = (msg, url, cb) -> auth = 'Basic ' + new Buffer(user + ':' + pass).toString('base64'); msg.http(url) .headers(Authorization: auth, Accept: 'application/json') .get() (err, res, body) -> json_body = null switch res.statusCode when 200 then json_body = JSON.parse(body) else json_body = null cb json_body getLinkToItem = (msg, object, type) -> project = if object && object.Project then object.Project else null if project objectId = object.ObjectID jsPos = project._ref.lastIndexOf '.js' lastSlashPos = project._ref.lastIndexOf '/' projectId = project._ref[(lastSlashPos+1)..(jsPos)] msg.send "https://rally1.rallydev.com/#/#{projectId}/detail/#{type}/#{objectId}" else #do nothing stripHtml = (html, cb) -> return_text = html.replace(/<style.+\/style>/g, '') return_text = return_text.replace(/<br ?\/?>/g, "\n\n").replace(/&nbsp;/g, ' ').replace(/[ ]+/g, ' ').replace(/%22/g, '"').replace(/&amp;/g, '&').replace(/<\/?.+?>/g, '') return_text = return_text.replace(/&gt;/g, '>').replace(/&lt;/g, '<') cb return_text prettifyDescription = (html_description, cb) -> child = exec "echo \"#{html_description}\" | lynx -dump -stdin", (error, stdout, stderr) -> return_text = html_description if !error return_text = stdout else stripHtml return_text, (cleaned) -> return_text = cleaned cb return_text
true
# Description: # Rally information for artifacts # # Dependencies: # None # # Configuration: # HUBOT_RALLY_USERNAME # HUBOT_RALLY_PASSWORD # # Commands: # hubot rally me <formattedID> - Lookup a task, story, defect, etc. from Rally # # Notes: # Since Rally supports rich text for description fields, it will come back as HTML # to pretty print this we can run it through lynx. Make sure you have lynx installed # and PATH accessible, otherwise we will degrade to just showing the html description. # # Author: # brianmichel exec = require('child_process').exec user = process.env.HUBOT_RALLY_USERNAME pass = PI:PASSWORD:<PASSWORD>END_PI.HUBPI:PASSWORD:<PASSWORD>END_PIALLY_PI:PASSWORD:<PASSWORD>END_PI api_version = 'v2.0' logger = null typeInfoByPrefix = DE: name: 'defect' extraOutputFields: [ 'State' 'ScheduleState' 'Severity' ] DS: name: 'defectsuite' extraOutputFields: [ 'ScheduleState' ] F: name: 'feature' queryName: 'portfolioitem/feature' linkName: 'portfolioitem/feature' extraOutputFields: [ 'State._refObjectName' 'Parent._refObjectName' ] I: name: 'initiative' queryName: 'portfolioitem/initiative' linkName: 'portfolioitem/initiative' extraOutputFields: [ 'State._refObjectName' 'Parent._refObjectName' ] T: name: 'theme' queryName: 'portfolioitem/theme' linkName: 'portfolioitem/theme' extraOutputFields: [ 'State._refObjectName' 'Parent._refObjectName' ] TA: name: 'task' extraOutputFields: [ 'State' 'WorkProduct._refObjectName' ] TC: name: 'testcase' extraOutputFields: [ 'WorkProduct._refObjectName' 'Type' ] US: name: 'story' queryName: 'hierarchicalrequirement' linkName: 'userstory' extraOutputFields: [ 'ScheduleState' 'Parent._refObjectName' 'Feature._refObjectName' ] module.exports = (robot) -> logger = robot.logger robot.respond /(rally)( me)? ([a-z]+)(\d+)/i, (msg) -> if user && pass idPrefix = msg.match[3].toUpperCase() idNumber = msg.match[4] if typeInfoByPrefix.hasOwnProperty(idPrefix) queryRequest msg, typeInfoByPrefix[idPrefix], idNumber, (string) -> msg.send string else msg.send "Uhh, I don't know that formatted ID prefix" else msg.send 'You need to set HUBOT_RALLY_USERNAME & HUBOT_RALLY_PASSWORD before making requests!' queryRequest = (msg, typeInfo, idNumber, cb) -> queryName = typeInfo.queryName || typeInfo.name queryString = "/#{queryName}.js?query=(FormattedID = #{idNumber})&fetch=true" rallyRequest msg, queryString, (json) -> if json && json.QueryResult.TotalResultCount > 0 result = json.QueryResult.Results[0] linkName = typeInfo.linkName || typeInfo.name getLinkToItem msg, result, linkName description = 'No Description' prettifyDescription result.Description, (output) -> description = output || description returnArray = [ "#{result.FormattedID} - #{result.Name}" labeledField(result, 'Owner._refObjectName') labeledField(result, 'Project._refObjectName') ] returnArray.push(labeledField(result, field)) for field in typeInfo.extraOutputFields returnArray.push("Description:") returnArray.push("#{description}") cb returnArray.join("\n") else cb "Aww snap, I couldn't find that #{typeInfo.name}!" labeledField = (result, field) -> match = field.match(/^(\w+)\._refObjectName$/) if match "#{match[1]}: #{refObjectName(result, match[1])}" else "#{field}: #{result[field]}" refObjectName = (result, field) -> if result[field] then result[field]._refObjectName else "No #{field}" rallyRequest = (msg, query, cb) -> rally_url = 'https://rally1.rallydev.com/slm/webservice/' + api_version + query # logger.debug "rally_url = #{rally_url}" basicAuthRequest msg, rally_url, (json) -> # if json # logger.debug "json = #{JSON.stringify(json)}" cb json basicAuthRequest = (msg, url, cb) -> auth = 'Basic ' + new Buffer(user + ':' + pass).toString('base64'); msg.http(url) .headers(Authorization: auth, Accept: 'application/json') .get() (err, res, body) -> json_body = null switch res.statusCode when 200 then json_body = JSON.parse(body) else json_body = null cb json_body getLinkToItem = (msg, object, type) -> project = if object && object.Project then object.Project else null if project objectId = object.ObjectID jsPos = project._ref.lastIndexOf '.js' lastSlashPos = project._ref.lastIndexOf '/' projectId = project._ref[(lastSlashPos+1)..(jsPos)] msg.send "https://rally1.rallydev.com/#/#{projectId}/detail/#{type}/#{objectId}" else #do nothing stripHtml = (html, cb) -> return_text = html.replace(/<style.+\/style>/g, '') return_text = return_text.replace(/<br ?\/?>/g, "\n\n").replace(/&nbsp;/g, ' ').replace(/[ ]+/g, ' ').replace(/%22/g, '"').replace(/&amp;/g, '&').replace(/<\/?.+?>/g, '') return_text = return_text.replace(/&gt;/g, '>').replace(/&lt;/g, '<') cb return_text prettifyDescription = (html_description, cb) -> child = exec "echo \"#{html_description}\" | lynx -dump -stdin", (error, stdout, stderr) -> return_text = html_description if !error return_text = stdout else stripHtml return_text, (cleaned) -> return_text = cleaned cb return_text