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": "til\n\n The MIT License (MIT)\n\n Copyright (c) 2014 Yasuhiro Okuno\n\n Permission is hereby granted, free of charge, ", "end": 88, "score": 0.9998644590377808, "start": 74, "tag": "NAME", "value": "Yasuhiro Okuno" } ]
coffee_lib/crowdutil/subcmd/cmdlist.coffee
koma75/crowdutil
1
### @license crowdutil The MIT License (MIT) Copyright (c) 2014 Yasuhiro Okuno 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. ### # # Operetta implementation # defaultOpts = (cmd) -> cmd.parameters(['-c', '--config'], "config file to use [optional]") cmd.parameters(['-D', '--directory'], "target directory [optional]") cmd.options(['-v', '--verbose'], "verbose mode") return # callback(opts): common initialization function. connects to crowd # to add a new command, use the following snippet: # # operetta.command( # 'command-name', # 'command description', # (cmd) -> # cmd # .banner = "crowdutil: command-name\n" + # "command description.\n\n" # defaultOpts(cmd) # add default set of flags(-D and -v) # cmd.parameters(['-p','--param'], # "parameter flag which takes input") # cmd.options(['-o','--option'], # "options flag which takes no input") # cmd.start( # (opts) -> # if callback(opts) # require('./command-name').run(opts) # else # logger.error 'initialization failed' # return # ) # return # ) # # change the command-name, command description and the parameters/options. # leave everything else intact!! start = (callback) -> Operetta = require('operetta').Operetta operetta = new Operetta() # TEST COMMAND operetta.command( 'test-connect', 'test connection to selected Directory', (cmd) -> cmd .banner = "crowdutil: test-connect\n" + "test connection to selected directory.\n\n" defaultOpts(cmd) cmd.start( (opts) -> if callback(opts) require('./test-connection').run(opts) else logger.error 'initialization failed' return ) return ) # CREATE USER operetta.command( 'create-user', 'create user in selected Directory', (cmd) -> cmd .banner = "crowdutil: create-user\n" + "create user in selected directory\n\n" defaultOpts(cmd) cmd.parameters(['-f','--first'], "user's first name") cmd.parameters(['-l','--last'], "user's last name") cmd.parameters(['-d','--dispname'], "user's display name [optional]") cmd.parameters(['-e','--email'], "user's email address") cmd.parameters(['-u','--uid'], "user's login ID") cmd.parameters(['-p','--pass'], "user's password [optional]") cmd.start( (opts) -> if callback(opts) require('./create-user').run(opts) else logger.error 'initialization failed' return ) return ) # SEARCH USER operetta.command( 'search-user', 'search user in selected Directory', (cmd) -> cmd .banner = "crowdutil: search-user\n" + "search user in selected directory\n\n" defaultOpts(cmd) cmd.parameters(['-f','--first'], "user's first name") cmd.parameters(['-l','--last'], "user's last name") cmd.parameters(['-e','--email'], "user's email address") cmd.parameters(['-u','--uid'], "user's login ID") cmd.start( (opts) -> if callback(opts) require('./search-user').run(opts) else logger.error 'initialization failed' return ) return ) # UPDATE USER operetta.command( 'update-user', 'update user in selected Directory', (cmd) -> cmd .banner = "crowdutil: update-user\n" + "update user in selected directory\n\n" defaultOpts(cmd) cmd.parameters(['-f','--first'], "user's first name [optional]") cmd.parameters(['-l','--last'], "user's last name [optional]") cmd.parameters(['-d','--dispname'], "user's display name [optional]") cmd.parameters(['-e','--email'], "user's email address [optional]") cmd.parameters(['-u','--uid'], "target user ID to update") cmd.parameters(['-a','--active'], "user's account active status (true|false)[optional]") cmd.start( (opts) -> if callback(opts) require('./update-user').run(opts) else logger.error 'initialization failed' return ) return ) # CREATE GROUP operetta.command( 'create-group', 'create group in selected Directory', (cmd) -> cmd .banner = "crowdutil: create-group\n" + "create group in selected directory.\n\n" defaultOpts(cmd) cmd.parameters(['-n','--name'], "group name") cmd.parameters(['-d','--desc'], "description of the group") cmd.start( (opts) -> if callback(opts) require('./create-group').run(opts) else logger.error 'initialization failed' return ) return ) # ADD USERS TO GROUPS operetta.command( 'add-to-groups', 'add users to groups', (cmd) -> cmd .banner = "crowdutil: add-to-groups\n" + "add list of users to list of groups.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "comma separated list of groups to add users to") cmd.parameters(['-u','--uid'], "comma separated list of users to add to groups") cmd.start( (opts) -> if callback(opts) require('./add-to-groups').run(opts) else logger.error 'initialization failed' return ) return ) # LIST GROUP MEMBERS operetta.command( 'list-group', 'list group membership of a user', (cmd) -> cmd .banner = "crowdutil: list-group\n" + "list group membership of a user.\n\n" defaultOpts(cmd) cmd.parameters(['-u','--uid'], "uid to find group membership of.") cmd.start( (opts) -> if callback(opts) require('./list-group').run(opts) else logger.error 'initialization failed' return ) return ) # LIST GROUP MEMBERS operetta.command( 'list-member', 'list members of the group', (cmd) -> cmd .banner = "crowdutil: list-member\n" + "list members of the specified group.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "group to find members of.") cmd.start( (opts) -> if callback(opts) require('./list-member').run(opts) else logger.error 'initialization failed' return ) return ) # CHECK MEMBERSIHP OF USERS IN GROUPS operetta.command( 'is-member', 'check membership of users in groups', (cmd) -> cmd .banner = "crowdutil: is-member\n" + "check membership of users in groups.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "comma separated list of groups") cmd.parameters(['-u','--uid'], "comma separated list of users") cmd.start( (opts) -> if callback(opts) require('./is-member').run(opts) else logger.error 'initialization failed' return ) return ) # REMOVE USERS FROM GROUPS operetta.command( 'rm-from-groups', 'remove users from groups', (cmd) -> cmd .banner = "crowdutil: rm-from-groups\n" + "remove list of users from list of groups.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "comma separated list of groups to remove users from") cmd.parameters(['-u','--uid'], "comma separated list of users to remove from groups") cmd.start( (opts) -> if callback(opts) require('./rm-from-groups').run(opts) else logger.error 'initialization failed' return ) return ) # EMPTY GROUPS operetta.command( 'empty-groups', 'empty the specified group', (cmd) -> cmd .banner = "crowdutil: empty-groups\n" + "remove all direct members from the list of groups.\n" + "If no -f option is supplied, you must answer 'yes' to proceed.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "comma separated list of groups to empty out") cmd.options(['-f','--force'], "force emptying the group") cmd.start( (opts) -> if callback(opts) require('./empty-groups').run(opts) else logger.error 'initialization failed' return ) return ) # BATCH EXECUTE operetta.command( 'batch-exec', 'execute according to batch file', (cmd) -> cmd .banner = "crowdutil: batch-exec\n" + "execute according to given batch file.\n\n" defaultOpts(cmd) # add default set of flags(-D and -v) cmd.parameters(['-b','--batch'], "path to the batch file to execute") cmd.options(['-f','--force'], "ignore errors and continue processing the batch") cmd.start( (opts) -> if callback(opts) require('./batch-exec').run(opts) else logger.error 'initialization failed' return ) return ) # INIT CONFIG operetta.command( 'create-config', 'create a sample config file', (cmd) -> cmd .banner = "crowdutil: create-config\n" + "create a sample config file.\n\n" cmd.parameters(['-o','--out'], "output filename (default to $HOME/.crowdutil/config.json). stdout to print") cmd.options(['-f','--force'], "force overwriting file.") cmd.start( (opts) -> require('./create-config').run(opts) return ) return ) operetta .banner = "crowdutil. Atlassian Crowd utility command line tool\n\n" operetta.options( ['-V','--version'], "display version info" ) operetta.on( '-V', (value) -> pjson = require '../../../package.json' console.log pjson.name + " version " + pjson.version return ) operetta.start() return exports.start = start
210806
### @license crowdutil The MIT License (MIT) Copyright (c) 2014 <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. ### # # Operetta implementation # defaultOpts = (cmd) -> cmd.parameters(['-c', '--config'], "config file to use [optional]") cmd.parameters(['-D', '--directory'], "target directory [optional]") cmd.options(['-v', '--verbose'], "verbose mode") return # callback(opts): common initialization function. connects to crowd # to add a new command, use the following snippet: # # operetta.command( # 'command-name', # 'command description', # (cmd) -> # cmd # .banner = "crowdutil: command-name\n" + # "command description.\n\n" # defaultOpts(cmd) # add default set of flags(-D and -v) # cmd.parameters(['-p','--param'], # "parameter flag which takes input") # cmd.options(['-o','--option'], # "options flag which takes no input") # cmd.start( # (opts) -> # if callback(opts) # require('./command-name').run(opts) # else # logger.error 'initialization failed' # return # ) # return # ) # # change the command-name, command description and the parameters/options. # leave everything else intact!! start = (callback) -> Operetta = require('operetta').Operetta operetta = new Operetta() # TEST COMMAND operetta.command( 'test-connect', 'test connection to selected Directory', (cmd) -> cmd .banner = "crowdutil: test-connect\n" + "test connection to selected directory.\n\n" defaultOpts(cmd) cmd.start( (opts) -> if callback(opts) require('./test-connection').run(opts) else logger.error 'initialization failed' return ) return ) # CREATE USER operetta.command( 'create-user', 'create user in selected Directory', (cmd) -> cmd .banner = "crowdutil: create-user\n" + "create user in selected directory\n\n" defaultOpts(cmd) cmd.parameters(['-f','--first'], "user's first name") cmd.parameters(['-l','--last'], "user's last name") cmd.parameters(['-d','--dispname'], "user's display name [optional]") cmd.parameters(['-e','--email'], "user's email address") cmd.parameters(['-u','--uid'], "user's login ID") cmd.parameters(['-p','--pass'], "user's password [optional]") cmd.start( (opts) -> if callback(opts) require('./create-user').run(opts) else logger.error 'initialization failed' return ) return ) # SEARCH USER operetta.command( 'search-user', 'search user in selected Directory', (cmd) -> cmd .banner = "crowdutil: search-user\n" + "search user in selected directory\n\n" defaultOpts(cmd) cmd.parameters(['-f','--first'], "user's first name") cmd.parameters(['-l','--last'], "user's last name") cmd.parameters(['-e','--email'], "user's email address") cmd.parameters(['-u','--uid'], "user's login ID") cmd.start( (opts) -> if callback(opts) require('./search-user').run(opts) else logger.error 'initialization failed' return ) return ) # UPDATE USER operetta.command( 'update-user', 'update user in selected Directory', (cmd) -> cmd .banner = "crowdutil: update-user\n" + "update user in selected directory\n\n" defaultOpts(cmd) cmd.parameters(['-f','--first'], "user's first name [optional]") cmd.parameters(['-l','--last'], "user's last name [optional]") cmd.parameters(['-d','--dispname'], "user's display name [optional]") cmd.parameters(['-e','--email'], "user's email address [optional]") cmd.parameters(['-u','--uid'], "target user ID to update") cmd.parameters(['-a','--active'], "user's account active status (true|false)[optional]") cmd.start( (opts) -> if callback(opts) require('./update-user').run(opts) else logger.error 'initialization failed' return ) return ) # CREATE GROUP operetta.command( 'create-group', 'create group in selected Directory', (cmd) -> cmd .banner = "crowdutil: create-group\n" + "create group in selected directory.\n\n" defaultOpts(cmd) cmd.parameters(['-n','--name'], "group name") cmd.parameters(['-d','--desc'], "description of the group") cmd.start( (opts) -> if callback(opts) require('./create-group').run(opts) else logger.error 'initialization failed' return ) return ) # ADD USERS TO GROUPS operetta.command( 'add-to-groups', 'add users to groups', (cmd) -> cmd .banner = "crowdutil: add-to-groups\n" + "add list of users to list of groups.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "comma separated list of groups to add users to") cmd.parameters(['-u','--uid'], "comma separated list of users to add to groups") cmd.start( (opts) -> if callback(opts) require('./add-to-groups').run(opts) else logger.error 'initialization failed' return ) return ) # LIST GROUP MEMBERS operetta.command( 'list-group', 'list group membership of a user', (cmd) -> cmd .banner = "crowdutil: list-group\n" + "list group membership of a user.\n\n" defaultOpts(cmd) cmd.parameters(['-u','--uid'], "uid to find group membership of.") cmd.start( (opts) -> if callback(opts) require('./list-group').run(opts) else logger.error 'initialization failed' return ) return ) # LIST GROUP MEMBERS operetta.command( 'list-member', 'list members of the group', (cmd) -> cmd .banner = "crowdutil: list-member\n" + "list members of the specified group.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "group to find members of.") cmd.start( (opts) -> if callback(opts) require('./list-member').run(opts) else logger.error 'initialization failed' return ) return ) # CHECK MEMBERSIHP OF USERS IN GROUPS operetta.command( 'is-member', 'check membership of users in groups', (cmd) -> cmd .banner = "crowdutil: is-member\n" + "check membership of users in groups.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "comma separated list of groups") cmd.parameters(['-u','--uid'], "comma separated list of users") cmd.start( (opts) -> if callback(opts) require('./is-member').run(opts) else logger.error 'initialization failed' return ) return ) # REMOVE USERS FROM GROUPS operetta.command( 'rm-from-groups', 'remove users from groups', (cmd) -> cmd .banner = "crowdutil: rm-from-groups\n" + "remove list of users from list of groups.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "comma separated list of groups to remove users from") cmd.parameters(['-u','--uid'], "comma separated list of users to remove from groups") cmd.start( (opts) -> if callback(opts) require('./rm-from-groups').run(opts) else logger.error 'initialization failed' return ) return ) # EMPTY GROUPS operetta.command( 'empty-groups', 'empty the specified group', (cmd) -> cmd .banner = "crowdutil: empty-groups\n" + "remove all direct members from the list of groups.\n" + "If no -f option is supplied, you must answer 'yes' to proceed.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "comma separated list of groups to empty out") cmd.options(['-f','--force'], "force emptying the group") cmd.start( (opts) -> if callback(opts) require('./empty-groups').run(opts) else logger.error 'initialization failed' return ) return ) # BATCH EXECUTE operetta.command( 'batch-exec', 'execute according to batch file', (cmd) -> cmd .banner = "crowdutil: batch-exec\n" + "execute according to given batch file.\n\n" defaultOpts(cmd) # add default set of flags(-D and -v) cmd.parameters(['-b','--batch'], "path to the batch file to execute") cmd.options(['-f','--force'], "ignore errors and continue processing the batch") cmd.start( (opts) -> if callback(opts) require('./batch-exec').run(opts) else logger.error 'initialization failed' return ) return ) # INIT CONFIG operetta.command( 'create-config', 'create a sample config file', (cmd) -> cmd .banner = "crowdutil: create-config\n" + "create a sample config file.\n\n" cmd.parameters(['-o','--out'], "output filename (default to $HOME/.crowdutil/config.json). stdout to print") cmd.options(['-f','--force'], "force overwriting file.") cmd.start( (opts) -> require('./create-config').run(opts) return ) return ) operetta .banner = "crowdutil. Atlassian Crowd utility command line tool\n\n" operetta.options( ['-V','--version'], "display version info" ) operetta.on( '-V', (value) -> pjson = require '../../../package.json' console.log pjson.name + " version " + pjson.version return ) operetta.start() return exports.start = start
true
### @license crowdutil The MIT License (MIT) Copyright (c) 2014 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. ### # # Operetta implementation # defaultOpts = (cmd) -> cmd.parameters(['-c', '--config'], "config file to use [optional]") cmd.parameters(['-D', '--directory'], "target directory [optional]") cmd.options(['-v', '--verbose'], "verbose mode") return # callback(opts): common initialization function. connects to crowd # to add a new command, use the following snippet: # # operetta.command( # 'command-name', # 'command description', # (cmd) -> # cmd # .banner = "crowdutil: command-name\n" + # "command description.\n\n" # defaultOpts(cmd) # add default set of flags(-D and -v) # cmd.parameters(['-p','--param'], # "parameter flag which takes input") # cmd.options(['-o','--option'], # "options flag which takes no input") # cmd.start( # (opts) -> # if callback(opts) # require('./command-name').run(opts) # else # logger.error 'initialization failed' # return # ) # return # ) # # change the command-name, command description and the parameters/options. # leave everything else intact!! start = (callback) -> Operetta = require('operetta').Operetta operetta = new Operetta() # TEST COMMAND operetta.command( 'test-connect', 'test connection to selected Directory', (cmd) -> cmd .banner = "crowdutil: test-connect\n" + "test connection to selected directory.\n\n" defaultOpts(cmd) cmd.start( (opts) -> if callback(opts) require('./test-connection').run(opts) else logger.error 'initialization failed' return ) return ) # CREATE USER operetta.command( 'create-user', 'create user in selected Directory', (cmd) -> cmd .banner = "crowdutil: create-user\n" + "create user in selected directory\n\n" defaultOpts(cmd) cmd.parameters(['-f','--first'], "user's first name") cmd.parameters(['-l','--last'], "user's last name") cmd.parameters(['-d','--dispname'], "user's display name [optional]") cmd.parameters(['-e','--email'], "user's email address") cmd.parameters(['-u','--uid'], "user's login ID") cmd.parameters(['-p','--pass'], "user's password [optional]") cmd.start( (opts) -> if callback(opts) require('./create-user').run(opts) else logger.error 'initialization failed' return ) return ) # SEARCH USER operetta.command( 'search-user', 'search user in selected Directory', (cmd) -> cmd .banner = "crowdutil: search-user\n" + "search user in selected directory\n\n" defaultOpts(cmd) cmd.parameters(['-f','--first'], "user's first name") cmd.parameters(['-l','--last'], "user's last name") cmd.parameters(['-e','--email'], "user's email address") cmd.parameters(['-u','--uid'], "user's login ID") cmd.start( (opts) -> if callback(opts) require('./search-user').run(opts) else logger.error 'initialization failed' return ) return ) # UPDATE USER operetta.command( 'update-user', 'update user in selected Directory', (cmd) -> cmd .banner = "crowdutil: update-user\n" + "update user in selected directory\n\n" defaultOpts(cmd) cmd.parameters(['-f','--first'], "user's first name [optional]") cmd.parameters(['-l','--last'], "user's last name [optional]") cmd.parameters(['-d','--dispname'], "user's display name [optional]") cmd.parameters(['-e','--email'], "user's email address [optional]") cmd.parameters(['-u','--uid'], "target user ID to update") cmd.parameters(['-a','--active'], "user's account active status (true|false)[optional]") cmd.start( (opts) -> if callback(opts) require('./update-user').run(opts) else logger.error 'initialization failed' return ) return ) # CREATE GROUP operetta.command( 'create-group', 'create group in selected Directory', (cmd) -> cmd .banner = "crowdutil: create-group\n" + "create group in selected directory.\n\n" defaultOpts(cmd) cmd.parameters(['-n','--name'], "group name") cmd.parameters(['-d','--desc'], "description of the group") cmd.start( (opts) -> if callback(opts) require('./create-group').run(opts) else logger.error 'initialization failed' return ) return ) # ADD USERS TO GROUPS operetta.command( 'add-to-groups', 'add users to groups', (cmd) -> cmd .banner = "crowdutil: add-to-groups\n" + "add list of users to list of groups.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "comma separated list of groups to add users to") cmd.parameters(['-u','--uid'], "comma separated list of users to add to groups") cmd.start( (opts) -> if callback(opts) require('./add-to-groups').run(opts) else logger.error 'initialization failed' return ) return ) # LIST GROUP MEMBERS operetta.command( 'list-group', 'list group membership of a user', (cmd) -> cmd .banner = "crowdutil: list-group\n" + "list group membership of a user.\n\n" defaultOpts(cmd) cmd.parameters(['-u','--uid'], "uid to find group membership of.") cmd.start( (opts) -> if callback(opts) require('./list-group').run(opts) else logger.error 'initialization failed' return ) return ) # LIST GROUP MEMBERS operetta.command( 'list-member', 'list members of the group', (cmd) -> cmd .banner = "crowdutil: list-member\n" + "list members of the specified group.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "group to find members of.") cmd.start( (opts) -> if callback(opts) require('./list-member').run(opts) else logger.error 'initialization failed' return ) return ) # CHECK MEMBERSIHP OF USERS IN GROUPS operetta.command( 'is-member', 'check membership of users in groups', (cmd) -> cmd .banner = "crowdutil: is-member\n" + "check membership of users in groups.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "comma separated list of groups") cmd.parameters(['-u','--uid'], "comma separated list of users") cmd.start( (opts) -> if callback(opts) require('./is-member').run(opts) else logger.error 'initialization failed' return ) return ) # REMOVE USERS FROM GROUPS operetta.command( 'rm-from-groups', 'remove users from groups', (cmd) -> cmd .banner = "crowdutil: rm-from-groups\n" + "remove list of users from list of groups.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "comma separated list of groups to remove users from") cmd.parameters(['-u','--uid'], "comma separated list of users to remove from groups") cmd.start( (opts) -> if callback(opts) require('./rm-from-groups').run(opts) else logger.error 'initialization failed' return ) return ) # EMPTY GROUPS operetta.command( 'empty-groups', 'empty the specified group', (cmd) -> cmd .banner = "crowdutil: empty-groups\n" + "remove all direct members from the list of groups.\n" + "If no -f option is supplied, you must answer 'yes' to proceed.\n\n" defaultOpts(cmd) cmd.parameters(['-g','--group'], "comma separated list of groups to empty out") cmd.options(['-f','--force'], "force emptying the group") cmd.start( (opts) -> if callback(opts) require('./empty-groups').run(opts) else logger.error 'initialization failed' return ) return ) # BATCH EXECUTE operetta.command( 'batch-exec', 'execute according to batch file', (cmd) -> cmd .banner = "crowdutil: batch-exec\n" + "execute according to given batch file.\n\n" defaultOpts(cmd) # add default set of flags(-D and -v) cmd.parameters(['-b','--batch'], "path to the batch file to execute") cmd.options(['-f','--force'], "ignore errors and continue processing the batch") cmd.start( (opts) -> if callback(opts) require('./batch-exec').run(opts) else logger.error 'initialization failed' return ) return ) # INIT CONFIG operetta.command( 'create-config', 'create a sample config file', (cmd) -> cmd .banner = "crowdutil: create-config\n" + "create a sample config file.\n\n" cmd.parameters(['-o','--out'], "output filename (default to $HOME/.crowdutil/config.json). stdout to print") cmd.options(['-f','--force'], "force overwriting file.") cmd.start( (opts) -> require('./create-config').run(opts) return ) return ) operetta .banner = "crowdutil. Atlassian Crowd utility command line tool\n\n" operetta.options( ['-V','--version'], "display version info" ) operetta.on( '-V', (value) -> pjson = require '../../../package.json' console.log pjson.name + " version " + pjson.version return ) operetta.start() return exports.start = start
[ { "context": "ffee\n# Copyright 2017 9165584 Canada Corporation <legal@fuzzy.ai>\n# All rights reserved.\n\nfs = require 'fs'\npath =", "end": 76, "score": 0.9999081492424011, "start": 62, "tag": "EMAIL", "value": "legal@fuzzy.ai" } ]
src/version.coffee
enterstudio/lemonade-stand
2
# version.coffee # Copyright 2017 9165584 Canada Corporation <legal@fuzzy.ai> # All rights reserved. fs = require 'fs' path = require 'path' pkg = fs.readFileSync path.join(__dirname, '..', 'package.json') data = JSON.parse pkg module.exports = data.version
90055
# version.coffee # Copyright 2017 9165584 Canada Corporation <<EMAIL>> # All rights reserved. fs = require 'fs' path = require 'path' pkg = fs.readFileSync path.join(__dirname, '..', 'package.json') data = JSON.parse pkg module.exports = data.version
true
# version.coffee # Copyright 2017 9165584 Canada Corporation <PI:EMAIL:<EMAIL>END_PI> # All rights reserved. fs = require 'fs' path = require 'path' pkg = fs.readFileSync path.join(__dirname, '..', 'package.json') data = JSON.parse pkg module.exports = data.version
[ { "context": "est\n\n\t\t@stubbedUser = \n\t\t\t_id: \"3131231\"\n\t\t\tname:\"bob\"\n\t\t\temail:\"hello@world.com\"\n\t\t@newEmail = \"bob@bo", "end": 753, "score": 0.596405565738678, "start": 750, "tag": "NAME", "value": "bob" }, { "context": "User = \n\t\t\t_id: \"3131231\"\n\t\t\tname:\"bob\"\n\t\t\temail:\"hello@world.com\"\n\t\t@newEmail = \"bob@bob.com\"\n\n\tdescribe 'getInsti", "end": 780, "score": 0.9999106526374817, "start": 765, "tag": "EMAIL", "value": "hello@world.com" }, { "context": "e:\"bob\"\n\t\t\temail:\"hello@world.com\"\n\t\t@newEmail = \"bob@bob.com\"\n\n\tdescribe 'getInstitutionAffiliations', ->\n\t\tit", "end": 808, "score": 0.9999235272407532, "start": 797, "tag": "EMAIL", "value": "bob@bob.com" } ]
test/unit/coffee/Institutions/InstitutionsAPITests.coffee
shyoshyo/web-sharelatex
1
should = require('chai').should() expect = require('chai').expect SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Institutions/InstitutionsAPI" expect = require("chai").expect describe "InstitutionsAPI", -> beforeEach -> @logger = err: sinon.stub(), log: -> @settings = apis: { v1: { url: 'v1.url', user: '', pass: '' } } @request = sinon.stub() @InstitutionsAPI = SandboxedModule.require modulePath, requires: "logger-sharelatex": @logger "metrics-sharelatex": timeAsyncMethod: sinon.stub() 'settings-sharelatex': @settings 'request': @request @stubbedUser = _id: "3131231" name:"bob" email:"hello@world.com" @newEmail = "bob@bob.com" describe 'getInstitutionAffiliations', -> it 'get affiliations', (done)-> @institutionId = 123 responseBody = ['123abc', '456def'] @request.yields(null, { statusCode: 200 }, responseBody) @InstitutionsAPI.getInstitutionAffiliations @institutionId, (err, body) => should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/institutions/#{@institutionId}/affiliations" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'GET' should.not.exist(requestOptions.body) body.should.equal responseBody done() it 'handle empty response', (done)-> @settings.apis = null @InstitutionsAPI.getInstitutionAffiliations @institutionId, (err, body) => should.not.exist(err) expect(body).to.be.a 'Array' body.length.should.equal 0 done() describe 'getInstitutionLicences', -> it 'get licences', (done)-> @institutionId = 123 responseBody = {"lag":"monthly","data":[{"key":"users","values":[{"x":"2018-01-01","y":1}]}]} @request.yields(null, { statusCode: 200 }, responseBody) startDate = '1417392000' endDate = '1420848000' @InstitutionsAPI.getInstitutionLicences @institutionId, startDate, endDate, 'monthly', (err, body) => should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/institutions/#{@institutionId}/institution_licences" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'GET' requestOptions.body['start_date'].should.equal startDate requestOptions.body['end_date'].should.equal endDate requestOptions.body.lag.should.equal 'monthly' body.should.equal responseBody done() describe 'getUserAffiliations', -> it 'get affiliations', (done)-> responseBody = [{ foo: 'bar' }] @request.callsArgWith(1, null, { statusCode: 201 }, responseBody) @InstitutionsAPI.getUserAffiliations @stubbedUser._id, (err, body) => should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'GET' should.not.exist(requestOptions.body) body.should.equal responseBody done() it 'handle error', (done)-> body = errors: 'affiliation error message' @request.callsArgWith(1, null, { statusCode: 503 }, body) @InstitutionsAPI.getUserAffiliations @stubbedUser._id, (err) => should.exist(err) err.message.should.have.string 503 err.message.should.have.string body.errors done() it 'handle empty response', (done)-> @settings.apis = null @InstitutionsAPI.getUserAffiliations @stubbedUser._id, (err, body) => should.not.exist(err) expect(body).to.be.a 'Array' body.length.should.equal 0 done() describe 'addAffiliation', -> beforeEach -> @request.callsArgWith(1, null, { statusCode: 201 }) it 'add affiliation', (done)-> affiliationOptions = university: { id: 1 } role: 'Prof' department: 'Math' confirmedAt: new Date() @InstitutionsAPI.addAffiliation @stubbedUser._id, @newEmail, affiliationOptions, (err)=> should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'POST' body = requestOptions.body Object.keys(body).length.should.equal 5 body.email.should.equal @newEmail body.university.should.equal affiliationOptions.university body.department.should.equal affiliationOptions.department body.role.should.equal affiliationOptions.role body.confirmedAt.should.equal affiliationOptions.confirmedAt done() it 'handle error', (done)-> body = errors: 'affiliation error message' @request.callsArgWith(1, null, { statusCode: 422 }, body) @InstitutionsAPI.addAffiliation @stubbedUser._id, @newEmail, {}, (err)=> should.exist(err) err.message.should.have.string 422 err.message.should.have.string body.errors done() describe 'removeAffiliation', -> beforeEach -> @request.callsArgWith(1, null, { statusCode: 404 }) it 'remove affiliation', (done)-> @InstitutionsAPI.removeAffiliation @stubbedUser._id, @newEmail, (err)=> should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations/remove" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'POST' expect(requestOptions.body).to.deep.equal { email: @newEmail } done() it 'handle error', (done)-> @request.callsArgWith(1, null, { statusCode: 500 }) @InstitutionsAPI.removeAffiliation @stubbedUser._id, @newEmail, (err)=> should.exist(err) err.message.should.exist done() describe 'deleteAffiliations', -> it 'delete affiliations', (done)-> @request.callsArgWith(1, null, { statusCode: 200 }) @InstitutionsAPI.deleteAffiliations @stubbedUser._id, (err) => should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'DELETE' done() it 'handle error', (done)-> body = errors: 'affiliation error message' @request.callsArgWith(1, null, { statusCode: 518 }, body) @InstitutionsAPI.deleteAffiliations @stubbedUser._id, (err) => should.exist(err) err.message.should.have.string 518 err.message.should.have.string body.errors done() describe 'endorseAffiliation', -> beforeEach -> @request.callsArgWith(1, null, { statusCode: 204 }) it 'endorse affiliation', (done)-> @InstitutionsAPI.endorseAffiliation @stubbedUser._id, @newEmail, 'Student','Physics', (err)=> should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations/endorse" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'POST' body = requestOptions.body Object.keys(body).length.should.equal 3 body.email.should.equal @newEmail body.role.should.equal 'Student' body.department.should.equal 'Physics' done()
31496
should = require('chai').should() expect = require('chai').expect SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Institutions/InstitutionsAPI" expect = require("chai").expect describe "InstitutionsAPI", -> beforeEach -> @logger = err: sinon.stub(), log: -> @settings = apis: { v1: { url: 'v1.url', user: '', pass: '' } } @request = sinon.stub() @InstitutionsAPI = SandboxedModule.require modulePath, requires: "logger-sharelatex": @logger "metrics-sharelatex": timeAsyncMethod: sinon.stub() 'settings-sharelatex': @settings 'request': @request @stubbedUser = _id: "3131231" name:"<NAME>" email:"<EMAIL>" @newEmail = "<EMAIL>" describe 'getInstitutionAffiliations', -> it 'get affiliations', (done)-> @institutionId = 123 responseBody = ['123abc', '456def'] @request.yields(null, { statusCode: 200 }, responseBody) @InstitutionsAPI.getInstitutionAffiliations @institutionId, (err, body) => should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/institutions/#{@institutionId}/affiliations" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'GET' should.not.exist(requestOptions.body) body.should.equal responseBody done() it 'handle empty response', (done)-> @settings.apis = null @InstitutionsAPI.getInstitutionAffiliations @institutionId, (err, body) => should.not.exist(err) expect(body).to.be.a 'Array' body.length.should.equal 0 done() describe 'getInstitutionLicences', -> it 'get licences', (done)-> @institutionId = 123 responseBody = {"lag":"monthly","data":[{"key":"users","values":[{"x":"2018-01-01","y":1}]}]} @request.yields(null, { statusCode: 200 }, responseBody) startDate = '1417392000' endDate = '1420848000' @InstitutionsAPI.getInstitutionLicences @institutionId, startDate, endDate, 'monthly', (err, body) => should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/institutions/#{@institutionId}/institution_licences" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'GET' requestOptions.body['start_date'].should.equal startDate requestOptions.body['end_date'].should.equal endDate requestOptions.body.lag.should.equal 'monthly' body.should.equal responseBody done() describe 'getUserAffiliations', -> it 'get affiliations', (done)-> responseBody = [{ foo: 'bar' }] @request.callsArgWith(1, null, { statusCode: 201 }, responseBody) @InstitutionsAPI.getUserAffiliations @stubbedUser._id, (err, body) => should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'GET' should.not.exist(requestOptions.body) body.should.equal responseBody done() it 'handle error', (done)-> body = errors: 'affiliation error message' @request.callsArgWith(1, null, { statusCode: 503 }, body) @InstitutionsAPI.getUserAffiliations @stubbedUser._id, (err) => should.exist(err) err.message.should.have.string 503 err.message.should.have.string body.errors done() it 'handle empty response', (done)-> @settings.apis = null @InstitutionsAPI.getUserAffiliations @stubbedUser._id, (err, body) => should.not.exist(err) expect(body).to.be.a 'Array' body.length.should.equal 0 done() describe 'addAffiliation', -> beforeEach -> @request.callsArgWith(1, null, { statusCode: 201 }) it 'add affiliation', (done)-> affiliationOptions = university: { id: 1 } role: 'Prof' department: 'Math' confirmedAt: new Date() @InstitutionsAPI.addAffiliation @stubbedUser._id, @newEmail, affiliationOptions, (err)=> should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'POST' body = requestOptions.body Object.keys(body).length.should.equal 5 body.email.should.equal @newEmail body.university.should.equal affiliationOptions.university body.department.should.equal affiliationOptions.department body.role.should.equal affiliationOptions.role body.confirmedAt.should.equal affiliationOptions.confirmedAt done() it 'handle error', (done)-> body = errors: 'affiliation error message' @request.callsArgWith(1, null, { statusCode: 422 }, body) @InstitutionsAPI.addAffiliation @stubbedUser._id, @newEmail, {}, (err)=> should.exist(err) err.message.should.have.string 422 err.message.should.have.string body.errors done() describe 'removeAffiliation', -> beforeEach -> @request.callsArgWith(1, null, { statusCode: 404 }) it 'remove affiliation', (done)-> @InstitutionsAPI.removeAffiliation @stubbedUser._id, @newEmail, (err)=> should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations/remove" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'POST' expect(requestOptions.body).to.deep.equal { email: @newEmail } done() it 'handle error', (done)-> @request.callsArgWith(1, null, { statusCode: 500 }) @InstitutionsAPI.removeAffiliation @stubbedUser._id, @newEmail, (err)=> should.exist(err) err.message.should.exist done() describe 'deleteAffiliations', -> it 'delete affiliations', (done)-> @request.callsArgWith(1, null, { statusCode: 200 }) @InstitutionsAPI.deleteAffiliations @stubbedUser._id, (err) => should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'DELETE' done() it 'handle error', (done)-> body = errors: 'affiliation error message' @request.callsArgWith(1, null, { statusCode: 518 }, body) @InstitutionsAPI.deleteAffiliations @stubbedUser._id, (err) => should.exist(err) err.message.should.have.string 518 err.message.should.have.string body.errors done() describe 'endorseAffiliation', -> beforeEach -> @request.callsArgWith(1, null, { statusCode: 204 }) it 'endorse affiliation', (done)-> @InstitutionsAPI.endorseAffiliation @stubbedUser._id, @newEmail, 'Student','Physics', (err)=> should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations/endorse" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'POST' body = requestOptions.body Object.keys(body).length.should.equal 3 body.email.should.equal @newEmail body.role.should.equal 'Student' body.department.should.equal 'Physics' done()
true
should = require('chai').should() expect = require('chai').expect SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Institutions/InstitutionsAPI" expect = require("chai").expect describe "InstitutionsAPI", -> beforeEach -> @logger = err: sinon.stub(), log: -> @settings = apis: { v1: { url: 'v1.url', user: '', pass: '' } } @request = sinon.stub() @InstitutionsAPI = SandboxedModule.require modulePath, requires: "logger-sharelatex": @logger "metrics-sharelatex": timeAsyncMethod: sinon.stub() 'settings-sharelatex': @settings 'request': @request @stubbedUser = _id: "3131231" name:"PI:NAME:<NAME>END_PI" email:"PI:EMAIL:<EMAIL>END_PI" @newEmail = "PI:EMAIL:<EMAIL>END_PI" describe 'getInstitutionAffiliations', -> it 'get affiliations', (done)-> @institutionId = 123 responseBody = ['123abc', '456def'] @request.yields(null, { statusCode: 200 }, responseBody) @InstitutionsAPI.getInstitutionAffiliations @institutionId, (err, body) => should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/institutions/#{@institutionId}/affiliations" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'GET' should.not.exist(requestOptions.body) body.should.equal responseBody done() it 'handle empty response', (done)-> @settings.apis = null @InstitutionsAPI.getInstitutionAffiliations @institutionId, (err, body) => should.not.exist(err) expect(body).to.be.a 'Array' body.length.should.equal 0 done() describe 'getInstitutionLicences', -> it 'get licences', (done)-> @institutionId = 123 responseBody = {"lag":"monthly","data":[{"key":"users","values":[{"x":"2018-01-01","y":1}]}]} @request.yields(null, { statusCode: 200 }, responseBody) startDate = '1417392000' endDate = '1420848000' @InstitutionsAPI.getInstitutionLicences @institutionId, startDate, endDate, 'monthly', (err, body) => should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/institutions/#{@institutionId}/institution_licences" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'GET' requestOptions.body['start_date'].should.equal startDate requestOptions.body['end_date'].should.equal endDate requestOptions.body.lag.should.equal 'monthly' body.should.equal responseBody done() describe 'getUserAffiliations', -> it 'get affiliations', (done)-> responseBody = [{ foo: 'bar' }] @request.callsArgWith(1, null, { statusCode: 201 }, responseBody) @InstitutionsAPI.getUserAffiliations @stubbedUser._id, (err, body) => should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'GET' should.not.exist(requestOptions.body) body.should.equal responseBody done() it 'handle error', (done)-> body = errors: 'affiliation error message' @request.callsArgWith(1, null, { statusCode: 503 }, body) @InstitutionsAPI.getUserAffiliations @stubbedUser._id, (err) => should.exist(err) err.message.should.have.string 503 err.message.should.have.string body.errors done() it 'handle empty response', (done)-> @settings.apis = null @InstitutionsAPI.getUserAffiliations @stubbedUser._id, (err, body) => should.not.exist(err) expect(body).to.be.a 'Array' body.length.should.equal 0 done() describe 'addAffiliation', -> beforeEach -> @request.callsArgWith(1, null, { statusCode: 201 }) it 'add affiliation', (done)-> affiliationOptions = university: { id: 1 } role: 'Prof' department: 'Math' confirmedAt: new Date() @InstitutionsAPI.addAffiliation @stubbedUser._id, @newEmail, affiliationOptions, (err)=> should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'POST' body = requestOptions.body Object.keys(body).length.should.equal 5 body.email.should.equal @newEmail body.university.should.equal affiliationOptions.university body.department.should.equal affiliationOptions.department body.role.should.equal affiliationOptions.role body.confirmedAt.should.equal affiliationOptions.confirmedAt done() it 'handle error', (done)-> body = errors: 'affiliation error message' @request.callsArgWith(1, null, { statusCode: 422 }, body) @InstitutionsAPI.addAffiliation @stubbedUser._id, @newEmail, {}, (err)=> should.exist(err) err.message.should.have.string 422 err.message.should.have.string body.errors done() describe 'removeAffiliation', -> beforeEach -> @request.callsArgWith(1, null, { statusCode: 404 }) it 'remove affiliation', (done)-> @InstitutionsAPI.removeAffiliation @stubbedUser._id, @newEmail, (err)=> should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations/remove" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'POST' expect(requestOptions.body).to.deep.equal { email: @newEmail } done() it 'handle error', (done)-> @request.callsArgWith(1, null, { statusCode: 500 }) @InstitutionsAPI.removeAffiliation @stubbedUser._id, @newEmail, (err)=> should.exist(err) err.message.should.exist done() describe 'deleteAffiliations', -> it 'delete affiliations', (done)-> @request.callsArgWith(1, null, { statusCode: 200 }) @InstitutionsAPI.deleteAffiliations @stubbedUser._id, (err) => should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'DELETE' done() it 'handle error', (done)-> body = errors: 'affiliation error message' @request.callsArgWith(1, null, { statusCode: 518 }, body) @InstitutionsAPI.deleteAffiliations @stubbedUser._id, (err) => should.exist(err) err.message.should.have.string 518 err.message.should.have.string body.errors done() describe 'endorseAffiliation', -> beforeEach -> @request.callsArgWith(1, null, { statusCode: 204 }) it 'endorse affiliation', (done)-> @InstitutionsAPI.endorseAffiliation @stubbedUser._id, @newEmail, 'Student','Physics', (err)=> should.not.exist(err) @request.calledOnce.should.equal true requestOptions = @request.lastCall.args[0] expectedUrl = "v1.url/api/v2/users/#{@stubbedUser._id}/affiliations/endorse" requestOptions.url.should.equal expectedUrl requestOptions.method.should.equal 'POST' body = requestOptions.body Object.keys(body).length.should.equal 3 body.email.should.equal @newEmail body.role.should.equal 'Student' body.department.should.equal 'Physics' done()
[ { "context": "th different worker-types\n * @author Valiton GmbH, Bastian \"hereandnow\" Behrens\n###\n\n###*\n * Standard librar", "end": 148, "score": 0.9998211860656738, "start": 141, "tag": "NAME", "value": "Bastian" }, { "context": "nt worker-types\n * @author Valiton GmbH, Bastian \"hereandnow\" Behrens\n###\n\n###*\n * Standard library imports\n##", "end": 160, "score": 0.6795461773872375, "start": 150, "tag": "USERNAME", "value": "hereandnow" }, { "context": "types\n * @author Valiton GmbH, Bastian \"hereandnow\" Behrens\n###\n\n###*\n * Standard library imports\n###\ncluster", "end": 169, "score": 0.9493069648742676, "start": 162, "tag": "NAME", "value": "Behrens" } ]
src/various-cluster.coffee
valiton/node-various-cluster
1
###* * @name various-cluster * @description easily create a mulit-cluster environment with different worker-types * @author Valiton GmbH, Bastian "hereandnow" Behrens ### ###* * Standard library imports ### cluster = require 'cluster' util = require 'util' ###* * 3rd library imports ### prettySeconds = require 'pretty-seconds' _ = require 'lodash' ### * Local imports ### WorkerType = require './worker-type' Worker = require './worker' class VariousCluster _log = (type, msg) -> if typeof process.logger is 'object' return process.logger[type](msg) util.log msg _exit = -> workers = Object.keys(cluster.workers).length if workers is 0 _log.call this, 'notice', util.format('%s with pid %s has no workers remaining, exit after %s uptime', @config.title, process.pid, prettySeconds(process.uptime())) process.exit 0 else if !!process.shuttingDown _log.call this, 'notice', util.format('%s with pid %s waits for %s workers to shutdown', @config.title, process.pid, workers) ###* * initalize the VariousCluster with the given config * * @param {object} config read more about config options in README * @function global.VariousCluster.prototype.init * @returns {this} the current instance for chaining ### init: (@config) -> if cluster.isMaster process.title = @config.title or 'various-cluster-master' cluster.on 'exit', (worker, code, signal) => process.nextTick => _exit.call this process.on 'uncaughtException', (err) => process.shuttingDown = true _log.call this, 'crit', util.format('%s with pid %s had uncaught exception, shutdown all workers: %s', @config.title, process.pid, err.stack) _exit.call this worker.send(type: 'shutmedown') for key, worker of cluster.workers ['SIGINT', 'SIGTERM'].forEach (signal) => process.on signal, => process.shuttingDown = true _log.call this, 'notice', util.format('%s with pid %s received signal %s, shutdown all workers', @config.title, process.pid, signal) _exit.call this worker.send(type: 'shutmedown') for key, worker of cluster.workers for workerConfig in @config.workers defaultWorkerTypeConfig = count: @config.count shutdownTimeout: @config.shutdownTimeout title: 'various-cluster-worker' new WorkerType().init _.defaults(workerConfig, defaultWorkerTypeConfig) else if cluster.isWorker new Worker().init() this module.exports = new VariousCluster()
15594
###* * @name various-cluster * @description easily create a mulit-cluster environment with different worker-types * @author Valiton GmbH, <NAME> "hereandnow" <NAME> ### ###* * Standard library imports ### cluster = require 'cluster' util = require 'util' ###* * 3rd library imports ### prettySeconds = require 'pretty-seconds' _ = require 'lodash' ### * Local imports ### WorkerType = require './worker-type' Worker = require './worker' class VariousCluster _log = (type, msg) -> if typeof process.logger is 'object' return process.logger[type](msg) util.log msg _exit = -> workers = Object.keys(cluster.workers).length if workers is 0 _log.call this, 'notice', util.format('%s with pid %s has no workers remaining, exit after %s uptime', @config.title, process.pid, prettySeconds(process.uptime())) process.exit 0 else if !!process.shuttingDown _log.call this, 'notice', util.format('%s with pid %s waits for %s workers to shutdown', @config.title, process.pid, workers) ###* * initalize the VariousCluster with the given config * * @param {object} config read more about config options in README * @function global.VariousCluster.prototype.init * @returns {this} the current instance for chaining ### init: (@config) -> if cluster.isMaster process.title = @config.title or 'various-cluster-master' cluster.on 'exit', (worker, code, signal) => process.nextTick => _exit.call this process.on 'uncaughtException', (err) => process.shuttingDown = true _log.call this, 'crit', util.format('%s with pid %s had uncaught exception, shutdown all workers: %s', @config.title, process.pid, err.stack) _exit.call this worker.send(type: 'shutmedown') for key, worker of cluster.workers ['SIGINT', 'SIGTERM'].forEach (signal) => process.on signal, => process.shuttingDown = true _log.call this, 'notice', util.format('%s with pid %s received signal %s, shutdown all workers', @config.title, process.pid, signal) _exit.call this worker.send(type: 'shutmedown') for key, worker of cluster.workers for workerConfig in @config.workers defaultWorkerTypeConfig = count: @config.count shutdownTimeout: @config.shutdownTimeout title: 'various-cluster-worker' new WorkerType().init _.defaults(workerConfig, defaultWorkerTypeConfig) else if cluster.isWorker new Worker().init() this module.exports = new VariousCluster()
true
###* * @name various-cluster * @description easily create a mulit-cluster environment with different worker-types * @author Valiton GmbH, PI:NAME:<NAME>END_PI "hereandnow" PI:NAME:<NAME>END_PI ### ###* * Standard library imports ### cluster = require 'cluster' util = require 'util' ###* * 3rd library imports ### prettySeconds = require 'pretty-seconds' _ = require 'lodash' ### * Local imports ### WorkerType = require './worker-type' Worker = require './worker' class VariousCluster _log = (type, msg) -> if typeof process.logger is 'object' return process.logger[type](msg) util.log msg _exit = -> workers = Object.keys(cluster.workers).length if workers is 0 _log.call this, 'notice', util.format('%s with pid %s has no workers remaining, exit after %s uptime', @config.title, process.pid, prettySeconds(process.uptime())) process.exit 0 else if !!process.shuttingDown _log.call this, 'notice', util.format('%s with pid %s waits for %s workers to shutdown', @config.title, process.pid, workers) ###* * initalize the VariousCluster with the given config * * @param {object} config read more about config options in README * @function global.VariousCluster.prototype.init * @returns {this} the current instance for chaining ### init: (@config) -> if cluster.isMaster process.title = @config.title or 'various-cluster-master' cluster.on 'exit', (worker, code, signal) => process.nextTick => _exit.call this process.on 'uncaughtException', (err) => process.shuttingDown = true _log.call this, 'crit', util.format('%s with pid %s had uncaught exception, shutdown all workers: %s', @config.title, process.pid, err.stack) _exit.call this worker.send(type: 'shutmedown') for key, worker of cluster.workers ['SIGINT', 'SIGTERM'].forEach (signal) => process.on signal, => process.shuttingDown = true _log.call this, 'notice', util.format('%s with pid %s received signal %s, shutdown all workers', @config.title, process.pid, signal) _exit.call this worker.send(type: 'shutmedown') for key, worker of cluster.workers for workerConfig in @config.workers defaultWorkerTypeConfig = count: @config.count shutdownTimeout: @config.shutdownTimeout title: 'various-cluster-worker' new WorkerType().init _.defaults(workerConfig, defaultWorkerTypeConfig) else if cluster.isWorker new Worker().init() this module.exports = new VariousCluster()
[ { "context": " = new Users([\n factories.makeUser({name: 'Abner'})\n factories.makeUser({name: 'Abigail'})\n", "end": 1318, "score": 0.9994416236877441, "start": 1313, "tag": "NAME", "value": "Abner" }, { "context": "ame: 'Abner'})\n factories.makeUser({name: 'Abigail'})\n factories.makeUser({name: 'Abby'}, {pr", "end": 1364, "score": 0.9997116923332214, "start": 1357, "tag": "NAME", "value": "Abigail" }, { "context": "e: 'Abigail'})\n factories.makeUser({name: 'Abby'}, {prepaid: available})\n factories.makeUs", "end": 1407, "score": 0.9994781017303467, "start": 1403, "tag": "NAME", "value": "Abby" }, { "context": "d: available})\n factories.makeUser({name: 'Ben'}, {prepaid: available})\n factories.makeUs", "end": 1471, "score": 0.999782145023346, "start": 1468, "tag": "NAME", "value": "Ben" }, { "context": "d: available})\n factories.makeUser({name: 'Ned'}, {prepaid: expired})\n factories.makeUser", "end": 1535, "score": 0.999380350112915, "start": 1532, "tag": "NAME", "value": "Ned" }, { "context": "aid: expired})\n factories.makeUser({name: 'Ebner'}, {prepaid: expired})\n ])\n @levels = n", "end": 1599, "score": 0.9996300339698792, "start": 1594, "tag": "NAME", "value": "Ebner" } ]
test/app/views/teachers/TeacherClassView.spec.coffee
reyesj1988/Codecombat
1
TeacherClassView = require 'views/courses/TeacherClassView' storage = require 'core/storage' forms = require 'core/forms' factories = require 'test/app/factories' Users = require 'collections/Users' Courses = require 'collections/Courses' Levels = require 'collections/Levels' LevelSessions = require 'collections/LevelSessions' CourseInstances = require 'collections/CourseInstances' describe '/teachers/classes/:handle', -> describe 'TeacherClassView', -> # describe 'when logged out', -> # it 'responds with 401 error' # it 'shows Log In and Create Account buttons' # describe "when you don't own the class", -> # it 'responds with 403 error' # it 'shows Log Out button' describe 'when logged in', -> beforeEach (done) -> me = factories.makeUser({}) @courses = new Courses([ factories.makeCourse({name: 'First Course'}), factories.makeCourse({name: 'Second Course'}), factories.makeCourse({name: 'Beta Course', releasePhase: 'beta'}), ]) @releasedCourses = new Courses(@courses.where({ releasePhase: 'released' })) available = factories.makePrepaid() expired = factories.makePrepaid({endDate: moment().subtract(1, 'day').toISOString()}) @students = new Users([ factories.makeUser({name: 'Abner'}) factories.makeUser({name: 'Abigail'}) factories.makeUser({name: 'Abby'}, {prepaid: available}) factories.makeUser({name: 'Ben'}, {prepaid: available}) factories.makeUser({name: 'Ned'}, {prepaid: expired}) factories.makeUser({name: 'Ebner'}, {prepaid: expired}) ]) @levels = new Levels(_.times(2, -> factories.makeLevel({ concepts: ['basic_syntax', 'arguments', 'functions'] }))) @classroom = factories.makeClassroom({}, { courses: @releasedCourses, members: @students, levels: [@levels, new Levels()] }) @courseInstances = new CourseInstances([ factories.makeCourseInstance({}, { course: @releasedCourses.first(), @classroom, members: @students }) factories.makeCourseInstance({}, { course: @releasedCourses.last(), @classroom, members: @students }) ]) sessions = [] @finishedStudent = @students.first() @unfinishedStudent = @students.last() for level in @levels.models sessions.push(factories.makeLevelSession( {state: {complete: true}, playtime: 60}, {level, creator: @finishedStudent}) ) sessions.push(factories.makeLevelSession( {state: {complete: true}, playtime: 60}, {level: @levels.first(), creator: @unfinishedStudent}) ) @levelSessions = new LevelSessions(sessions) @view = new TeacherClassView({}, @courseInstances.first().id) @view.classroom.fakeRequests[0].respondWith({ status: 200, responseText: @classroom.stringify() }) @view.courses.fakeRequests[0].respondWith({ status: 200, responseText: @courses.stringify() }) @view.courseInstances.fakeRequests[0].respondWith({ status: 200, responseText: @courseInstances.stringify() }) @view.students.fakeRequests[0].respondWith({ status: 200, responseText: @students.stringify() }) @view.classroom.sessions.fakeRequests[0].respondWith({ status: 200, responseText: @levelSessions.stringify() }) @view.levels.fakeRequests[0].respondWith({ status: 200, responseText: @levels.stringify() }) jasmine.demoEl(@view.$el) _.defer done it 'has contents', -> expect(@view.$el.children().length).toBeGreaterThan(0) # it "shows the classroom's name and description" # it "shows the classroom's join code" describe 'the Students tab', -> beforeEach (done) -> @view.state.set('activeTab', '#students-tab') _.defer(done) # it 'shows all of the students' # it 'sorts correctly by Name' # it 'sorts correctly by Progress' describe 'bulk-assign controls', -> it 'shows alert when assigning course 2 to unenrolled students', (done) -> expect(@view.$('.cant-assign-to-unenrolled').hasClass('visible')).toBe(false) @view.$('.student-row .checkbox-flat').click() @view.$('.assign-to-selected-students').click() _.defer => expect(@view.$('.cant-assign-to-unenrolled').hasClass('visible')).toBe(true) done() it 'shows alert when assigning but no students are selected', (done) -> expect(@view.$('.no-students-selected').hasClass('visible')).toBe(false) @view.$('.assign-to-selected-students').click() _.defer => expect(@view.$('.no-students-selected').hasClass('visible')).toBe(true) done() # describe 'the Course Progress tab', -> # it 'shows the correct Course Overview progress' # # describe 'when viewing another course' # it 'still shows the correct Course Overview progress' # describe 'the Enrollment Status tab', -> beforeEach -> @view.state.set('activeTab', '#enrollment-status-tab') describe 'Enroll button', -> it 'calls enrollStudents with that user when clicked', -> spyOn(@view, 'enrollStudents') @view.$('.enroll-student-button:first').click() expect(@view.enrollStudents).toHaveBeenCalled() users = @view.enrollStudents.calls.argsFor(0)[0] expect(users.size()).toBe(1) expect(users.first().id).toBe(@view.students.first().id) describe 'Export Student Progress (CSV) button', -> it 'downloads a CSV file', -> spyOn(window, 'open').and.callFake (encodedCSV) => progressData = decodeURI(encodedCSV) CSVHeader = 'data:text\/csv;charset=utf-8,' expect(progressData).toMatch new RegExp('^' + CSVHeader) lines = progressData.slice(CSVHeader.length).split('\n') expect(lines.length).toBe(@students.length + 1) for line in lines simplerLine = line.replace(/"[^"]+"/g, '""') # Username,Email,Total Playtime, [CS1-? Playtime], Concepts expect(simplerLine.match(/[^,]+/g).length).toBe(3 + @releasedCourses.length + 1) if simplerLine.match new RegExp(@finishedStudent.get('email')) expect(simplerLine).toMatch /2 minutes,2 minutes,0/ else if simplerLine.match new RegExp(@unfinishedStudent.get('email')) expect(simplerLine).toMatch /a minute,a minute,0/ else if simplerLine.match /@/ expect(simplerLine).toMatch /0,0,0/ return true @view.$('.export-student-progress-btn').click() expect(window.open).toHaveBeenCalled()
208424
TeacherClassView = require 'views/courses/TeacherClassView' storage = require 'core/storage' forms = require 'core/forms' factories = require 'test/app/factories' Users = require 'collections/Users' Courses = require 'collections/Courses' Levels = require 'collections/Levels' LevelSessions = require 'collections/LevelSessions' CourseInstances = require 'collections/CourseInstances' describe '/teachers/classes/:handle', -> describe 'TeacherClassView', -> # describe 'when logged out', -> # it 'responds with 401 error' # it 'shows Log In and Create Account buttons' # describe "when you don't own the class", -> # it 'responds with 403 error' # it 'shows Log Out button' describe 'when logged in', -> beforeEach (done) -> me = factories.makeUser({}) @courses = new Courses([ factories.makeCourse({name: 'First Course'}), factories.makeCourse({name: 'Second Course'}), factories.makeCourse({name: 'Beta Course', releasePhase: 'beta'}), ]) @releasedCourses = new Courses(@courses.where({ releasePhase: 'released' })) available = factories.makePrepaid() expired = factories.makePrepaid({endDate: moment().subtract(1, 'day').toISOString()}) @students = new Users([ factories.makeUser({name: '<NAME>'}) factories.makeUser({name: '<NAME>'}) factories.makeUser({name: '<NAME>'}, {prepaid: available}) factories.makeUser({name: '<NAME>'}, {prepaid: available}) factories.makeUser({name: '<NAME>'}, {prepaid: expired}) factories.makeUser({name: '<NAME>'}, {prepaid: expired}) ]) @levels = new Levels(_.times(2, -> factories.makeLevel({ concepts: ['basic_syntax', 'arguments', 'functions'] }))) @classroom = factories.makeClassroom({}, { courses: @releasedCourses, members: @students, levels: [@levels, new Levels()] }) @courseInstances = new CourseInstances([ factories.makeCourseInstance({}, { course: @releasedCourses.first(), @classroom, members: @students }) factories.makeCourseInstance({}, { course: @releasedCourses.last(), @classroom, members: @students }) ]) sessions = [] @finishedStudent = @students.first() @unfinishedStudent = @students.last() for level in @levels.models sessions.push(factories.makeLevelSession( {state: {complete: true}, playtime: 60}, {level, creator: @finishedStudent}) ) sessions.push(factories.makeLevelSession( {state: {complete: true}, playtime: 60}, {level: @levels.first(), creator: @unfinishedStudent}) ) @levelSessions = new LevelSessions(sessions) @view = new TeacherClassView({}, @courseInstances.first().id) @view.classroom.fakeRequests[0].respondWith({ status: 200, responseText: @classroom.stringify() }) @view.courses.fakeRequests[0].respondWith({ status: 200, responseText: @courses.stringify() }) @view.courseInstances.fakeRequests[0].respondWith({ status: 200, responseText: @courseInstances.stringify() }) @view.students.fakeRequests[0].respondWith({ status: 200, responseText: @students.stringify() }) @view.classroom.sessions.fakeRequests[0].respondWith({ status: 200, responseText: @levelSessions.stringify() }) @view.levels.fakeRequests[0].respondWith({ status: 200, responseText: @levels.stringify() }) jasmine.demoEl(@view.$el) _.defer done it 'has contents', -> expect(@view.$el.children().length).toBeGreaterThan(0) # it "shows the classroom's name and description" # it "shows the classroom's join code" describe 'the Students tab', -> beforeEach (done) -> @view.state.set('activeTab', '#students-tab') _.defer(done) # it 'shows all of the students' # it 'sorts correctly by Name' # it 'sorts correctly by Progress' describe 'bulk-assign controls', -> it 'shows alert when assigning course 2 to unenrolled students', (done) -> expect(@view.$('.cant-assign-to-unenrolled').hasClass('visible')).toBe(false) @view.$('.student-row .checkbox-flat').click() @view.$('.assign-to-selected-students').click() _.defer => expect(@view.$('.cant-assign-to-unenrolled').hasClass('visible')).toBe(true) done() it 'shows alert when assigning but no students are selected', (done) -> expect(@view.$('.no-students-selected').hasClass('visible')).toBe(false) @view.$('.assign-to-selected-students').click() _.defer => expect(@view.$('.no-students-selected').hasClass('visible')).toBe(true) done() # describe 'the Course Progress tab', -> # it 'shows the correct Course Overview progress' # # describe 'when viewing another course' # it 'still shows the correct Course Overview progress' # describe 'the Enrollment Status tab', -> beforeEach -> @view.state.set('activeTab', '#enrollment-status-tab') describe 'Enroll button', -> it 'calls enrollStudents with that user when clicked', -> spyOn(@view, 'enrollStudents') @view.$('.enroll-student-button:first').click() expect(@view.enrollStudents).toHaveBeenCalled() users = @view.enrollStudents.calls.argsFor(0)[0] expect(users.size()).toBe(1) expect(users.first().id).toBe(@view.students.first().id) describe 'Export Student Progress (CSV) button', -> it 'downloads a CSV file', -> spyOn(window, 'open').and.callFake (encodedCSV) => progressData = decodeURI(encodedCSV) CSVHeader = 'data:text\/csv;charset=utf-8,' expect(progressData).toMatch new RegExp('^' + CSVHeader) lines = progressData.slice(CSVHeader.length).split('\n') expect(lines.length).toBe(@students.length + 1) for line in lines simplerLine = line.replace(/"[^"]+"/g, '""') # Username,Email,Total Playtime, [CS1-? Playtime], Concepts expect(simplerLine.match(/[^,]+/g).length).toBe(3 + @releasedCourses.length + 1) if simplerLine.match new RegExp(@finishedStudent.get('email')) expect(simplerLine).toMatch /2 minutes,2 minutes,0/ else if simplerLine.match new RegExp(@unfinishedStudent.get('email')) expect(simplerLine).toMatch /a minute,a minute,0/ else if simplerLine.match /@/ expect(simplerLine).toMatch /0,0,0/ return true @view.$('.export-student-progress-btn').click() expect(window.open).toHaveBeenCalled()
true
TeacherClassView = require 'views/courses/TeacherClassView' storage = require 'core/storage' forms = require 'core/forms' factories = require 'test/app/factories' Users = require 'collections/Users' Courses = require 'collections/Courses' Levels = require 'collections/Levels' LevelSessions = require 'collections/LevelSessions' CourseInstances = require 'collections/CourseInstances' describe '/teachers/classes/:handle', -> describe 'TeacherClassView', -> # describe 'when logged out', -> # it 'responds with 401 error' # it 'shows Log In and Create Account buttons' # describe "when you don't own the class", -> # it 'responds with 403 error' # it 'shows Log Out button' describe 'when logged in', -> beforeEach (done) -> me = factories.makeUser({}) @courses = new Courses([ factories.makeCourse({name: 'First Course'}), factories.makeCourse({name: 'Second Course'}), factories.makeCourse({name: 'Beta Course', releasePhase: 'beta'}), ]) @releasedCourses = new Courses(@courses.where({ releasePhase: 'released' })) available = factories.makePrepaid() expired = factories.makePrepaid({endDate: moment().subtract(1, 'day').toISOString()}) @students = new Users([ factories.makeUser({name: 'PI:NAME:<NAME>END_PI'}) factories.makeUser({name: 'PI:NAME:<NAME>END_PI'}) factories.makeUser({name: 'PI:NAME:<NAME>END_PI'}, {prepaid: available}) factories.makeUser({name: 'PI:NAME:<NAME>END_PI'}, {prepaid: available}) factories.makeUser({name: 'PI:NAME:<NAME>END_PI'}, {prepaid: expired}) factories.makeUser({name: 'PI:NAME:<NAME>END_PI'}, {prepaid: expired}) ]) @levels = new Levels(_.times(2, -> factories.makeLevel({ concepts: ['basic_syntax', 'arguments', 'functions'] }))) @classroom = factories.makeClassroom({}, { courses: @releasedCourses, members: @students, levels: [@levels, new Levels()] }) @courseInstances = new CourseInstances([ factories.makeCourseInstance({}, { course: @releasedCourses.first(), @classroom, members: @students }) factories.makeCourseInstance({}, { course: @releasedCourses.last(), @classroom, members: @students }) ]) sessions = [] @finishedStudent = @students.first() @unfinishedStudent = @students.last() for level in @levels.models sessions.push(factories.makeLevelSession( {state: {complete: true}, playtime: 60}, {level, creator: @finishedStudent}) ) sessions.push(factories.makeLevelSession( {state: {complete: true}, playtime: 60}, {level: @levels.first(), creator: @unfinishedStudent}) ) @levelSessions = new LevelSessions(sessions) @view = new TeacherClassView({}, @courseInstances.first().id) @view.classroom.fakeRequests[0].respondWith({ status: 200, responseText: @classroom.stringify() }) @view.courses.fakeRequests[0].respondWith({ status: 200, responseText: @courses.stringify() }) @view.courseInstances.fakeRequests[0].respondWith({ status: 200, responseText: @courseInstances.stringify() }) @view.students.fakeRequests[0].respondWith({ status: 200, responseText: @students.stringify() }) @view.classroom.sessions.fakeRequests[0].respondWith({ status: 200, responseText: @levelSessions.stringify() }) @view.levels.fakeRequests[0].respondWith({ status: 200, responseText: @levels.stringify() }) jasmine.demoEl(@view.$el) _.defer done it 'has contents', -> expect(@view.$el.children().length).toBeGreaterThan(0) # it "shows the classroom's name and description" # it "shows the classroom's join code" describe 'the Students tab', -> beforeEach (done) -> @view.state.set('activeTab', '#students-tab') _.defer(done) # it 'shows all of the students' # it 'sorts correctly by Name' # it 'sorts correctly by Progress' describe 'bulk-assign controls', -> it 'shows alert when assigning course 2 to unenrolled students', (done) -> expect(@view.$('.cant-assign-to-unenrolled').hasClass('visible')).toBe(false) @view.$('.student-row .checkbox-flat').click() @view.$('.assign-to-selected-students').click() _.defer => expect(@view.$('.cant-assign-to-unenrolled').hasClass('visible')).toBe(true) done() it 'shows alert when assigning but no students are selected', (done) -> expect(@view.$('.no-students-selected').hasClass('visible')).toBe(false) @view.$('.assign-to-selected-students').click() _.defer => expect(@view.$('.no-students-selected').hasClass('visible')).toBe(true) done() # describe 'the Course Progress tab', -> # it 'shows the correct Course Overview progress' # # describe 'when viewing another course' # it 'still shows the correct Course Overview progress' # describe 'the Enrollment Status tab', -> beforeEach -> @view.state.set('activeTab', '#enrollment-status-tab') describe 'Enroll button', -> it 'calls enrollStudents with that user when clicked', -> spyOn(@view, 'enrollStudents') @view.$('.enroll-student-button:first').click() expect(@view.enrollStudents).toHaveBeenCalled() users = @view.enrollStudents.calls.argsFor(0)[0] expect(users.size()).toBe(1) expect(users.first().id).toBe(@view.students.first().id) describe 'Export Student Progress (CSV) button', -> it 'downloads a CSV file', -> spyOn(window, 'open').and.callFake (encodedCSV) => progressData = decodeURI(encodedCSV) CSVHeader = 'data:text\/csv;charset=utf-8,' expect(progressData).toMatch new RegExp('^' + CSVHeader) lines = progressData.slice(CSVHeader.length).split('\n') expect(lines.length).toBe(@students.length + 1) for line in lines simplerLine = line.replace(/"[^"]+"/g, '""') # Username,Email,Total Playtime, [CS1-? Playtime], Concepts expect(simplerLine.match(/[^,]+/g).length).toBe(3 + @releasedCourses.length + 1) if simplerLine.match new RegExp(@finishedStudent.get('email')) expect(simplerLine).toMatch /2 minutes,2 minutes,0/ else if simplerLine.match new RegExp(@unfinishedStudent.get('email')) expect(simplerLine).toMatch /a minute,a minute,0/ else if simplerLine.match /@/ expect(simplerLine).toMatch /0,0,0/ return true @view.$('.export-student-progress-btn').click() expect(window.open).toHaveBeenCalled()
[ { "context": " 2015\n# The MIT License (MIT)\n# Copyright (c) 2015 Dustin Dowell\n# github.com/dustindowell22/durable-font-size\n# =", "end": 102, "score": 0.9998409152030945, "start": 89, "tag": "NAME", "value": "Dustin Dowell" }, { "context": ")\n# Copyright (c) 2015 Dustin Dowell\n# github.com/dustindowell22/durable-font-size\n# =============================", "end": 130, "score": 0.9964298009872437, "start": 116, "tag": "USERNAME", "value": "dustindowell22" } ]
buckle/framework/coffee/plugins/jquery.durable-font-size.coffee
dustin-archive/buckle
2
# Durable Font Size - 1.0.2 # June 23, 2015 # The MIT License (MIT) # Copyright (c) 2015 Dustin Dowell # github.com/dustindowell22/durable-font-size # ============================================= (($) -> $.fn.dfs = (drag = 32, precision = 'low', container = 'window', fontSize = null) -> # Cache this object $this = $(this) # Store the font size if fontSize == null console.log('hello') fontSize = parseFloat($this.css('font-size')) # Self-initiating Durable Font Size do dfs = -> # containerWidth = if container == 'window' $(window).width() else if container == 'parent' parseFloat($this.parent().css('width')) # fontScale = fontSize + (containerWidth / (drag * fontSize)) # newFontSize = if precision == 'low' fontScale else if precision == 'medium' Math.round(fontScale) else if precision == 'high' Math.round(parseFloat(fontScale / fontSize) * fontSize) else fontSize # Set the font size $this.css('font-size', (newFontSize / 16) + 'rem') # Execute on resize $(window).on('resize orientationchange', dfs) # Allow chaining return this ) jQuery
104583
# Durable Font Size - 1.0.2 # June 23, 2015 # The MIT License (MIT) # Copyright (c) 2015 <NAME> # github.com/dustindowell22/durable-font-size # ============================================= (($) -> $.fn.dfs = (drag = 32, precision = 'low', container = 'window', fontSize = null) -> # Cache this object $this = $(this) # Store the font size if fontSize == null console.log('hello') fontSize = parseFloat($this.css('font-size')) # Self-initiating Durable Font Size do dfs = -> # containerWidth = if container == 'window' $(window).width() else if container == 'parent' parseFloat($this.parent().css('width')) # fontScale = fontSize + (containerWidth / (drag * fontSize)) # newFontSize = if precision == 'low' fontScale else if precision == 'medium' Math.round(fontScale) else if precision == 'high' Math.round(parseFloat(fontScale / fontSize) * fontSize) else fontSize # Set the font size $this.css('font-size', (newFontSize / 16) + 'rem') # Execute on resize $(window).on('resize orientationchange', dfs) # Allow chaining return this ) jQuery
true
# Durable Font Size - 1.0.2 # June 23, 2015 # The MIT License (MIT) # Copyright (c) 2015 PI:NAME:<NAME>END_PI # github.com/dustindowell22/durable-font-size # ============================================= (($) -> $.fn.dfs = (drag = 32, precision = 'low', container = 'window', fontSize = null) -> # Cache this object $this = $(this) # Store the font size if fontSize == null console.log('hello') fontSize = parseFloat($this.css('font-size')) # Self-initiating Durable Font Size do dfs = -> # containerWidth = if container == 'window' $(window).width() else if container == 'parent' parseFloat($this.parent().css('width')) # fontScale = fontSize + (containerWidth / (drag * fontSize)) # newFontSize = if precision == 'low' fontScale else if precision == 'medium' Math.round(fontScale) else if precision == 'high' Math.round(parseFloat(fontScale / fontSize) * fontSize) else fontSize # Set the font size $this.css('font-size', (newFontSize / 16) + 'rem') # Execute on resize $(window).on('resize orientationchange', dfs) # Allow chaining return this ) jQuery
[ { "context": "###\n@Author: Kristinita\n@Date: 2018-02-22 11:54:50\n@Last Modified time:", "end": 23, "score": 0.9998382329940796, "start": 13, "tag": "NAME", "value": "Kristinita" }, { "context": "pp/IT-articles/typo-reporter\n# https://github.com/psmb/typo-reporter/issues/4#issuecomment-367471138\nroo", "end": 338, "score": 0.9991660118103027, "start": 334, "tag": "USERNAME", "value": "psmb" } ]
themes/sashapelican/static/coffee/typo-reporter/typo-reporter-en.coffee
Kristinita/---
6
### @Author: Kristinita @Date: 2018-02-22 11:54:50 @Last Modified time: 2018-02-22 11:59:46 ### ################# # typo-reporter # ################# # Script, that users can send message about site typos: # https://www.npmjs.com/package/typo-reporter # https://kristinita.netlify.app/IT-articles/typo-reporter # https://github.com/psmb/typo-reporter/issues/4#issuecomment-367471138 rootNode = document.createElement("div") document.body.appendChild rootNode typo = new TypoReporter({ formId: "<%= form_id_typo_reporter %>" locale: "en" offset: 44 }, rootNode)
84851
### @Author: <NAME> @Date: 2018-02-22 11:54:50 @Last Modified time: 2018-02-22 11:59:46 ### ################# # typo-reporter # ################# # Script, that users can send message about site typos: # https://www.npmjs.com/package/typo-reporter # https://kristinita.netlify.app/IT-articles/typo-reporter # https://github.com/psmb/typo-reporter/issues/4#issuecomment-367471138 rootNode = document.createElement("div") document.body.appendChild rootNode typo = new TypoReporter({ formId: "<%= form_id_typo_reporter %>" locale: "en" offset: 44 }, rootNode)
true
### @Author: PI:NAME:<NAME>END_PI @Date: 2018-02-22 11:54:50 @Last Modified time: 2018-02-22 11:59:46 ### ################# # typo-reporter # ################# # Script, that users can send message about site typos: # https://www.npmjs.com/package/typo-reporter # https://kristinita.netlify.app/IT-articles/typo-reporter # https://github.com/psmb/typo-reporter/issues/4#issuecomment-367471138 rootNode = document.createElement("div") document.body.appendChild rootNode typo = new TypoReporter({ formId: "<%= form_id_typo_reporter %>" locale: "en" offset: 44 }, rootNode)
[ { "context": "# Not really great, but... good enough, I guess --Jason (4/30/13)\n totalCards = _(globals.playerNu", "end": 1732, "score": 0.7505853176116943, "start": 1727, "tag": "NAME", "value": "Jason" }, { "context": "hen make it so that ID collisions are unlikely. --Jason (6/8/13)\n safetyNum = 10000\n r ", "end": 3304, "score": 0.9464681148529053, "start": 3299, "tag": "NAME", "value": "Jason" } ]
app/assets/javascripts/index/main.coffee
TheBizzle/ClowCards
0
f = -> dependOn("root_main") dependOn("api_prototypes") dependOn("index_onload") Obj = dependOn("adt_obj") $ = dependOn("api_jquery") CardIterator = dependOn("index_carditerator") Cards = dependOn("index_cards") Constants = dependOn("index_constants") globals = dependOn("index_globals") $globals = dependOn("index_jglobals") Element = dependOn("index_element") class Index constructor: -> @_resetIterator() # (Event) => Unit handleRowKey: (event) -> switch (event.keyCode or event.which) when 13 then @addRow() else return # (Event) => Unit handleNumPickerKey: (event) -> switch (event.keyCode or event.which) when 13 then @genCards() else return # () => Unit clearErrorFuzz: -> $globals.$nameInput.removeClass('glowing-border') # () => Unit addRow: -> @clearErrorFuzz() $input = $globals.$nameInput name = $input.val() if not _(name).isEmpty() if _(globals.playerNums).size() < Constants.MaxPlayerCount $input.val("") @_genRow(name) else $input.addClass('glowing-border') # (String) => Unit removeRow: (id) -> $.byID(id).remove() num = generateNumFromID(id) globals.playerNums = _(globals.playerNums).filter((n) -> n != num).value() # () => Unit genCards: -> @clearErrorFuzz() numCards = parseInt($globals.$cardNumSpinner.val()) maxCards = new Obj(getCards()).filter((k, v) -> v.enabled).size() # Not really great, but... good enough, I guess --Jason (4/30/13) totalCards = _(globals.playerNums).size() * numCards if totalCards <= maxCards @_cleanupLastCardGen() _([0...numCards]).forEach((x) => @_genCardForEachPlayer()).value() else msg = """You attempted to generate #{totalCards} cards, but there are only #{maxCards} available. | |Please reduce the number of cards or players and try again. """.stripMargin().trim() alert(msg) # (String) => String genCardImageURL: (name) -> _genCardImageURL(name) # (String) => String genPriorityImageURL: (name) -> "/assets/images/index/priority/#{name}.png" # (String) => Unit _genRow: (name) => nums = globals.playerNums num = if _(nums).isEmpty() then 1 else (_(nums).last() + 1) id = generatePlayerID(num) elemID = "#{id}-elem" globals.playerNums = nums.append(num) Element.generatePlayerRow(name, id, elemID, => @removeRow(id)).insertBefore($globals.$adderTable) # () => Unit _genCardForEachPlayer: => _(globals.playerNums).map((num) -> generatePlayerID(num)).forEach((id) => @_insertCardForID(id)).value() # (String) => Unit _insertCardForID: (id) => card = @_cardIterator.next() if card? # Given how this is currently implemented, this number is irrelevant; if multiple of the same card can be drawn though, # this then make it so that ID collisions are unlikely. --Jason (6/8/13) safetyNum = 10000 r = Math.floor(Math.random() * safetyNum) cardID = "#{card.slugify()}-#{r}" imgURL = _genCardImageURL(card) column = Element.generateCardEntryColumn(card, cardID, imgURL, Cards[card].faction) $.byID(id).find(".row-content-row").append(column) else alert("Card pool exhausted! Pick fewer cards!") # () => Unit _cleanupLastCardGen: => clearCardBuckets() @_resetIterator() # () => Unit _resetIterator: => @_cardIterator = new CardIterator(getCards()) # (String) => Unit makeImageVisible = (id) -> loaderID = "#{id}-loading" img = $.byID(id) loader = $.byID(loaderID) img.removeClass("hidden") loader.remove() # () => Unit clearCardBuckets = -> _(globals.playerNums).map((num) -> generatePlayerID(num)).forEach( (id) -> $.byID(id).find(".row-content-row").empty() ).value() # (String) => String _genCardImageURL = (name) -> "/assets/images/index/#{name.slugify()}.png" # (String) => String generatePlayerID = (num) -> "player-#{num}" # (String) => Int generateNumFromID = (id) -> [[], num, []] = id.split("-") parseInt(num) # () => Obj[Object[Any]] getCards = -> cardObj = new Obj(Cards).clone().value() labels = $globals.$cardHolder.children("label").map(-> $(this)) _(labels).forEach( (elem) -> id = elem.attr("for") name = elem.text() cardObj[name].enabled = $.byID(id)[0].checked ).value() cardObj declareModule("index_main", f)
36152
f = -> dependOn("root_main") dependOn("api_prototypes") dependOn("index_onload") Obj = dependOn("adt_obj") $ = dependOn("api_jquery") CardIterator = dependOn("index_carditerator") Cards = dependOn("index_cards") Constants = dependOn("index_constants") globals = dependOn("index_globals") $globals = dependOn("index_jglobals") Element = dependOn("index_element") class Index constructor: -> @_resetIterator() # (Event) => Unit handleRowKey: (event) -> switch (event.keyCode or event.which) when 13 then @addRow() else return # (Event) => Unit handleNumPickerKey: (event) -> switch (event.keyCode or event.which) when 13 then @genCards() else return # () => Unit clearErrorFuzz: -> $globals.$nameInput.removeClass('glowing-border') # () => Unit addRow: -> @clearErrorFuzz() $input = $globals.$nameInput name = $input.val() if not _(name).isEmpty() if _(globals.playerNums).size() < Constants.MaxPlayerCount $input.val("") @_genRow(name) else $input.addClass('glowing-border') # (String) => Unit removeRow: (id) -> $.byID(id).remove() num = generateNumFromID(id) globals.playerNums = _(globals.playerNums).filter((n) -> n != num).value() # () => Unit genCards: -> @clearErrorFuzz() numCards = parseInt($globals.$cardNumSpinner.val()) maxCards = new Obj(getCards()).filter((k, v) -> v.enabled).size() # Not really great, but... good enough, I guess --<NAME> (4/30/13) totalCards = _(globals.playerNums).size() * numCards if totalCards <= maxCards @_cleanupLastCardGen() _([0...numCards]).forEach((x) => @_genCardForEachPlayer()).value() else msg = """You attempted to generate #{totalCards} cards, but there are only #{maxCards} available. | |Please reduce the number of cards or players and try again. """.stripMargin().trim() alert(msg) # (String) => String genCardImageURL: (name) -> _genCardImageURL(name) # (String) => String genPriorityImageURL: (name) -> "/assets/images/index/priority/#{name}.png" # (String) => Unit _genRow: (name) => nums = globals.playerNums num = if _(nums).isEmpty() then 1 else (_(nums).last() + 1) id = generatePlayerID(num) elemID = "#{id}-elem" globals.playerNums = nums.append(num) Element.generatePlayerRow(name, id, elemID, => @removeRow(id)).insertBefore($globals.$adderTable) # () => Unit _genCardForEachPlayer: => _(globals.playerNums).map((num) -> generatePlayerID(num)).forEach((id) => @_insertCardForID(id)).value() # (String) => Unit _insertCardForID: (id) => card = @_cardIterator.next() if card? # Given how this is currently implemented, this number is irrelevant; if multiple of the same card can be drawn though, # this then make it so that ID collisions are unlikely. --<NAME> (6/8/13) safetyNum = 10000 r = Math.floor(Math.random() * safetyNum) cardID = "#{card.slugify()}-#{r}" imgURL = _genCardImageURL(card) column = Element.generateCardEntryColumn(card, cardID, imgURL, Cards[card].faction) $.byID(id).find(".row-content-row").append(column) else alert("Card pool exhausted! Pick fewer cards!") # () => Unit _cleanupLastCardGen: => clearCardBuckets() @_resetIterator() # () => Unit _resetIterator: => @_cardIterator = new CardIterator(getCards()) # (String) => Unit makeImageVisible = (id) -> loaderID = "#{id}-loading" img = $.byID(id) loader = $.byID(loaderID) img.removeClass("hidden") loader.remove() # () => Unit clearCardBuckets = -> _(globals.playerNums).map((num) -> generatePlayerID(num)).forEach( (id) -> $.byID(id).find(".row-content-row").empty() ).value() # (String) => String _genCardImageURL = (name) -> "/assets/images/index/#{name.slugify()}.png" # (String) => String generatePlayerID = (num) -> "player-#{num}" # (String) => Int generateNumFromID = (id) -> [[], num, []] = id.split("-") parseInt(num) # () => Obj[Object[Any]] getCards = -> cardObj = new Obj(Cards).clone().value() labels = $globals.$cardHolder.children("label").map(-> $(this)) _(labels).forEach( (elem) -> id = elem.attr("for") name = elem.text() cardObj[name].enabled = $.byID(id)[0].checked ).value() cardObj declareModule("index_main", f)
true
f = -> dependOn("root_main") dependOn("api_prototypes") dependOn("index_onload") Obj = dependOn("adt_obj") $ = dependOn("api_jquery") CardIterator = dependOn("index_carditerator") Cards = dependOn("index_cards") Constants = dependOn("index_constants") globals = dependOn("index_globals") $globals = dependOn("index_jglobals") Element = dependOn("index_element") class Index constructor: -> @_resetIterator() # (Event) => Unit handleRowKey: (event) -> switch (event.keyCode or event.which) when 13 then @addRow() else return # (Event) => Unit handleNumPickerKey: (event) -> switch (event.keyCode or event.which) when 13 then @genCards() else return # () => Unit clearErrorFuzz: -> $globals.$nameInput.removeClass('glowing-border') # () => Unit addRow: -> @clearErrorFuzz() $input = $globals.$nameInput name = $input.val() if not _(name).isEmpty() if _(globals.playerNums).size() < Constants.MaxPlayerCount $input.val("") @_genRow(name) else $input.addClass('glowing-border') # (String) => Unit removeRow: (id) -> $.byID(id).remove() num = generateNumFromID(id) globals.playerNums = _(globals.playerNums).filter((n) -> n != num).value() # () => Unit genCards: -> @clearErrorFuzz() numCards = parseInt($globals.$cardNumSpinner.val()) maxCards = new Obj(getCards()).filter((k, v) -> v.enabled).size() # Not really great, but... good enough, I guess --PI:NAME:<NAME>END_PI (4/30/13) totalCards = _(globals.playerNums).size() * numCards if totalCards <= maxCards @_cleanupLastCardGen() _([0...numCards]).forEach((x) => @_genCardForEachPlayer()).value() else msg = """You attempted to generate #{totalCards} cards, but there are only #{maxCards} available. | |Please reduce the number of cards or players and try again. """.stripMargin().trim() alert(msg) # (String) => String genCardImageURL: (name) -> _genCardImageURL(name) # (String) => String genPriorityImageURL: (name) -> "/assets/images/index/priority/#{name}.png" # (String) => Unit _genRow: (name) => nums = globals.playerNums num = if _(nums).isEmpty() then 1 else (_(nums).last() + 1) id = generatePlayerID(num) elemID = "#{id}-elem" globals.playerNums = nums.append(num) Element.generatePlayerRow(name, id, elemID, => @removeRow(id)).insertBefore($globals.$adderTable) # () => Unit _genCardForEachPlayer: => _(globals.playerNums).map((num) -> generatePlayerID(num)).forEach((id) => @_insertCardForID(id)).value() # (String) => Unit _insertCardForID: (id) => card = @_cardIterator.next() if card? # Given how this is currently implemented, this number is irrelevant; if multiple of the same card can be drawn though, # this then make it so that ID collisions are unlikely. --PI:NAME:<NAME>END_PI (6/8/13) safetyNum = 10000 r = Math.floor(Math.random() * safetyNum) cardID = "#{card.slugify()}-#{r}" imgURL = _genCardImageURL(card) column = Element.generateCardEntryColumn(card, cardID, imgURL, Cards[card].faction) $.byID(id).find(".row-content-row").append(column) else alert("Card pool exhausted! Pick fewer cards!") # () => Unit _cleanupLastCardGen: => clearCardBuckets() @_resetIterator() # () => Unit _resetIterator: => @_cardIterator = new CardIterator(getCards()) # (String) => Unit makeImageVisible = (id) -> loaderID = "#{id}-loading" img = $.byID(id) loader = $.byID(loaderID) img.removeClass("hidden") loader.remove() # () => Unit clearCardBuckets = -> _(globals.playerNums).map((num) -> generatePlayerID(num)).forEach( (id) -> $.byID(id).find(".row-content-row").empty() ).value() # (String) => String _genCardImageURL = (name) -> "/assets/images/index/#{name.slugify()}.png" # (String) => String generatePlayerID = (num) -> "player-#{num}" # (String) => Int generateNumFromID = (id) -> [[], num, []] = id.split("-") parseInt(num) # () => Obj[Object[Any]] getCards = -> cardObj = new Obj(Cards).clone().value() labels = $globals.$cardHolder.children("label").map(-> $(this)) _(labels).forEach( (elem) -> id = elem.attr("for") name = elem.text() cardObj[name].enabled = $.byID(id)[0].checked ).value() cardObj declareModule("index_main", f)
[ { "context": "ileoverview Tests for comma-dangle rule.\n# @author Ian Christian Myers\n###\n\n'use strict'\n\n#-----------------------------", "end": 79, "score": 0.9996938705444336, "start": 60, "tag": "NAME", "value": "Ian Christian Myers" }, { "context": ": ['only-multiline']\n ,\n # https://github.com/eslint/eslint/issues/3627\n code: '[a, ...rest] = []'\n", "end": 3874, "score": 0.999404788017273, "start": 3868, "tag": "USERNAME", "value": "eslint" }, { "context": " options: ['always']\n ,\n # https://github.com/eslint/eslint/issues/7297\n code: '{foo, ...bar} = baz", "end": 4402, "score": 0.9993663430213928, "start": 4396, "tag": "USERNAME", "value": "eslint" }, { "context": " options: ['always']\n ,\n # https://github.com/eslint/eslint/issues/3794\n code: \"import {foo,} from ", "end": 4513, "score": 0.9993521571159363, "start": 4507, "tag": "USERNAME", "value": "eslint" }, { "context": " column: 4\n ]\n ,\n # https://github.com/eslint/eslint/issues/7291\n code:\n 'foo = [\\n' + ", "end": 12165, "score": 0.9992425441741943, "start": 12159, "tag": "USERNAME", "value": "eslint" }, { "context": " column: 19\n ]\n ,\n # https://github.com/eslint/eslint/issues/3794\n code: \"import {foo} from '", "end": 16268, "score": 0.9957486987113953, "start": 16262, "tag": "USERNAME", "value": "eslint" }, { "context": ": 'ExportSpecifier']\n ,\n # https://github.com/eslint/eslint/issues/6233\n code: 'foo = {a: (1)}'\n ", "end": 18577, "score": 0.999106228351593, "start": 18571, "tag": "USERNAME", "value": "eslint" } ]
src/tests/rules/comma-dangle.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for comma-dangle rule. # @author Ian Christian Myers ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ ### eslint-disable ### rule = require 'eslint/lib/rules/comma-dangle' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Gets the path to the parser of the given name. # # @param {string} name - The name of a parser to get. # @returns {string} The path to the specified parser. ### # parser = (name) -> # path.resolve __dirname, "../../fixtures/parsers/comma-dangle/#{name}.js" #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### ruleTester.run 'comma-dangle', rule, valid: [ "foo = { bar: 'baz' }" "foo = bar: 'baz'" "foo = {\n bar: 'baz'\n}" "foo = [ 'baz' ]" "foo = [\n 'baz'\n]" '[,,]' '[\n,\n,\n]' '[,]' '[\n,\n]' '[]' '[\n]' , code: 'foo = [\n (if bar then baz else qux),\n ]' options: ['always-multiline'] , code: "foo = { bar: 'baz' }", options: ['never'] , code: "foo = {\n bar: 'baz'\n}", options: ['never'] , code: "foo = [ 'baz' ]", options: ['never'] , code: '{ a, b } = foo' options: ['never'] , code: '[ a, b ] = foo' options: ['never'] , code: '{ a,\n b, \n} = foo' options: ['only-multiline'] , code: '[ a,\n b, \n] = foo' options: ['only-multiline'] , code: '[(1),]', options: ['always'] , code: 'x = { foo: (1),}', options: ['always'] , code: "foo = { bar: 'baz', }", options: ['always'] , code: "foo = {\n bar: 'baz',\n}", options: ['always'] , code: "foo = \n bar: 'baz',\n", options: ['always'] , code: "foo = {\n bar: 'baz'\n,}", options: ['always'] , code: "foo = [ 'baz', ]", options: ['always'] , code: "foo = [\n 'baz',\n]", options: ['always'] , code: "foo = [\n 'baz'\n,]", options: ['always'] , code: '[,,]', options: ['always'] , code: '[\n,\n,\n]', options: ['always'] , code: '[,]', options: ['always'] , code: '[\n,\n]', options: ['always'] , code: '[]', options: ['always'] , code: '[\n]', options: ['always'] , code: "foo = { bar: 'baz' }", options: ['always-multiline'] , code: "foo = { bar: 'baz' }", options: ['only-multiline'] , code: "foo = {\nbar: 'baz',\n}", options: ['always-multiline'] , code: "foo = {\nbar: 'baz',\n}", options: ['only-multiline'] , code: "foo = [ 'baz' ]", options: ['always-multiline'] , code: "foo = [ 'baz' ]", options: ['only-multiline'] , code: "foo = [\n 'baz',\n]", options: ['always-multiline'] , code: "foo = [\n 'baz',\n]", options: ['only-multiline'] , code: 'foo = {a: 1, b: 2, c: 3, d: 4}', options: ['always-multiline'] , code: 'foo = {a: 1, b: 2, c: 3, d: 4}', options: ['only-multiline'] , code: 'foo = {a: 1, b: 2,\nc: 3, d: 4}' options: ['always-multiline'] , code: 'foo = {a: 1, b: 2,\nc: 3, d: 4}', options: ['only-multiline'] , code: "foo = {x: {\nfoo: 'bar',\n}}", options: ['always-multiline'] , code: "foo = {x: {\nfoo: 'bar',\n}}", options: ['only-multiline'] , code: 'foo = new Map([\n [key, {\n a: 1,\n b: 2,\n c: 3,\n }],\n])' options: ['always-multiline'] , code: 'foo = new Map([\n [key, {\n a: 1,\n b: 2,\n c: 3,\n }],\n])' options: ['only-multiline'] , # https://github.com/eslint/eslint/issues/3627 code: '[a, ...rest] = []' options: ['always'] , code: '[\n a,\n ...rest\n] = []' options: ['always'] , code: '[\n a,\n ...rest\n] = []' options: ['always-multiline'] , code: '[\n a,\n ...rest\n] = []' options: ['only-multiline'] , code: '[a, ...rest] = []' options: ['always'] , code: 'for [a, ...rest] in [] then ;' options: ['always'] , code: 'a = [b, ...spread,]' options: ['always'] , # https://github.com/eslint/eslint/issues/7297 code: '{foo, ...bar} = baz' options: ['always'] , # https://github.com/eslint/eslint/issues/3794 code: "import {foo,} from 'foo'" options: ['always'] , code: "import foo from 'foo'" options: ['always'] , code: "import foo, {abc,} from 'foo'" options: ['always'] , code: "import * as foo from 'foo'" options: ['always'] , code: "export {foo,} from 'foo'" options: ['always'] , code: "import {foo} from 'foo'" options: ['never'] , code: "import foo from 'foo'" options: ['never'] , code: "import foo, {abc} from 'foo'" options: ['never'] , code: "import * as foo from 'foo'" options: ['never'] , code: "export {foo} from 'foo'" options: ['never'] , code: "import {foo} from 'foo'" options: ['always-multiline'] , code: "import {foo} from 'foo'" options: ['only-multiline'] , code: "export {foo} from 'foo'" options: ['always-multiline'] , code: "export {foo} from 'foo'" options: ['only-multiline'] , code: "import {\n foo,\n} from 'foo'" options: ['always-multiline'] , code: "import {\n foo,\n} from 'foo'" options: ['only-multiline'] , code: "export {\n foo,\n} from 'foo'" options: ['always-multiline'] , code: "export {\n foo,\n} from 'foo'" options: ['only-multiline'] , code: '(a) ->' options: ['always'] , code: '(a) ->' options: ['always'] , code: '(\na,\nb\n) ->' options: ['always-multiline'] , code: 'foo(\na,b)' options: ['always-multiline'] , code: 'foo(a,b,)' options: ['always-multiline'] , # trailing comma in functions code: '(a) ->' options: [functions: 'never'] , code: '(a) ->' options: [functions: 'always'] , code: 'foo(a)' options: [functions: 'never'] , code: '(a, ...b) ->' options: [functions: 'always'] , code: 'foo(a,)' options: [functions: 'always'] , code: 'bar(...a,)' options: [functions: 'always'] , code: '(a) -> ' options: [functions: 'always-multiline'] , code: 'foo(a)' options: [functions: 'always-multiline'] , code: 'foo a' options: [functions: 'always-multiline'] , code: '(\na,\nb,\n) -> ' options: [functions: 'always-multiline'] , code: '(\na,\n...b\n) -> ' options: [functions: 'always-multiline'] , code: 'foo(\na,\nb,\n)' options: [functions: 'always-multiline'] , code: 'foo(\na,\n...b,\n)' options: [functions: 'always-multiline'] , code: 'function foo(a) {} ' options: [functions: 'only-multiline'] , code: 'foo(a)' options: [functions: 'only-multiline'] , code: 'function foo(\na,\nb,\n) {} ' options: [functions: 'only-multiline'] , code: 'foo(\na,\nb,\n)' options: [functions: 'only-multiline'] , code: 'function foo(\na,\nb\n) {} ' options: [functions: 'only-multiline'] , code: 'foo(\na,\nb\n)' options: [functions: 'only-multiline'] ] invalid: [ code: "foo = { bar: 'baz', }" output: "foo = { bar: 'baz' }" errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 23 ] , code: "foo = {\nbar: 'baz',\n}" output: "foo = {\nbar: 'baz'\n}" errors: [ messageId: 'unexpected' type: 'Property' line: 2 column: 11 ] , code: "foo({ bar: 'baz', qux: 'quux', })" output: "foo({ bar: 'baz', qux: 'quux' })" errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 30 ] , code: "foo({\nbar: 'baz',\nqux: 'quux',\n})" output: "foo({\nbar: 'baz',\nqux: 'quux'\n})" errors: [ messageId: 'unexpected' type: 'Property' line: 3 column: 12 ] , code: "foo = [ 'baz', ]" output: "foo = [ 'baz' ]" errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 18 ] , code: "foo = [ 'baz',\n]" output: "foo = [ 'baz'\n]" errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 18 ] , code: "foo = { bar: 'bar'\n\n, }" output: "foo = { bar: 'bar'\n\n }" errors: [ messageId: 'unexpected' type: 'Property' line: 3 column: 1 ] , code: "foo = { bar: 'baz', }" output: "foo = { bar: 'baz' }" options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 23 ] , code: "foo = { bar: 'baz', }" output: "foo = { bar: 'baz' }" options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 23 ] , code: "foo = {\nbar: 'baz',\n}" output: "foo = {\nbar: 'baz'\n}" options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 2 column: 11 ] , code: "foo({ bar: 'baz', qux: 'quux', })" output: "foo({ bar: 'baz', qux: 'quux' })" options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 30 ] , code: "foo({ bar: 'baz', qux: 'quux', })" output: "foo({ bar: 'baz', qux: 'quux' })" options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 30 ] , code: "foo = { bar: 'baz' }" output: "foo = { bar: 'baz', }" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 1 column: 23 ] , code: "foo = {\nbar: 'baz'\n}" output: "foo = {\nbar: 'baz',\n}" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 2 column: 11 ] , code: "foo({ bar: 'baz', qux: 'quux' })" output: "foo({ bar: 'baz', qux: 'quux', })" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 1 column: 30 ] , code: "foo({\nbar: 'baz',\nqux: 'quux'\n})" output: "foo({\nbar: 'baz',\nqux: 'quux',\n})" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 3 column: 12 ] , code: "foo = [ 'baz' ]" output: "foo = [ 'baz', ]" options: ['always'] errors: [ messageId: 'missing' type: 'Literal' line: 1 column: 18 ] , code: "foo = [ 'baz'\n]" output: "foo = [ 'baz',\n]" options: ['always'] errors: [ messageId: 'missing' type: 'Literal' line: 1 column: 18 ] , code: "foo = { bar:\n\n'bar' }" output: "foo = { bar:\n\n'bar', }" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 3 column: 6 ] , code: "foo = {\nbar: 'baz'\n}" output: "foo = {\nbar: 'baz',\n}" options: ['always-multiline'] errors: [ messageId: 'missing' type: 'Property' line: 2 column: 11 ] , code: 'foo = [\n' + ' bar,\n' + ' (\n' + ' baz\n' + ' )\n' + ']' output: 'foo = [\n' + ' bar,\n' + ' (\n' + ' baz\n' + ' ),\n' + ']' options: ['always'] errors: [ messageId: 'missing' type: 'Identifier' line: 5 column: 4 ] , code: 'foo = {\n' + " foo: 'bar',\n" + ' baz: (\n' + ' qux\n' + ' )\n' + '}' output: 'foo = {\n' + " foo: 'bar',\n" + ' baz: (\n' + ' qux\n' + ' ),\n' + '}' options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 5 column: 4 ] , # https://github.com/eslint/eslint/issues/7291 code: 'foo = [\n' + ' (bar\n' + ' ? baz\n' + ' : qux\n' + ' )\n' + ']' output: 'foo = [\n' + ' (bar\n' + ' ? baz\n' + ' : qux\n' + ' ),\n' + ']' options: ['always'] errors: [ messageId: 'missing' type: 'ConditionalExpression' line: 5 column: 4 ] , code: "foo = { bar: 'baz', }" output: "foo = { bar: 'baz' }" options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 23 ] , code: "foo({\nbar: 'baz',\nqux: 'quux'\n})" output: "foo({\nbar: 'baz',\nqux: 'quux',\n})" options: ['always-multiline'] errors: [ messageId: 'missing' type: 'Property' line: 3 column: 12 ] , code: "foo({ bar: 'baz', qux: 'quux', })" output: "foo({ bar: 'baz', qux: 'quux' })" options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 30 ] , code: "foo = [\n'baz'\n]" output: "foo = [\n'baz',\n]" options: ['always-multiline'] errors: [ messageId: 'missing' type: 'Literal' line: 2 column: 6 ] , code: "foo = ['baz',]" output: "foo = ['baz']" options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 17 ] , code: "foo = ['baz',]" output: "foo = ['baz']" options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 17 ] , code: "foo = {x: {\nfoo: 'bar',\n},}" output: "foo = {x: {\nfoo: 'bar',\n}}" options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 3 column: 2 ] , code: 'foo = {a: 1, b: 2,\nc: 3, d: 4,}' output: 'foo = {a: 1, b: 2,\nc: 3, d: 4}' options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 2 column: 11 ] , code: 'foo = {a: 1, b: 2,\nc: 3, d: 4,}' output: 'foo = {a: 1, b: 2,\nc: 3, d: 4}' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 2 column: 11 ] , code: 'foo = [{\na: 1,\nb: 2,\nc: 3,\nd: 4,\n},]' output: 'foo = [{\na: 1,\nb: 2,\nc: 3,\nd: 4,\n}]' options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'ObjectExpression' line: 6 column: 2 ] , code: '{ a, b, } = foo' output: '{ a, b } = foo' options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 11 ] , code: '{ a, b, } = foo' output: '{ a, b } = foo' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 11 ] , code: '[ a, b, ] = foo' output: '[ a, b ] = foo' options: ['never'] errors: [ messageId: 'unexpected' type: 'Identifier' line: 1 column: 11 ] , code: '[ a, b, ] = foo' output: '[ a, b ] = foo' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Identifier' line: 1 column: 11 ] , code: '[(1),]' output: '[(1)]' options: ['never'] errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 5 ] , code: '[(1),]' output: '[(1)]' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 5 ] , code: 'x = { foo: (1),}' output: 'x = { foo: (1)}' options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 19 ] , code: 'x = { foo: (1),}' output: 'x = { foo: (1)}' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 19 ] , # https://github.com/eslint/eslint/issues/3794 code: "import {foo} from 'foo'" output: "import {foo,} from 'foo'" options: ['always'] errors: [messageId: 'missing', type: 'ImportSpecifier'] , code: "import foo, {abc} from 'foo'" output: "import foo, {abc,} from 'foo'" options: ['always'] errors: [messageId: 'missing', type: 'ImportSpecifier'] , code: "export {foo} from 'foo'" output: "export {foo,} from 'foo'" options: ['always'] errors: [messageId: 'missing', type: 'ExportSpecifier'] , code: "import {foo,} from 'foo'" output: "import {foo} from 'foo'" options: ['never'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "import {foo,} from 'foo'" output: "import {foo} from 'foo'" options: ['only-multiline'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "import foo, {abc,} from 'foo'" output: "import foo, {abc} from 'foo'" options: ['never'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "import foo, {abc,} from 'foo'" output: "import foo, {abc} from 'foo'" options: ['only-multiline'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "export {foo,} from 'foo'" output: "export {foo} from 'foo'" options: ['never'] errors: [messageId: 'unexpected', type: 'ExportSpecifier'] , code: "export {foo,} from 'foo'" output: "export {foo} from 'foo'" options: ['only-multiline'] errors: [messageId: 'unexpected', type: 'ExportSpecifier'] , code: "import {foo,} from 'foo'" output: "import {foo} from 'foo'" options: ['always-multiline'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "export {foo,} from 'foo'" output: "export {foo} from 'foo'" options: ['always-multiline'] errors: [messageId: 'unexpected', type: 'ExportSpecifier'] , code: "import {\n foo\n} from 'foo'" output: "import {\n foo,\n} from 'foo'" options: ['always-multiline'] errors: [messageId: 'missing', type: 'ImportSpecifier'] , code: "export {\n foo\n} from 'foo'" output: "export {\n foo,\n} from 'foo'" options: ['always-multiline'] errors: [messageId: 'missing', type: 'ExportSpecifier'] , # https://github.com/eslint/eslint/issues/6233 code: 'foo = {a: (1)}' output: 'foo = {a: (1),}' options: ['always'] errors: [messageId: 'missing', type: 'Property'] , code: 'foo = [(1)]' output: 'foo = [(1),]' options: ['always'] errors: [messageId: 'missing', type: 'Literal'] , code: 'foo = [\n1,\n(2)\n]' output: 'foo = [\n1,\n(2),\n]' options: ['always-multiline'] errors: [messageId: 'missing', type: 'Literal'] , # trailing commas in functions code: 'function foo(a,) {}' output: 'function foo(a) {}' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(function foo(a,) {})' output: '(function foo(a) {})' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(a,) => a' output: '(a) => a' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(a,) => (a)' output: '(a) => (a)' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '({foo(a,) {}})' output: '({foo(a) {}})' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'class A {foo(a,) {}}' output: 'class A {foo(a) {}}' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(a,)' output: 'foo(a)' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(...a,)' output: 'foo(...a)' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'SpreadElement'] , code: 'function foo(a) {}' output: 'function foo(a,) {}' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: '(function foo(a) {})' output: '(function foo(a,) {})' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: '(a) => a' output: '(a,) => a' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: '(a) => (a)' output: '(a,) => (a)' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: '({foo(a) {}})' output: '({foo(a,) {}})' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'class A {foo(a) {}}' output: 'class A {foo(a,) {}}' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'foo(a)' output: 'foo(a,)' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'foo(...a)' output: 'foo(...a,)' options: [functions: 'always'] errors: [messageId: 'missing', type: 'SpreadElement'] , code: 'function foo(a,) {}' output: 'function foo(a) {}' options: [functions: 'always-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(function foo(a,) {})' output: '(function foo(a) {})' options: [functions: 'always-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(a,)' output: 'foo(a)' options: [functions: 'always-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(...a,)' output: 'foo(...a)' options: [functions: 'always-multiline'] errors: [messageId: 'unexpected', type: 'SpreadElement'] , code: 'function foo(\na,\nb\n) {}' output: 'function foo(\na,\nb,\n) {}' options: [functions: 'always-multiline'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'foo(\na,\nb\n)' output: 'foo(\na,\nb,\n)' options: [functions: 'always-multiline'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'foo(\n...a,\n...b\n)' output: 'foo(\n...a,\n...b,\n)' options: [functions: 'always-multiline'] errors: [messageId: 'missing', type: 'SpreadElement'] , code: 'function foo(a,) {}' output: 'function foo(a) {}' options: [functions: 'only-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(function foo(a,) {})' output: '(function foo(a) {})' options: [functions: 'only-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(a,)' output: 'foo(a)' options: [functions: 'only-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(...a,)' output: 'foo(...a)' options: [functions: 'only-multiline'] errors: [messageId: 'unexpected', type: 'SpreadElement'] , # separated options code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a} = {a: 1} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" options: [ objects: 'never' arrays: 'ignore' imports: 'ignore' exports: 'ignore' functions: 'ignore' ] errors: [ messageId: 'unexpected', line: 1 , messageId: 'unexpected', line: 1 ] , code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a,} = {a: 1,} [b] = [1] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" options: [ objects: 'ignore' arrays: 'never' imports: 'ignore' exports: 'ignore' functions: 'ignore' ] errors: [ messageId: 'unexpected', line: 2 , messageId: 'unexpected', line: 2 ] , code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a,} = {a: 1,} [b,] = [1,] import {c} from "foo" export {d,} (function foo(e,) {})(f,)""" options: [ objects: 'ignore' arrays: 'ignore' imports: 'never' exports: 'ignore' functions: 'ignore' ] errors: [messageId: 'unexpected', line: 3] , code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d} (function foo(e,) {})(f,)""" options: [ objects: 'ignore' arrays: 'ignore' imports: 'ignore' exports: 'never' functions: 'ignore' ] errors: [messageId: 'unexpected', line: 4] , code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e) {})(f)""" options: [ objects: 'ignore' arrays: 'ignore' imports: 'ignore' exports: 'ignore' functions: 'never' ] errors: [ messageId: 'unexpected', line: 5 , messageId: 'unexpected', line: 5 ] ] ###
175893
###* # @fileoverview Tests for comma-dangle rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ ### eslint-disable ### rule = require 'eslint/lib/rules/comma-dangle' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Gets the path to the parser of the given name. # # @param {string} name - The name of a parser to get. # @returns {string} The path to the specified parser. ### # parser = (name) -> # path.resolve __dirname, "../../fixtures/parsers/comma-dangle/#{name}.js" #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### ruleTester.run 'comma-dangle', rule, valid: [ "foo = { bar: 'baz' }" "foo = bar: 'baz'" "foo = {\n bar: 'baz'\n}" "foo = [ 'baz' ]" "foo = [\n 'baz'\n]" '[,,]' '[\n,\n,\n]' '[,]' '[\n,\n]' '[]' '[\n]' , code: 'foo = [\n (if bar then baz else qux),\n ]' options: ['always-multiline'] , code: "foo = { bar: 'baz' }", options: ['never'] , code: "foo = {\n bar: 'baz'\n}", options: ['never'] , code: "foo = [ 'baz' ]", options: ['never'] , code: '{ a, b } = foo' options: ['never'] , code: '[ a, b ] = foo' options: ['never'] , code: '{ a,\n b, \n} = foo' options: ['only-multiline'] , code: '[ a,\n b, \n] = foo' options: ['only-multiline'] , code: '[(1),]', options: ['always'] , code: 'x = { foo: (1),}', options: ['always'] , code: "foo = { bar: 'baz', }", options: ['always'] , code: "foo = {\n bar: 'baz',\n}", options: ['always'] , code: "foo = \n bar: 'baz',\n", options: ['always'] , code: "foo = {\n bar: 'baz'\n,}", options: ['always'] , code: "foo = [ 'baz', ]", options: ['always'] , code: "foo = [\n 'baz',\n]", options: ['always'] , code: "foo = [\n 'baz'\n,]", options: ['always'] , code: '[,,]', options: ['always'] , code: '[\n,\n,\n]', options: ['always'] , code: '[,]', options: ['always'] , code: '[\n,\n]', options: ['always'] , code: '[]', options: ['always'] , code: '[\n]', options: ['always'] , code: "foo = { bar: 'baz' }", options: ['always-multiline'] , code: "foo = { bar: 'baz' }", options: ['only-multiline'] , code: "foo = {\nbar: 'baz',\n}", options: ['always-multiline'] , code: "foo = {\nbar: 'baz',\n}", options: ['only-multiline'] , code: "foo = [ 'baz' ]", options: ['always-multiline'] , code: "foo = [ 'baz' ]", options: ['only-multiline'] , code: "foo = [\n 'baz',\n]", options: ['always-multiline'] , code: "foo = [\n 'baz',\n]", options: ['only-multiline'] , code: 'foo = {a: 1, b: 2, c: 3, d: 4}', options: ['always-multiline'] , code: 'foo = {a: 1, b: 2, c: 3, d: 4}', options: ['only-multiline'] , code: 'foo = {a: 1, b: 2,\nc: 3, d: 4}' options: ['always-multiline'] , code: 'foo = {a: 1, b: 2,\nc: 3, d: 4}', options: ['only-multiline'] , code: "foo = {x: {\nfoo: 'bar',\n}}", options: ['always-multiline'] , code: "foo = {x: {\nfoo: 'bar',\n}}", options: ['only-multiline'] , code: 'foo = new Map([\n [key, {\n a: 1,\n b: 2,\n c: 3,\n }],\n])' options: ['always-multiline'] , code: 'foo = new Map([\n [key, {\n a: 1,\n b: 2,\n c: 3,\n }],\n])' options: ['only-multiline'] , # https://github.com/eslint/eslint/issues/3627 code: '[a, ...rest] = []' options: ['always'] , code: '[\n a,\n ...rest\n] = []' options: ['always'] , code: '[\n a,\n ...rest\n] = []' options: ['always-multiline'] , code: '[\n a,\n ...rest\n] = []' options: ['only-multiline'] , code: '[a, ...rest] = []' options: ['always'] , code: 'for [a, ...rest] in [] then ;' options: ['always'] , code: 'a = [b, ...spread,]' options: ['always'] , # https://github.com/eslint/eslint/issues/7297 code: '{foo, ...bar} = baz' options: ['always'] , # https://github.com/eslint/eslint/issues/3794 code: "import {foo,} from 'foo'" options: ['always'] , code: "import foo from 'foo'" options: ['always'] , code: "import foo, {abc,} from 'foo'" options: ['always'] , code: "import * as foo from 'foo'" options: ['always'] , code: "export {foo,} from 'foo'" options: ['always'] , code: "import {foo} from 'foo'" options: ['never'] , code: "import foo from 'foo'" options: ['never'] , code: "import foo, {abc} from 'foo'" options: ['never'] , code: "import * as foo from 'foo'" options: ['never'] , code: "export {foo} from 'foo'" options: ['never'] , code: "import {foo} from 'foo'" options: ['always-multiline'] , code: "import {foo} from 'foo'" options: ['only-multiline'] , code: "export {foo} from 'foo'" options: ['always-multiline'] , code: "export {foo} from 'foo'" options: ['only-multiline'] , code: "import {\n foo,\n} from 'foo'" options: ['always-multiline'] , code: "import {\n foo,\n} from 'foo'" options: ['only-multiline'] , code: "export {\n foo,\n} from 'foo'" options: ['always-multiline'] , code: "export {\n foo,\n} from 'foo'" options: ['only-multiline'] , code: '(a) ->' options: ['always'] , code: '(a) ->' options: ['always'] , code: '(\na,\nb\n) ->' options: ['always-multiline'] , code: 'foo(\na,b)' options: ['always-multiline'] , code: 'foo(a,b,)' options: ['always-multiline'] , # trailing comma in functions code: '(a) ->' options: [functions: 'never'] , code: '(a) ->' options: [functions: 'always'] , code: 'foo(a)' options: [functions: 'never'] , code: '(a, ...b) ->' options: [functions: 'always'] , code: 'foo(a,)' options: [functions: 'always'] , code: 'bar(...a,)' options: [functions: 'always'] , code: '(a) -> ' options: [functions: 'always-multiline'] , code: 'foo(a)' options: [functions: 'always-multiline'] , code: 'foo a' options: [functions: 'always-multiline'] , code: '(\na,\nb,\n) -> ' options: [functions: 'always-multiline'] , code: '(\na,\n...b\n) -> ' options: [functions: 'always-multiline'] , code: 'foo(\na,\nb,\n)' options: [functions: 'always-multiline'] , code: 'foo(\na,\n...b,\n)' options: [functions: 'always-multiline'] , code: 'function foo(a) {} ' options: [functions: 'only-multiline'] , code: 'foo(a)' options: [functions: 'only-multiline'] , code: 'function foo(\na,\nb,\n) {} ' options: [functions: 'only-multiline'] , code: 'foo(\na,\nb,\n)' options: [functions: 'only-multiline'] , code: 'function foo(\na,\nb\n) {} ' options: [functions: 'only-multiline'] , code: 'foo(\na,\nb\n)' options: [functions: 'only-multiline'] ] invalid: [ code: "foo = { bar: 'baz', }" output: "foo = { bar: 'baz' }" errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 23 ] , code: "foo = {\nbar: 'baz',\n}" output: "foo = {\nbar: 'baz'\n}" errors: [ messageId: 'unexpected' type: 'Property' line: 2 column: 11 ] , code: "foo({ bar: 'baz', qux: 'quux', })" output: "foo({ bar: 'baz', qux: 'quux' })" errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 30 ] , code: "foo({\nbar: 'baz',\nqux: 'quux',\n})" output: "foo({\nbar: 'baz',\nqux: 'quux'\n})" errors: [ messageId: 'unexpected' type: 'Property' line: 3 column: 12 ] , code: "foo = [ 'baz', ]" output: "foo = [ 'baz' ]" errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 18 ] , code: "foo = [ 'baz',\n]" output: "foo = [ 'baz'\n]" errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 18 ] , code: "foo = { bar: 'bar'\n\n, }" output: "foo = { bar: 'bar'\n\n }" errors: [ messageId: 'unexpected' type: 'Property' line: 3 column: 1 ] , code: "foo = { bar: 'baz', }" output: "foo = { bar: 'baz' }" options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 23 ] , code: "foo = { bar: 'baz', }" output: "foo = { bar: 'baz' }" options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 23 ] , code: "foo = {\nbar: 'baz',\n}" output: "foo = {\nbar: 'baz'\n}" options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 2 column: 11 ] , code: "foo({ bar: 'baz', qux: 'quux', })" output: "foo({ bar: 'baz', qux: 'quux' })" options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 30 ] , code: "foo({ bar: 'baz', qux: 'quux', })" output: "foo({ bar: 'baz', qux: 'quux' })" options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 30 ] , code: "foo = { bar: 'baz' }" output: "foo = { bar: 'baz', }" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 1 column: 23 ] , code: "foo = {\nbar: 'baz'\n}" output: "foo = {\nbar: 'baz',\n}" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 2 column: 11 ] , code: "foo({ bar: 'baz', qux: 'quux' })" output: "foo({ bar: 'baz', qux: 'quux', })" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 1 column: 30 ] , code: "foo({\nbar: 'baz',\nqux: 'quux'\n})" output: "foo({\nbar: 'baz',\nqux: 'quux',\n})" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 3 column: 12 ] , code: "foo = [ 'baz' ]" output: "foo = [ 'baz', ]" options: ['always'] errors: [ messageId: 'missing' type: 'Literal' line: 1 column: 18 ] , code: "foo = [ 'baz'\n]" output: "foo = [ 'baz',\n]" options: ['always'] errors: [ messageId: 'missing' type: 'Literal' line: 1 column: 18 ] , code: "foo = { bar:\n\n'bar' }" output: "foo = { bar:\n\n'bar', }" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 3 column: 6 ] , code: "foo = {\nbar: 'baz'\n}" output: "foo = {\nbar: 'baz',\n}" options: ['always-multiline'] errors: [ messageId: 'missing' type: 'Property' line: 2 column: 11 ] , code: 'foo = [\n' + ' bar,\n' + ' (\n' + ' baz\n' + ' )\n' + ']' output: 'foo = [\n' + ' bar,\n' + ' (\n' + ' baz\n' + ' ),\n' + ']' options: ['always'] errors: [ messageId: 'missing' type: 'Identifier' line: 5 column: 4 ] , code: 'foo = {\n' + " foo: 'bar',\n" + ' baz: (\n' + ' qux\n' + ' )\n' + '}' output: 'foo = {\n' + " foo: 'bar',\n" + ' baz: (\n' + ' qux\n' + ' ),\n' + '}' options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 5 column: 4 ] , # https://github.com/eslint/eslint/issues/7291 code: 'foo = [\n' + ' (bar\n' + ' ? baz\n' + ' : qux\n' + ' )\n' + ']' output: 'foo = [\n' + ' (bar\n' + ' ? baz\n' + ' : qux\n' + ' ),\n' + ']' options: ['always'] errors: [ messageId: 'missing' type: 'ConditionalExpression' line: 5 column: 4 ] , code: "foo = { bar: 'baz', }" output: "foo = { bar: 'baz' }" options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 23 ] , code: "foo({\nbar: 'baz',\nqux: 'quux'\n})" output: "foo({\nbar: 'baz',\nqux: 'quux',\n})" options: ['always-multiline'] errors: [ messageId: 'missing' type: 'Property' line: 3 column: 12 ] , code: "foo({ bar: 'baz', qux: 'quux', })" output: "foo({ bar: 'baz', qux: 'quux' })" options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 30 ] , code: "foo = [\n'baz'\n]" output: "foo = [\n'baz',\n]" options: ['always-multiline'] errors: [ messageId: 'missing' type: 'Literal' line: 2 column: 6 ] , code: "foo = ['baz',]" output: "foo = ['baz']" options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 17 ] , code: "foo = ['baz',]" output: "foo = ['baz']" options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 17 ] , code: "foo = {x: {\nfoo: 'bar',\n},}" output: "foo = {x: {\nfoo: 'bar',\n}}" options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 3 column: 2 ] , code: 'foo = {a: 1, b: 2,\nc: 3, d: 4,}' output: 'foo = {a: 1, b: 2,\nc: 3, d: 4}' options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 2 column: 11 ] , code: 'foo = {a: 1, b: 2,\nc: 3, d: 4,}' output: 'foo = {a: 1, b: 2,\nc: 3, d: 4}' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 2 column: 11 ] , code: 'foo = [{\na: 1,\nb: 2,\nc: 3,\nd: 4,\n},]' output: 'foo = [{\na: 1,\nb: 2,\nc: 3,\nd: 4,\n}]' options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'ObjectExpression' line: 6 column: 2 ] , code: '{ a, b, } = foo' output: '{ a, b } = foo' options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 11 ] , code: '{ a, b, } = foo' output: '{ a, b } = foo' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 11 ] , code: '[ a, b, ] = foo' output: '[ a, b ] = foo' options: ['never'] errors: [ messageId: 'unexpected' type: 'Identifier' line: 1 column: 11 ] , code: '[ a, b, ] = foo' output: '[ a, b ] = foo' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Identifier' line: 1 column: 11 ] , code: '[(1),]' output: '[(1)]' options: ['never'] errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 5 ] , code: '[(1),]' output: '[(1)]' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 5 ] , code: 'x = { foo: (1),}' output: 'x = { foo: (1)}' options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 19 ] , code: 'x = { foo: (1),}' output: 'x = { foo: (1)}' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 19 ] , # https://github.com/eslint/eslint/issues/3794 code: "import {foo} from 'foo'" output: "import {foo,} from 'foo'" options: ['always'] errors: [messageId: 'missing', type: 'ImportSpecifier'] , code: "import foo, {abc} from 'foo'" output: "import foo, {abc,} from 'foo'" options: ['always'] errors: [messageId: 'missing', type: 'ImportSpecifier'] , code: "export {foo} from 'foo'" output: "export {foo,} from 'foo'" options: ['always'] errors: [messageId: 'missing', type: 'ExportSpecifier'] , code: "import {foo,} from 'foo'" output: "import {foo} from 'foo'" options: ['never'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "import {foo,} from 'foo'" output: "import {foo} from 'foo'" options: ['only-multiline'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "import foo, {abc,} from 'foo'" output: "import foo, {abc} from 'foo'" options: ['never'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "import foo, {abc,} from 'foo'" output: "import foo, {abc} from 'foo'" options: ['only-multiline'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "export {foo,} from 'foo'" output: "export {foo} from 'foo'" options: ['never'] errors: [messageId: 'unexpected', type: 'ExportSpecifier'] , code: "export {foo,} from 'foo'" output: "export {foo} from 'foo'" options: ['only-multiline'] errors: [messageId: 'unexpected', type: 'ExportSpecifier'] , code: "import {foo,} from 'foo'" output: "import {foo} from 'foo'" options: ['always-multiline'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "export {foo,} from 'foo'" output: "export {foo} from 'foo'" options: ['always-multiline'] errors: [messageId: 'unexpected', type: 'ExportSpecifier'] , code: "import {\n foo\n} from 'foo'" output: "import {\n foo,\n} from 'foo'" options: ['always-multiline'] errors: [messageId: 'missing', type: 'ImportSpecifier'] , code: "export {\n foo\n} from 'foo'" output: "export {\n foo,\n} from 'foo'" options: ['always-multiline'] errors: [messageId: 'missing', type: 'ExportSpecifier'] , # https://github.com/eslint/eslint/issues/6233 code: 'foo = {a: (1)}' output: 'foo = {a: (1),}' options: ['always'] errors: [messageId: 'missing', type: 'Property'] , code: 'foo = [(1)]' output: 'foo = [(1),]' options: ['always'] errors: [messageId: 'missing', type: 'Literal'] , code: 'foo = [\n1,\n(2)\n]' output: 'foo = [\n1,\n(2),\n]' options: ['always-multiline'] errors: [messageId: 'missing', type: 'Literal'] , # trailing commas in functions code: 'function foo(a,) {}' output: 'function foo(a) {}' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(function foo(a,) {})' output: '(function foo(a) {})' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(a,) => a' output: '(a) => a' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(a,) => (a)' output: '(a) => (a)' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '({foo(a,) {}})' output: '({foo(a) {}})' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'class A {foo(a,) {}}' output: 'class A {foo(a) {}}' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(a,)' output: 'foo(a)' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(...a,)' output: 'foo(...a)' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'SpreadElement'] , code: 'function foo(a) {}' output: 'function foo(a,) {}' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: '(function foo(a) {})' output: '(function foo(a,) {})' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: '(a) => a' output: '(a,) => a' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: '(a) => (a)' output: '(a,) => (a)' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: '({foo(a) {}})' output: '({foo(a,) {}})' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'class A {foo(a) {}}' output: 'class A {foo(a,) {}}' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'foo(a)' output: 'foo(a,)' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'foo(...a)' output: 'foo(...a,)' options: [functions: 'always'] errors: [messageId: 'missing', type: 'SpreadElement'] , code: 'function foo(a,) {}' output: 'function foo(a) {}' options: [functions: 'always-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(function foo(a,) {})' output: '(function foo(a) {})' options: [functions: 'always-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(a,)' output: 'foo(a)' options: [functions: 'always-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(...a,)' output: 'foo(...a)' options: [functions: 'always-multiline'] errors: [messageId: 'unexpected', type: 'SpreadElement'] , code: 'function foo(\na,\nb\n) {}' output: 'function foo(\na,\nb,\n) {}' options: [functions: 'always-multiline'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'foo(\na,\nb\n)' output: 'foo(\na,\nb,\n)' options: [functions: 'always-multiline'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'foo(\n...a,\n...b\n)' output: 'foo(\n...a,\n...b,\n)' options: [functions: 'always-multiline'] errors: [messageId: 'missing', type: 'SpreadElement'] , code: 'function foo(a,) {}' output: 'function foo(a) {}' options: [functions: 'only-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(function foo(a,) {})' output: '(function foo(a) {})' options: [functions: 'only-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(a,)' output: 'foo(a)' options: [functions: 'only-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(...a,)' output: 'foo(...a)' options: [functions: 'only-multiline'] errors: [messageId: 'unexpected', type: 'SpreadElement'] , # separated options code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a} = {a: 1} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" options: [ objects: 'never' arrays: 'ignore' imports: 'ignore' exports: 'ignore' functions: 'ignore' ] errors: [ messageId: 'unexpected', line: 1 , messageId: 'unexpected', line: 1 ] , code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a,} = {a: 1,} [b] = [1] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" options: [ objects: 'ignore' arrays: 'never' imports: 'ignore' exports: 'ignore' functions: 'ignore' ] errors: [ messageId: 'unexpected', line: 2 , messageId: 'unexpected', line: 2 ] , code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a,} = {a: 1,} [b,] = [1,] import {c} from "foo" export {d,} (function foo(e,) {})(f,)""" options: [ objects: 'ignore' arrays: 'ignore' imports: 'never' exports: 'ignore' functions: 'ignore' ] errors: [messageId: 'unexpected', line: 3] , code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d} (function foo(e,) {})(f,)""" options: [ objects: 'ignore' arrays: 'ignore' imports: 'ignore' exports: 'never' functions: 'ignore' ] errors: [messageId: 'unexpected', line: 4] , code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e) {})(f)""" options: [ objects: 'ignore' arrays: 'ignore' imports: 'ignore' exports: 'ignore' functions: 'never' ] errors: [ messageId: 'unexpected', line: 5 , messageId: 'unexpected', line: 5 ] ] ###
true
###* # @fileoverview Tests for comma-dangle rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ ### eslint-disable ### rule = require 'eslint/lib/rules/comma-dangle' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Gets the path to the parser of the given name. # # @param {string} name - The name of a parser to get. # @returns {string} The path to the specified parser. ### # parser = (name) -> # path.resolve __dirname, "../../fixtures/parsers/comma-dangle/#{name}.js" #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### ruleTester.run 'comma-dangle', rule, valid: [ "foo = { bar: 'baz' }" "foo = bar: 'baz'" "foo = {\n bar: 'baz'\n}" "foo = [ 'baz' ]" "foo = [\n 'baz'\n]" '[,,]' '[\n,\n,\n]' '[,]' '[\n,\n]' '[]' '[\n]' , code: 'foo = [\n (if bar then baz else qux),\n ]' options: ['always-multiline'] , code: "foo = { bar: 'baz' }", options: ['never'] , code: "foo = {\n bar: 'baz'\n}", options: ['never'] , code: "foo = [ 'baz' ]", options: ['never'] , code: '{ a, b } = foo' options: ['never'] , code: '[ a, b ] = foo' options: ['never'] , code: '{ a,\n b, \n} = foo' options: ['only-multiline'] , code: '[ a,\n b, \n] = foo' options: ['only-multiline'] , code: '[(1),]', options: ['always'] , code: 'x = { foo: (1),}', options: ['always'] , code: "foo = { bar: 'baz', }", options: ['always'] , code: "foo = {\n bar: 'baz',\n}", options: ['always'] , code: "foo = \n bar: 'baz',\n", options: ['always'] , code: "foo = {\n bar: 'baz'\n,}", options: ['always'] , code: "foo = [ 'baz', ]", options: ['always'] , code: "foo = [\n 'baz',\n]", options: ['always'] , code: "foo = [\n 'baz'\n,]", options: ['always'] , code: '[,,]', options: ['always'] , code: '[\n,\n,\n]', options: ['always'] , code: '[,]', options: ['always'] , code: '[\n,\n]', options: ['always'] , code: '[]', options: ['always'] , code: '[\n]', options: ['always'] , code: "foo = { bar: 'baz' }", options: ['always-multiline'] , code: "foo = { bar: 'baz' }", options: ['only-multiline'] , code: "foo = {\nbar: 'baz',\n}", options: ['always-multiline'] , code: "foo = {\nbar: 'baz',\n}", options: ['only-multiline'] , code: "foo = [ 'baz' ]", options: ['always-multiline'] , code: "foo = [ 'baz' ]", options: ['only-multiline'] , code: "foo = [\n 'baz',\n]", options: ['always-multiline'] , code: "foo = [\n 'baz',\n]", options: ['only-multiline'] , code: 'foo = {a: 1, b: 2, c: 3, d: 4}', options: ['always-multiline'] , code: 'foo = {a: 1, b: 2, c: 3, d: 4}', options: ['only-multiline'] , code: 'foo = {a: 1, b: 2,\nc: 3, d: 4}' options: ['always-multiline'] , code: 'foo = {a: 1, b: 2,\nc: 3, d: 4}', options: ['only-multiline'] , code: "foo = {x: {\nfoo: 'bar',\n}}", options: ['always-multiline'] , code: "foo = {x: {\nfoo: 'bar',\n}}", options: ['only-multiline'] , code: 'foo = new Map([\n [key, {\n a: 1,\n b: 2,\n c: 3,\n }],\n])' options: ['always-multiline'] , code: 'foo = new Map([\n [key, {\n a: 1,\n b: 2,\n c: 3,\n }],\n])' options: ['only-multiline'] , # https://github.com/eslint/eslint/issues/3627 code: '[a, ...rest] = []' options: ['always'] , code: '[\n a,\n ...rest\n] = []' options: ['always'] , code: '[\n a,\n ...rest\n] = []' options: ['always-multiline'] , code: '[\n a,\n ...rest\n] = []' options: ['only-multiline'] , code: '[a, ...rest] = []' options: ['always'] , code: 'for [a, ...rest] in [] then ;' options: ['always'] , code: 'a = [b, ...spread,]' options: ['always'] , # https://github.com/eslint/eslint/issues/7297 code: '{foo, ...bar} = baz' options: ['always'] , # https://github.com/eslint/eslint/issues/3794 code: "import {foo,} from 'foo'" options: ['always'] , code: "import foo from 'foo'" options: ['always'] , code: "import foo, {abc,} from 'foo'" options: ['always'] , code: "import * as foo from 'foo'" options: ['always'] , code: "export {foo,} from 'foo'" options: ['always'] , code: "import {foo} from 'foo'" options: ['never'] , code: "import foo from 'foo'" options: ['never'] , code: "import foo, {abc} from 'foo'" options: ['never'] , code: "import * as foo from 'foo'" options: ['never'] , code: "export {foo} from 'foo'" options: ['never'] , code: "import {foo} from 'foo'" options: ['always-multiline'] , code: "import {foo} from 'foo'" options: ['only-multiline'] , code: "export {foo} from 'foo'" options: ['always-multiline'] , code: "export {foo} from 'foo'" options: ['only-multiline'] , code: "import {\n foo,\n} from 'foo'" options: ['always-multiline'] , code: "import {\n foo,\n} from 'foo'" options: ['only-multiline'] , code: "export {\n foo,\n} from 'foo'" options: ['always-multiline'] , code: "export {\n foo,\n} from 'foo'" options: ['only-multiline'] , code: '(a) ->' options: ['always'] , code: '(a) ->' options: ['always'] , code: '(\na,\nb\n) ->' options: ['always-multiline'] , code: 'foo(\na,b)' options: ['always-multiline'] , code: 'foo(a,b,)' options: ['always-multiline'] , # trailing comma in functions code: '(a) ->' options: [functions: 'never'] , code: '(a) ->' options: [functions: 'always'] , code: 'foo(a)' options: [functions: 'never'] , code: '(a, ...b) ->' options: [functions: 'always'] , code: 'foo(a,)' options: [functions: 'always'] , code: 'bar(...a,)' options: [functions: 'always'] , code: '(a) -> ' options: [functions: 'always-multiline'] , code: 'foo(a)' options: [functions: 'always-multiline'] , code: 'foo a' options: [functions: 'always-multiline'] , code: '(\na,\nb,\n) -> ' options: [functions: 'always-multiline'] , code: '(\na,\n...b\n) -> ' options: [functions: 'always-multiline'] , code: 'foo(\na,\nb,\n)' options: [functions: 'always-multiline'] , code: 'foo(\na,\n...b,\n)' options: [functions: 'always-multiline'] , code: 'function foo(a) {} ' options: [functions: 'only-multiline'] , code: 'foo(a)' options: [functions: 'only-multiline'] , code: 'function foo(\na,\nb,\n) {} ' options: [functions: 'only-multiline'] , code: 'foo(\na,\nb,\n)' options: [functions: 'only-multiline'] , code: 'function foo(\na,\nb\n) {} ' options: [functions: 'only-multiline'] , code: 'foo(\na,\nb\n)' options: [functions: 'only-multiline'] ] invalid: [ code: "foo = { bar: 'baz', }" output: "foo = { bar: 'baz' }" errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 23 ] , code: "foo = {\nbar: 'baz',\n}" output: "foo = {\nbar: 'baz'\n}" errors: [ messageId: 'unexpected' type: 'Property' line: 2 column: 11 ] , code: "foo({ bar: 'baz', qux: 'quux', })" output: "foo({ bar: 'baz', qux: 'quux' })" errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 30 ] , code: "foo({\nbar: 'baz',\nqux: 'quux',\n})" output: "foo({\nbar: 'baz',\nqux: 'quux'\n})" errors: [ messageId: 'unexpected' type: 'Property' line: 3 column: 12 ] , code: "foo = [ 'baz', ]" output: "foo = [ 'baz' ]" errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 18 ] , code: "foo = [ 'baz',\n]" output: "foo = [ 'baz'\n]" errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 18 ] , code: "foo = { bar: 'bar'\n\n, }" output: "foo = { bar: 'bar'\n\n }" errors: [ messageId: 'unexpected' type: 'Property' line: 3 column: 1 ] , code: "foo = { bar: 'baz', }" output: "foo = { bar: 'baz' }" options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 23 ] , code: "foo = { bar: 'baz', }" output: "foo = { bar: 'baz' }" options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 23 ] , code: "foo = {\nbar: 'baz',\n}" output: "foo = {\nbar: 'baz'\n}" options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 2 column: 11 ] , code: "foo({ bar: 'baz', qux: 'quux', })" output: "foo({ bar: 'baz', qux: 'quux' })" options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 30 ] , code: "foo({ bar: 'baz', qux: 'quux', })" output: "foo({ bar: 'baz', qux: 'quux' })" options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 30 ] , code: "foo = { bar: 'baz' }" output: "foo = { bar: 'baz', }" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 1 column: 23 ] , code: "foo = {\nbar: 'baz'\n}" output: "foo = {\nbar: 'baz',\n}" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 2 column: 11 ] , code: "foo({ bar: 'baz', qux: 'quux' })" output: "foo({ bar: 'baz', qux: 'quux', })" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 1 column: 30 ] , code: "foo({\nbar: 'baz',\nqux: 'quux'\n})" output: "foo({\nbar: 'baz',\nqux: 'quux',\n})" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 3 column: 12 ] , code: "foo = [ 'baz' ]" output: "foo = [ 'baz', ]" options: ['always'] errors: [ messageId: 'missing' type: 'Literal' line: 1 column: 18 ] , code: "foo = [ 'baz'\n]" output: "foo = [ 'baz',\n]" options: ['always'] errors: [ messageId: 'missing' type: 'Literal' line: 1 column: 18 ] , code: "foo = { bar:\n\n'bar' }" output: "foo = { bar:\n\n'bar', }" options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 3 column: 6 ] , code: "foo = {\nbar: 'baz'\n}" output: "foo = {\nbar: 'baz',\n}" options: ['always-multiline'] errors: [ messageId: 'missing' type: 'Property' line: 2 column: 11 ] , code: 'foo = [\n' + ' bar,\n' + ' (\n' + ' baz\n' + ' )\n' + ']' output: 'foo = [\n' + ' bar,\n' + ' (\n' + ' baz\n' + ' ),\n' + ']' options: ['always'] errors: [ messageId: 'missing' type: 'Identifier' line: 5 column: 4 ] , code: 'foo = {\n' + " foo: 'bar',\n" + ' baz: (\n' + ' qux\n' + ' )\n' + '}' output: 'foo = {\n' + " foo: 'bar',\n" + ' baz: (\n' + ' qux\n' + ' ),\n' + '}' options: ['always'] errors: [ messageId: 'missing' type: 'Property' line: 5 column: 4 ] , # https://github.com/eslint/eslint/issues/7291 code: 'foo = [\n' + ' (bar\n' + ' ? baz\n' + ' : qux\n' + ' )\n' + ']' output: 'foo = [\n' + ' (bar\n' + ' ? baz\n' + ' : qux\n' + ' ),\n' + ']' options: ['always'] errors: [ messageId: 'missing' type: 'ConditionalExpression' line: 5 column: 4 ] , code: "foo = { bar: 'baz', }" output: "foo = { bar: 'baz' }" options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 23 ] , code: "foo({\nbar: 'baz',\nqux: 'quux'\n})" output: "foo({\nbar: 'baz',\nqux: 'quux',\n})" options: ['always-multiline'] errors: [ messageId: 'missing' type: 'Property' line: 3 column: 12 ] , code: "foo({ bar: 'baz', qux: 'quux', })" output: "foo({ bar: 'baz', qux: 'quux' })" options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 30 ] , code: "foo = [\n'baz'\n]" output: "foo = [\n'baz',\n]" options: ['always-multiline'] errors: [ messageId: 'missing' type: 'Literal' line: 2 column: 6 ] , code: "foo = ['baz',]" output: "foo = ['baz']" options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 17 ] , code: "foo = ['baz',]" output: "foo = ['baz']" options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 17 ] , code: "foo = {x: {\nfoo: 'bar',\n},}" output: "foo = {x: {\nfoo: 'bar',\n}}" options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 3 column: 2 ] , code: 'foo = {a: 1, b: 2,\nc: 3, d: 4,}' output: 'foo = {a: 1, b: 2,\nc: 3, d: 4}' options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 2 column: 11 ] , code: 'foo = {a: 1, b: 2,\nc: 3, d: 4,}' output: 'foo = {a: 1, b: 2,\nc: 3, d: 4}' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 2 column: 11 ] , code: 'foo = [{\na: 1,\nb: 2,\nc: 3,\nd: 4,\n},]' output: 'foo = [{\na: 1,\nb: 2,\nc: 3,\nd: 4,\n}]' options: ['always-multiline'] errors: [ messageId: 'unexpected' type: 'ObjectExpression' line: 6 column: 2 ] , code: '{ a, b, } = foo' output: '{ a, b } = foo' options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 11 ] , code: '{ a, b, } = foo' output: '{ a, b } = foo' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 11 ] , code: '[ a, b, ] = foo' output: '[ a, b ] = foo' options: ['never'] errors: [ messageId: 'unexpected' type: 'Identifier' line: 1 column: 11 ] , code: '[ a, b, ] = foo' output: '[ a, b ] = foo' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Identifier' line: 1 column: 11 ] , code: '[(1),]' output: '[(1)]' options: ['never'] errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 5 ] , code: '[(1),]' output: '[(1)]' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Literal' line: 1 column: 5 ] , code: 'x = { foo: (1),}' output: 'x = { foo: (1)}' options: ['never'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 19 ] , code: 'x = { foo: (1),}' output: 'x = { foo: (1)}' options: ['only-multiline'] errors: [ messageId: 'unexpected' type: 'Property' line: 1 column: 19 ] , # https://github.com/eslint/eslint/issues/3794 code: "import {foo} from 'foo'" output: "import {foo,} from 'foo'" options: ['always'] errors: [messageId: 'missing', type: 'ImportSpecifier'] , code: "import foo, {abc} from 'foo'" output: "import foo, {abc,} from 'foo'" options: ['always'] errors: [messageId: 'missing', type: 'ImportSpecifier'] , code: "export {foo} from 'foo'" output: "export {foo,} from 'foo'" options: ['always'] errors: [messageId: 'missing', type: 'ExportSpecifier'] , code: "import {foo,} from 'foo'" output: "import {foo} from 'foo'" options: ['never'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "import {foo,} from 'foo'" output: "import {foo} from 'foo'" options: ['only-multiline'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "import foo, {abc,} from 'foo'" output: "import foo, {abc} from 'foo'" options: ['never'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "import foo, {abc,} from 'foo'" output: "import foo, {abc} from 'foo'" options: ['only-multiline'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "export {foo,} from 'foo'" output: "export {foo} from 'foo'" options: ['never'] errors: [messageId: 'unexpected', type: 'ExportSpecifier'] , code: "export {foo,} from 'foo'" output: "export {foo} from 'foo'" options: ['only-multiline'] errors: [messageId: 'unexpected', type: 'ExportSpecifier'] , code: "import {foo,} from 'foo'" output: "import {foo} from 'foo'" options: ['always-multiline'] errors: [messageId: 'unexpected', type: 'ImportSpecifier'] , code: "export {foo,} from 'foo'" output: "export {foo} from 'foo'" options: ['always-multiline'] errors: [messageId: 'unexpected', type: 'ExportSpecifier'] , code: "import {\n foo\n} from 'foo'" output: "import {\n foo,\n} from 'foo'" options: ['always-multiline'] errors: [messageId: 'missing', type: 'ImportSpecifier'] , code: "export {\n foo\n} from 'foo'" output: "export {\n foo,\n} from 'foo'" options: ['always-multiline'] errors: [messageId: 'missing', type: 'ExportSpecifier'] , # https://github.com/eslint/eslint/issues/6233 code: 'foo = {a: (1)}' output: 'foo = {a: (1),}' options: ['always'] errors: [messageId: 'missing', type: 'Property'] , code: 'foo = [(1)]' output: 'foo = [(1),]' options: ['always'] errors: [messageId: 'missing', type: 'Literal'] , code: 'foo = [\n1,\n(2)\n]' output: 'foo = [\n1,\n(2),\n]' options: ['always-multiline'] errors: [messageId: 'missing', type: 'Literal'] , # trailing commas in functions code: 'function foo(a,) {}' output: 'function foo(a) {}' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(function foo(a,) {})' output: '(function foo(a) {})' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(a,) => a' output: '(a) => a' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(a,) => (a)' output: '(a) => (a)' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '({foo(a,) {}})' output: '({foo(a) {}})' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'class A {foo(a,) {}}' output: 'class A {foo(a) {}}' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(a,)' output: 'foo(a)' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(...a,)' output: 'foo(...a)' options: [functions: 'never'] errors: [messageId: 'unexpected', type: 'SpreadElement'] , code: 'function foo(a) {}' output: 'function foo(a,) {}' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: '(function foo(a) {})' output: '(function foo(a,) {})' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: '(a) => a' output: '(a,) => a' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: '(a) => (a)' output: '(a,) => (a)' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: '({foo(a) {}})' output: '({foo(a,) {}})' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'class A {foo(a) {}}' output: 'class A {foo(a,) {}}' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'foo(a)' output: 'foo(a,)' options: [functions: 'always'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'foo(...a)' output: 'foo(...a,)' options: [functions: 'always'] errors: [messageId: 'missing', type: 'SpreadElement'] , code: 'function foo(a,) {}' output: 'function foo(a) {}' options: [functions: 'always-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(function foo(a,) {})' output: '(function foo(a) {})' options: [functions: 'always-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(a,)' output: 'foo(a)' options: [functions: 'always-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(...a,)' output: 'foo(...a)' options: [functions: 'always-multiline'] errors: [messageId: 'unexpected', type: 'SpreadElement'] , code: 'function foo(\na,\nb\n) {}' output: 'function foo(\na,\nb,\n) {}' options: [functions: 'always-multiline'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'foo(\na,\nb\n)' output: 'foo(\na,\nb,\n)' options: [functions: 'always-multiline'] errors: [messageId: 'missing', type: 'Identifier'] , code: 'foo(\n...a,\n...b\n)' output: 'foo(\n...a,\n...b,\n)' options: [functions: 'always-multiline'] errors: [messageId: 'missing', type: 'SpreadElement'] , code: 'function foo(a,) {}' output: 'function foo(a) {}' options: [functions: 'only-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: '(function foo(a,) {})' output: '(function foo(a) {})' options: [functions: 'only-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(a,)' output: 'foo(a)' options: [functions: 'only-multiline'] errors: [messageId: 'unexpected', type: 'Identifier'] , code: 'foo(...a,)' output: 'foo(...a)' options: [functions: 'only-multiline'] errors: [messageId: 'unexpected', type: 'SpreadElement'] , # separated options code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a} = {a: 1} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" options: [ objects: 'never' arrays: 'ignore' imports: 'ignore' exports: 'ignore' functions: 'ignore' ] errors: [ messageId: 'unexpected', line: 1 , messageId: 'unexpected', line: 1 ] , code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a,} = {a: 1,} [b] = [1] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" options: [ objects: 'ignore' arrays: 'never' imports: 'ignore' exports: 'ignore' functions: 'ignore' ] errors: [ messageId: 'unexpected', line: 2 , messageId: 'unexpected', line: 2 ] , code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a,} = {a: 1,} [b,] = [1,] import {c} from "foo" export {d,} (function foo(e,) {})(f,)""" options: [ objects: 'ignore' arrays: 'ignore' imports: 'never' exports: 'ignore' functions: 'ignore' ] errors: [messageId: 'unexpected', line: 3] , code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d} (function foo(e,) {})(f,)""" options: [ objects: 'ignore' arrays: 'ignore' imports: 'ignore' exports: 'never' functions: 'ignore' ] errors: [messageId: 'unexpected', line: 4] , code: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e,) {})(f,)""" output: """{a,} = {a: 1,} [b,] = [1,] import {c,} from "foo" export {d,} (function foo(e) {})(f)""" options: [ objects: 'ignore' arrays: 'ignore' imports: 'ignore' exports: 'ignore' functions: 'never' ] errors: [ messageId: 'unexpected', line: 5 , messageId: 'unexpected', line: 5 ] ] ###
[ { "context": "tabIndex value is not greater than zero.\n# @author Ethan Cohen\n###\n\n# ------------------------------------------", "end": 115, "score": 0.9998646974563599, "start": 104, "tag": "NAME", "value": "Ethan Cohen" } ]
src/tests/rules/tabindex-no-positive.coffee
danielbayley/eslint-plugin-coffee
21
### eslint-env jest ### ###* # @fileoverview Enforce tabIndex value is not greater than zero. # @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/tabindex-no-positive' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedError = message: 'Avoid positive integer values for tabIndex.' type: 'JSXAttribute' ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'tabindex-no-positive', rule, valid: [ code: '<div />' , code: '<div {...props} />' , code: '<div id="main" />' , code: '<div tabIndex={undefined} />' , code: '<div tabIndex={"#{undefined}"} />' , code: '<div tabIndex={"#{undefined}#{undefined}"} />' , code: '<div tabIndex={0} />' , code: '<div tabIndex={-1} />' , code: '<div tabIndex={null} />' , code: '<div tabIndex={bar()} />' , code: '<div tabIndex={bar} />' , code: '<div tabIndex={"foobar"} />' , code: '<div tabIndex="0" />' , code: '<div tabIndex="-1" />' , code: '<div tabIndex="-5" />' , code: '<div tabIndex="-5.5" />' , code: '<div tabIndex={-5.5} />' , code: '<div tabIndex={-5} />' ].map parserOptionsMapper invalid: [ code: '<div tabIndex="1" />', errors: [expectedError] , code: '<div tabIndex={1} />', errors: [expectedError] , code: '<div tabIndex={"1"} />', errors: [expectedError] , code: '<div tabIndex={1.589} />', errors: [expectedError] ].map parserOptionsMapper
132455
### eslint-env jest ### ###* # @fileoverview Enforce tabIndex value is not greater than zero. # @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/tabindex-no-positive' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedError = message: 'Avoid positive integer values for tabIndex.' type: 'JSXAttribute' ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'tabindex-no-positive', rule, valid: [ code: '<div />' , code: '<div {...props} />' , code: '<div id="main" />' , code: '<div tabIndex={undefined} />' , code: '<div tabIndex={"#{undefined}"} />' , code: '<div tabIndex={"#{undefined}#{undefined}"} />' , code: '<div tabIndex={0} />' , code: '<div tabIndex={-1} />' , code: '<div tabIndex={null} />' , code: '<div tabIndex={bar()} />' , code: '<div tabIndex={bar} />' , code: '<div tabIndex={"foobar"} />' , code: '<div tabIndex="0" />' , code: '<div tabIndex="-1" />' , code: '<div tabIndex="-5" />' , code: '<div tabIndex="-5.5" />' , code: '<div tabIndex={-5.5} />' , code: '<div tabIndex={-5} />' ].map parserOptionsMapper invalid: [ code: '<div tabIndex="1" />', errors: [expectedError] , code: '<div tabIndex={1} />', errors: [expectedError] , code: '<div tabIndex={"1"} />', errors: [expectedError] , code: '<div tabIndex={1.589} />', errors: [expectedError] ].map parserOptionsMapper
true
### eslint-env jest ### ###* # @fileoverview Enforce tabIndex value is not greater than zero. # @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/tabindex-no-positive' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedError = message: 'Avoid positive integer values for tabIndex.' type: 'JSXAttribute' ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'tabindex-no-positive', rule, valid: [ code: '<div />' , code: '<div {...props} />' , code: '<div id="main" />' , code: '<div tabIndex={undefined} />' , code: '<div tabIndex={"#{undefined}"} />' , code: '<div tabIndex={"#{undefined}#{undefined}"} />' , code: '<div tabIndex={0} />' , code: '<div tabIndex={-1} />' , code: '<div tabIndex={null} />' , code: '<div tabIndex={bar()} />' , code: '<div tabIndex={bar} />' , code: '<div tabIndex={"foobar"} />' , code: '<div tabIndex="0" />' , code: '<div tabIndex="-1" />' , code: '<div tabIndex="-5" />' , code: '<div tabIndex="-5.5" />' , code: '<div tabIndex={-5.5} />' , code: '<div tabIndex={-5} />' ].map parserOptionsMapper invalid: [ code: '<div tabIndex="1" />', errors: [expectedError] , code: '<div tabIndex={1} />', errors: [expectedError] , code: '<div tabIndex={"1"} />', errors: [expectedError] , code: '<div tabIndex={1.589} />', errors: [expectedError] ].map parserOptionsMapper
[ { "context": " cancel: \"modalCancel\"\n content: { name: \"Louis\" }\n contentViewClass: App.CustomModalConte", "end": 2107, "score": 0.9991574287414551, "start": 2102, "tag": "NAME", "value": "Louis" }, { "context": "verRoute = Ember.Route.extend\n model: -> {name: \"Louis\"}\n", "end": 2342, "score": 0.9992510676383972, "start": 2337, "tag": "NAME", "value": "Louis" } ]
app/app.coffee
cjc343/ember-widgets
0
# Dependencies require 'vendor/ember-list-view/list-view' require 'vendor/bootstrap/dist/js/bootstrap' require 'dist/js/ember-widgets' # Compiled Handlebars templates require 'build/app/templates' # Data require 'build/app/data/ember_widgets/countries' window.App = Ember.Application.create LOG_TRANSITIONS: false require 'build/app/views/mixins' require 'build/app/views/ember_widgets' App.Router.map -> @route 'license' @resource 'emberWidgets', path: '/ember-widgets', -> @route 'overview' @route 'documentation' @route 'accordion' @route 'carousel' @route 'modal' @route 'popover' @route 'select' @route 'colorPicker' @route 'radioButton' App.IndexRoute = Ember.Route.extend beforeModel: -> @transitionTo('emberWidgets.overview') App.EmberWidgetsIndexRoute = Ember.Route.extend beforeModel: -> @transitionTo('emberWidgets.overview') App.EmberWidgetsOverviewRoute = Ember.Route.extend activate: -> controller = @controllerFor('emberWidgets') controller.set 'showLargeHero', yes deactivate: -> controller = @controllerFor('emberWidgets') controller.set 'showLargeHero', no App.CustomPopoverContentView = Ember.View.extend templateName: 'custom-popover-content' App.CustomModalContentView = Ember.View.extend templateName: 'custom-modal-content' App.EmberWidgetsSelectRoute = Ember.Route.extend model: -> window.countries App.EmberWidgetsModalRoute = Ember.Route.extend actions: showModal: -> Ember.Widgets.ModalComponent.popup targetObject: this confirm: "modalConfirm" cancel: "modalCancel" content: "Isn't this one fine day?" showSmallModal: -> Ember.Widgets.ModalComponent.popup targetObject: this confirm: "modalConfirm" cancel: "modalCancel" size: 'small' content: "This is quite small isn't it? You can also use 'large'." showModalWithCustomContent: -> Ember.Widgets.ModalComponent.popup targetObject: this confirm: "modalConfirm" cancel: "modalCancel" content: { name: "Louis" } contentViewClass: App.CustomModalContentView modalConfirm: -> console.log("Modal Confirm!") modalCancel: -> console.log("Modal Cancel!") App.EmberWidgetsPopoverRoute = Ember.Route.extend model: -> {name: "Louis"}
161669
# Dependencies require 'vendor/ember-list-view/list-view' require 'vendor/bootstrap/dist/js/bootstrap' require 'dist/js/ember-widgets' # Compiled Handlebars templates require 'build/app/templates' # Data require 'build/app/data/ember_widgets/countries' window.App = Ember.Application.create LOG_TRANSITIONS: false require 'build/app/views/mixins' require 'build/app/views/ember_widgets' App.Router.map -> @route 'license' @resource 'emberWidgets', path: '/ember-widgets', -> @route 'overview' @route 'documentation' @route 'accordion' @route 'carousel' @route 'modal' @route 'popover' @route 'select' @route 'colorPicker' @route 'radioButton' App.IndexRoute = Ember.Route.extend beforeModel: -> @transitionTo('emberWidgets.overview') App.EmberWidgetsIndexRoute = Ember.Route.extend beforeModel: -> @transitionTo('emberWidgets.overview') App.EmberWidgetsOverviewRoute = Ember.Route.extend activate: -> controller = @controllerFor('emberWidgets') controller.set 'showLargeHero', yes deactivate: -> controller = @controllerFor('emberWidgets') controller.set 'showLargeHero', no App.CustomPopoverContentView = Ember.View.extend templateName: 'custom-popover-content' App.CustomModalContentView = Ember.View.extend templateName: 'custom-modal-content' App.EmberWidgetsSelectRoute = Ember.Route.extend model: -> window.countries App.EmberWidgetsModalRoute = Ember.Route.extend actions: showModal: -> Ember.Widgets.ModalComponent.popup targetObject: this confirm: "modalConfirm" cancel: "modalCancel" content: "Isn't this one fine day?" showSmallModal: -> Ember.Widgets.ModalComponent.popup targetObject: this confirm: "modalConfirm" cancel: "modalCancel" size: 'small' content: "This is quite small isn't it? You can also use 'large'." showModalWithCustomContent: -> Ember.Widgets.ModalComponent.popup targetObject: this confirm: "modalConfirm" cancel: "modalCancel" content: { name: "<NAME>" } contentViewClass: App.CustomModalContentView modalConfirm: -> console.log("Modal Confirm!") modalCancel: -> console.log("Modal Cancel!") App.EmberWidgetsPopoverRoute = Ember.Route.extend model: -> {name: "<NAME>"}
true
# Dependencies require 'vendor/ember-list-view/list-view' require 'vendor/bootstrap/dist/js/bootstrap' require 'dist/js/ember-widgets' # Compiled Handlebars templates require 'build/app/templates' # Data require 'build/app/data/ember_widgets/countries' window.App = Ember.Application.create LOG_TRANSITIONS: false require 'build/app/views/mixins' require 'build/app/views/ember_widgets' App.Router.map -> @route 'license' @resource 'emberWidgets', path: '/ember-widgets', -> @route 'overview' @route 'documentation' @route 'accordion' @route 'carousel' @route 'modal' @route 'popover' @route 'select' @route 'colorPicker' @route 'radioButton' App.IndexRoute = Ember.Route.extend beforeModel: -> @transitionTo('emberWidgets.overview') App.EmberWidgetsIndexRoute = Ember.Route.extend beforeModel: -> @transitionTo('emberWidgets.overview') App.EmberWidgetsOverviewRoute = Ember.Route.extend activate: -> controller = @controllerFor('emberWidgets') controller.set 'showLargeHero', yes deactivate: -> controller = @controllerFor('emberWidgets') controller.set 'showLargeHero', no App.CustomPopoverContentView = Ember.View.extend templateName: 'custom-popover-content' App.CustomModalContentView = Ember.View.extend templateName: 'custom-modal-content' App.EmberWidgetsSelectRoute = Ember.Route.extend model: -> window.countries App.EmberWidgetsModalRoute = Ember.Route.extend actions: showModal: -> Ember.Widgets.ModalComponent.popup targetObject: this confirm: "modalConfirm" cancel: "modalCancel" content: "Isn't this one fine day?" showSmallModal: -> Ember.Widgets.ModalComponent.popup targetObject: this confirm: "modalConfirm" cancel: "modalCancel" size: 'small' content: "This is quite small isn't it? You can also use 'large'." showModalWithCustomContent: -> Ember.Widgets.ModalComponent.popup targetObject: this confirm: "modalConfirm" cancel: "modalCancel" content: { name: "PI:NAME:<NAME>END_PI" } contentViewClass: App.CustomModalContentView modalConfirm: -> console.log("Modal Confirm!") modalCancel: -> console.log("Modal Cancel!") App.EmberWidgetsPopoverRoute = Ember.Route.extend model: -> {name: "PI:NAME:<NAME>END_PI"}
[ { "context": "# author: tmwhere.com\n\nPIXI = require('pixi.js/bin/pixi.js')\n_ = requir", "end": 21, "score": 0.888242244720459, "start": 10, "tag": "EMAIL", "value": "tmwhere.com" } ]
src/game_modules/mapgen.coffee
t-mw/citygen
177
# author: tmwhere.com PIXI = require('pixi.js/bin/pixi.js') _ = require('lodash') noise = require('perlin').noise Quadtree = require('quadtree').Quadtree seedrandom = require('seedrandom') math = require('generic_modules/math') util = require('generic_modules/utility') collision = require('generic_modules/collision') config = require('game_modules/config') class Segment extends collision.CollisionObject @End: START: "start" END: "end" constructor: (start, end, t, q) -> obj = @ start = _.cloneDeep(start) end = _.cloneDeep(end) t = util.defaultFor(t, 0) q = util.defaultFor(q, {}, true) @width = if q.highway then config.mapGeneration.HIGHWAY_SEGMENT_WIDTH else config.mapGeneration.DEFAULT_SEGMENT_WIDTH @collider = new collision.CollisionObject(this, collision.CollisionObject.Type.LINE, {start: start, end: end, width: @width}) @roadRevision = 0 @dirRevision = undefined @lengthRevision = undefined @cachedDir = undefined @cachedLength = undefined # representation of road @r = start: start end: end setStart: (val) -> @start = val obj.collider.updateCollisionProperties({start: @start}) obj.roadRevision++ setEnd: (val) -> @end = val obj.collider.updateCollisionProperties({end: @end}) obj.roadRevision++ # time-step delay before this road is evaluated @t = t # meta-information relevant to global goals @q = q # links backwards and forwards @links = b: [] f: [] @users = [] [@maxSpeed, @capacity] = if (q.highway) [1200, 12] else [800, 6] currentSpeed: -> # subtract 1 from users length so that a single user can go full speed Math.min(config.gameLogic.MIN_SPEED_PROPORTION, 1 - Math.max(0, @users.length - 1) / @capacity) * @maxSpeed # clockwise direction dir: -> if (@dirRevision != @roadRevision) @dirRevision = @roadRevision vector = math.subtractPoints(@r.end, @r.start) @cachedDir = -1 * math.sign(math.crossProduct({x:0, y: 1}, vector)) * math.angleBetween({x: 0, y: 1}, vector) return @cachedDir length: -> if (@lengthRevision != @roadRevision) @lengthRevision = @roadRevision @cachedLength = math.length(@r.start, @r.end) return @cachedLength debugLinks: -> @q.color = 0x00FF00 _.each(@links.b, (backwards) -> backwards.q.color = 0xFF0000 ) _.each(@links.f, (forwards) -> forwards.q.color = 0x0000FF ) startIsBackwards: -> if (@links.b.length > 0) math.equalV(@links.b[0].r.start, @r.start) || math.equalV(@links.b[0].r.end, @r.start) else math.equalV(@links.f[0].r.start, @r.end) || math.equalV(@links.f[0].r.end, @r.end) cost: -> @length() / @currentSpeed() costTo: (other, fromFraction) -> segmentEnd = @endContaining(other) return @cost() * if fromFraction? switch segmentEnd when Segment.End.START then fromFraction when Segment.End.END then (1-fromFraction) else 0.5 neighbours: -> @links.f.concat(@links.b) endContaining: (segment) -> startBackwards = @startIsBackwards() if @links.b.indexOf(segment) != -1 return if startBackwards then Segment.End.START else Segment.End.END else if @links.f.indexOf(segment) != -1 return if startBackwards then Segment.End.END else Segment.End.START else undefined linksForEndContaining: (segment) -> if @links.b.indexOf(segment) != -1 @links.b else if @links.f.indexOf(segment) != -1 @links.f else undefined split: (point, segment, segmentList, qTree) -> startIsBackwards = @startIsBackwards() splitPart = segmentFactory.fromExisting(this) addSegment(splitPart, segmentList, qTree) splitPart.r.setEnd(point) @r.setStart(point) # links are not copied using the preceding factory method # copy link array for the split part, keeping references the same splitPart.links.b = @links.b.slice(0) splitPart.links.f = @links.f.slice(0) # work out which links correspond to which end of the split segment if (startIsBackwards) firstSplit = splitPart secondSplit = this fixLinks = splitPart.links.b else firstSplit = this secondSplit = splitPart fixLinks = splitPart.links.f _.each(fixLinks, (link) -> index = link.links.b.indexOf(this) if (index != -1) link.links.b[index] = splitPart else index = link.links.f.indexOf(this) link.links.f[index] = splitPart , this) firstSplit.links.f = [] firstSplit.links.f.push(segment) firstSplit.links.f.push(secondSplit) secondSplit.links.b = [] secondSplit.links.b.push(segment) secondSplit.links.b.push(firstSplit) segment.links.f.push(firstSplit) segment.links.f.push(secondSplit) segmentFactory = do -> return { fromExisting: (segment, t, r, q) -> t = util.defaultFor(t, segment.t) r = util.defaultFor(r, segment.r) q = util.defaultFor(q, segment.q) return new Segment(r.start, r.end, t, q) , usingDirection: (start, dir, length, t, q) -> # default to east dir = util.defaultFor(dir, 90) length = util.defaultFor(length, config.mapGeneration.DEFAULT_SEGMENT_LENGTH) end = x: start.x + length*math.sinDegrees(dir), y: start.y + length*math.cosDegrees(dir) return new Segment(start, end, t, q) } heatmap = do -> { popOnRoad: (r) -> (@populationAt(r.start.x, r.start.y) + @populationAt(r.end.x, r.end.y))/2 populationAt: (x, y) -> value1 = (noise.simplex2(x/10000, y/10000) + 1) / 2 value2 = (noise.simplex2(x/20000 + 500, y/20000 + 500) + 1) / 2 value3 = (noise.simplex2(x/20000 + 1000, y/20000 + 1000) + 1) / 2 Math.pow((value1 * value2 + value3) / 2, 2) } doRoadSegmentsIntersect = (r1, r2) -> math.doLineSegmentsIntersect(r1.start, r1.end, r2.start, r2.end, true) localConstraints = (segment, segments, qTree, debugData) -> action = priority: 0, func: undefined, q: {} matches = qTree.retrieve(segment.collider.limits()) for i in [0..matches.length-1] by 1 other = matches[i].o # intersection check if (action.priority <= 4) intersection = doRoadSegmentsIntersect(segment.r, other.r) if (intersection) if (!action.q.t? || intersection.t < action.q.t) action.q.t = intersection.t do (other, intersection) -> action.priority = 4 action.func = -> # if intersecting lines are too similar don't continue if util.minDegreeDifference(other.dir(), segment.dir()) < config.mapGeneration.MINIMUM_INTERSECTION_DEVIATION return false other.split(intersection, segment, segments, qTree) segment.r.end = intersection segment.q.severed = true if (debugData?) if (!debugData.intersections?) debugData.intersections = [] debugData.intersections.push( x: intersection.x y: intersection.y ) return true # snap to crossing within radius check if (action.priority <= 3) # current segment's start must have been checked to have been created. # other segment's start must have a corresponding end. if (math.length(segment.r.end, other.r.end) <= config.mapGeneration.ROAD_SNAP_DISTANCE) do (other) -> point = other.r.end action.priority = 3 action.func = -> segment.r.end = point segment.q.severed = true # update links of otherSegment corresponding to other.r.end links = if other.startIsBackwards() then other.links.f else other.links.b # check for duplicate lines, don't add if it exists # this should be done before links are setup, to avoid having to undo that step if _.any(links, (link) -> ((math.equalV(link.r.start, segment.r.end) && math.equalV(link.r.end, segment.r.start)) || (math.equalV(link.r.start, segment.r.start) && math.equalV(link.r.end, segment.r.end)))) return false _.each(links, (link) -> # pick links of remaining segments at junction corresponding to other.r.end link.linksForEndContaining(other).push(segment) # add junction segments to snapped segment segment.links.f.push(link) ) links.push(segment) segment.links.f.push(other) if (debugData?) if (!debugData.snaps?) debugData.snaps = [] debugData.snaps.push( x: point.x y: point.y ) return true # intersection within radius check if (action.priority <= 2) {distance2, pointOnLine, lineProj2, length2} = math.distanceToLine(segment.r.end, other.r.start, other.r.end) if (distance2 < config.mapGeneration.ROAD_SNAP_DISTANCE * config.mapGeneration.ROAD_SNAP_DISTANCE && lineProj2 >= 0 && lineProj2 <= length2) do (other) -> point = pointOnLine action.priority = 2 action.func = -> segment.r.end = point segment.q.severed = true # if intersecting lines are too similar don't continue if util.minDegreeDifference(other.dir(), segment.dir()) < config.mapGeneration.MINIMUM_INTERSECTION_DEVIATION return false other.split(point, segment, segments, qTree) if (debugData?) if (!debugData.intersectionsRadius?) debugData.intersectionsRadius = [] debugData.intersectionsRadius.push( x: point.x y: point.y ) return true if (action.func) return action.func() return true globalGoals = do -> return { generate: (previousSegment) -> newBranches = [] if (!previousSegment.q.severed) template = (direction, length, t, q) -> segmentFactory.usingDirection(previousSegment.r.end, direction, length, t, q) # used for highways or going straight on a normal branch templateContinue = _.partialRight(template, previousSegment.length(), 0, previousSegment.q) # not using q, i.e. not highways templateBranch = _.partialRight( template, config.mapGeneration.DEFAULT_SEGMENT_LENGTH, if previousSegment.q.highway then config.mapGeneration.NORMAL_BRANCH_TIME_DELAY_FROM_HIGHWAY else 0) continueStraight = templateContinue(previousSegment.dir()) straightPop = heatmap.popOnRoad(continueStraight.r) if (previousSegment.q.highway) randomStraight = templateContinue(previousSegment.dir() + config.mapGeneration.RANDOM_STRAIGHT_ANGLE()) randomPop = heatmap.popOnRoad(randomStraight.r) roadPop if (randomPop > straightPop) newBranches.push(randomStraight) roadPop = randomPop else newBranches.push(continueStraight) roadPop = straightPop if (roadPop > config.mapGeneration.HIGHWAY_BRANCH_POPULATION_THRESHOLD) if (Math.random() < config.mapGeneration.HIGHWAY_BRANCH_PROBABILITY) leftHighwayBranch = templateContinue(previousSegment.dir() - 90 + config.mapGeneration.RANDOM_BRANCH_ANGLE()) newBranches.push(leftHighwayBranch) else if (Math.random() < config.mapGeneration.HIGHWAY_BRANCH_PROBABILITY) rightHighwayBranch = templateContinue(previousSegment.dir() + 90 + config.mapGeneration.RANDOM_BRANCH_ANGLE()) newBranches.push(rightHighwayBranch) else if (straightPop > config.mapGeneration.NORMAL_BRANCH_POPULATION_THRESHOLD) newBranches.push(continueStraight) if (straightPop > config.mapGeneration.NORMAL_BRANCH_POPULATION_THRESHOLD) if (Math.random() < config.mapGeneration.DEFAULT_BRANCH_PROBABILITY) leftBranch = templateBranch(previousSegment.dir() - 90 + config.mapGeneration.RANDOM_BRANCH_ANGLE()) newBranches.push(leftBranch) else if (Math.random() < config.mapGeneration.DEFAULT_BRANCH_PROBABILITY) rightBranch = templateBranch(previousSegment.dir() + 90 + config.mapGeneration.RANDOM_BRANCH_ANGLE()) newBranches.push(rightBranch) for i in [0..newBranches.length-1] by 1 do (branch = newBranches[i]) -> branch.setupBranchLinks = -> # setup links between each current branch and each existing branch stemming from the previous segment _.each(previousSegment.links.f, (link) -> @links.b.push(link) link.linksForEndContaining(previousSegment).push(this) , @) previousSegment.links.f.push(@) @links.b.push(previousSegment) return newBranches } addSegment = (segment, segmentList, qTree) -> segmentList.push(segment) qTree.insert(segment.collider.limits()) generate = (seed) -> debugData = {} Math.seedrandom(seed) # this perlin noise library only supports 65536 different seeds noise.seed(Math.random()) priorityQ = [] # setup first segments in queue do -> rootSegment = new Segment({x: 0, y: 0}, {x: config.mapGeneration.HIGHWAY_SEGMENT_LENGTH, y: 0}, 0, {highway: true}) oppositeDirection = segmentFactory.fromExisting(rootSegment) newEnd = x: rootSegment.r.start.x - config.mapGeneration.HIGHWAY_SEGMENT_LENGTH y: oppositeDirection.r.end.y oppositeDirection.r.setEnd(newEnd) oppositeDirection.links.b.push(rootSegment) rootSegment.links.b.push(oppositeDirection) priorityQ.push(rootSegment) priorityQ.push(oppositeDirection) segments = [] qTree = new Quadtree(config.mapGeneration.QUADTREE_PARAMS, config.mapGeneration.QUADTREE_MAX_OBJECTS, config.mapGeneration.QUADTREE_MAX_LEVELS) while (priorityQ.length > 0 && segments.length < config.mapGeneration.SEGMENT_COUNT_LIMIT) # pop smallest r(ti, ri, qi) from Q (i.e., smallest ‘t’) minT = undefined minT_i = 0 _.each(priorityQ, (segment, i) -> if (!minT? || segment.t < minT) minT = segment.t minT_i = i ) minSegment = priorityQ.splice(minT_i, 1)[0] accepted = localConstraints(minSegment, segments, qTree, debugData) if (accepted) if (minSegment.setupBranchLinks?) minSegment.setupBranchLinks() addSegment(minSegment, segments, qTree) _.each(globalGoals.generate(minSegment), (newSegment) -> newSegment.t = minSegment.t + 1 + newSegment.t priorityQ.push(newSegment) ) id = 0 for segment in segments segment.id = id++ console.log("#{segments.length} segments generated.") return { segments: segments qTree: qTree heatmap: heatmap debugData: debugData } module.exports = { Segment: Segment generate: generate }
34523
# author: <EMAIL> PIXI = require('pixi.js/bin/pixi.js') _ = require('lodash') noise = require('perlin').noise Quadtree = require('quadtree').Quadtree seedrandom = require('seedrandom') math = require('generic_modules/math') util = require('generic_modules/utility') collision = require('generic_modules/collision') config = require('game_modules/config') class Segment extends collision.CollisionObject @End: START: "start" END: "end" constructor: (start, end, t, q) -> obj = @ start = _.cloneDeep(start) end = _.cloneDeep(end) t = util.defaultFor(t, 0) q = util.defaultFor(q, {}, true) @width = if q.highway then config.mapGeneration.HIGHWAY_SEGMENT_WIDTH else config.mapGeneration.DEFAULT_SEGMENT_WIDTH @collider = new collision.CollisionObject(this, collision.CollisionObject.Type.LINE, {start: start, end: end, width: @width}) @roadRevision = 0 @dirRevision = undefined @lengthRevision = undefined @cachedDir = undefined @cachedLength = undefined # representation of road @r = start: start end: end setStart: (val) -> @start = val obj.collider.updateCollisionProperties({start: @start}) obj.roadRevision++ setEnd: (val) -> @end = val obj.collider.updateCollisionProperties({end: @end}) obj.roadRevision++ # time-step delay before this road is evaluated @t = t # meta-information relevant to global goals @q = q # links backwards and forwards @links = b: [] f: [] @users = [] [@maxSpeed, @capacity] = if (q.highway) [1200, 12] else [800, 6] currentSpeed: -> # subtract 1 from users length so that a single user can go full speed Math.min(config.gameLogic.MIN_SPEED_PROPORTION, 1 - Math.max(0, @users.length - 1) / @capacity) * @maxSpeed # clockwise direction dir: -> if (@dirRevision != @roadRevision) @dirRevision = @roadRevision vector = math.subtractPoints(@r.end, @r.start) @cachedDir = -1 * math.sign(math.crossProduct({x:0, y: 1}, vector)) * math.angleBetween({x: 0, y: 1}, vector) return @cachedDir length: -> if (@lengthRevision != @roadRevision) @lengthRevision = @roadRevision @cachedLength = math.length(@r.start, @r.end) return @cachedLength debugLinks: -> @q.color = 0x00FF00 _.each(@links.b, (backwards) -> backwards.q.color = 0xFF0000 ) _.each(@links.f, (forwards) -> forwards.q.color = 0x0000FF ) startIsBackwards: -> if (@links.b.length > 0) math.equalV(@links.b[0].r.start, @r.start) || math.equalV(@links.b[0].r.end, @r.start) else math.equalV(@links.f[0].r.start, @r.end) || math.equalV(@links.f[0].r.end, @r.end) cost: -> @length() / @currentSpeed() costTo: (other, fromFraction) -> segmentEnd = @endContaining(other) return @cost() * if fromFraction? switch segmentEnd when Segment.End.START then fromFraction when Segment.End.END then (1-fromFraction) else 0.5 neighbours: -> @links.f.concat(@links.b) endContaining: (segment) -> startBackwards = @startIsBackwards() if @links.b.indexOf(segment) != -1 return if startBackwards then Segment.End.START else Segment.End.END else if @links.f.indexOf(segment) != -1 return if startBackwards then Segment.End.END else Segment.End.START else undefined linksForEndContaining: (segment) -> if @links.b.indexOf(segment) != -1 @links.b else if @links.f.indexOf(segment) != -1 @links.f else undefined split: (point, segment, segmentList, qTree) -> startIsBackwards = @startIsBackwards() splitPart = segmentFactory.fromExisting(this) addSegment(splitPart, segmentList, qTree) splitPart.r.setEnd(point) @r.setStart(point) # links are not copied using the preceding factory method # copy link array for the split part, keeping references the same splitPart.links.b = @links.b.slice(0) splitPart.links.f = @links.f.slice(0) # work out which links correspond to which end of the split segment if (startIsBackwards) firstSplit = splitPart secondSplit = this fixLinks = splitPart.links.b else firstSplit = this secondSplit = splitPart fixLinks = splitPart.links.f _.each(fixLinks, (link) -> index = link.links.b.indexOf(this) if (index != -1) link.links.b[index] = splitPart else index = link.links.f.indexOf(this) link.links.f[index] = splitPart , this) firstSplit.links.f = [] firstSplit.links.f.push(segment) firstSplit.links.f.push(secondSplit) secondSplit.links.b = [] secondSplit.links.b.push(segment) secondSplit.links.b.push(firstSplit) segment.links.f.push(firstSplit) segment.links.f.push(secondSplit) segmentFactory = do -> return { fromExisting: (segment, t, r, q) -> t = util.defaultFor(t, segment.t) r = util.defaultFor(r, segment.r) q = util.defaultFor(q, segment.q) return new Segment(r.start, r.end, t, q) , usingDirection: (start, dir, length, t, q) -> # default to east dir = util.defaultFor(dir, 90) length = util.defaultFor(length, config.mapGeneration.DEFAULT_SEGMENT_LENGTH) end = x: start.x + length*math.sinDegrees(dir), y: start.y + length*math.cosDegrees(dir) return new Segment(start, end, t, q) } heatmap = do -> { popOnRoad: (r) -> (@populationAt(r.start.x, r.start.y) + @populationAt(r.end.x, r.end.y))/2 populationAt: (x, y) -> value1 = (noise.simplex2(x/10000, y/10000) + 1) / 2 value2 = (noise.simplex2(x/20000 + 500, y/20000 + 500) + 1) / 2 value3 = (noise.simplex2(x/20000 + 1000, y/20000 + 1000) + 1) / 2 Math.pow((value1 * value2 + value3) / 2, 2) } doRoadSegmentsIntersect = (r1, r2) -> math.doLineSegmentsIntersect(r1.start, r1.end, r2.start, r2.end, true) localConstraints = (segment, segments, qTree, debugData) -> action = priority: 0, func: undefined, q: {} matches = qTree.retrieve(segment.collider.limits()) for i in [0..matches.length-1] by 1 other = matches[i].o # intersection check if (action.priority <= 4) intersection = doRoadSegmentsIntersect(segment.r, other.r) if (intersection) if (!action.q.t? || intersection.t < action.q.t) action.q.t = intersection.t do (other, intersection) -> action.priority = 4 action.func = -> # if intersecting lines are too similar don't continue if util.minDegreeDifference(other.dir(), segment.dir()) < config.mapGeneration.MINIMUM_INTERSECTION_DEVIATION return false other.split(intersection, segment, segments, qTree) segment.r.end = intersection segment.q.severed = true if (debugData?) if (!debugData.intersections?) debugData.intersections = [] debugData.intersections.push( x: intersection.x y: intersection.y ) return true # snap to crossing within radius check if (action.priority <= 3) # current segment's start must have been checked to have been created. # other segment's start must have a corresponding end. if (math.length(segment.r.end, other.r.end) <= config.mapGeneration.ROAD_SNAP_DISTANCE) do (other) -> point = other.r.end action.priority = 3 action.func = -> segment.r.end = point segment.q.severed = true # update links of otherSegment corresponding to other.r.end links = if other.startIsBackwards() then other.links.f else other.links.b # check for duplicate lines, don't add if it exists # this should be done before links are setup, to avoid having to undo that step if _.any(links, (link) -> ((math.equalV(link.r.start, segment.r.end) && math.equalV(link.r.end, segment.r.start)) || (math.equalV(link.r.start, segment.r.start) && math.equalV(link.r.end, segment.r.end)))) return false _.each(links, (link) -> # pick links of remaining segments at junction corresponding to other.r.end link.linksForEndContaining(other).push(segment) # add junction segments to snapped segment segment.links.f.push(link) ) links.push(segment) segment.links.f.push(other) if (debugData?) if (!debugData.snaps?) debugData.snaps = [] debugData.snaps.push( x: point.x y: point.y ) return true # intersection within radius check if (action.priority <= 2) {distance2, pointOnLine, lineProj2, length2} = math.distanceToLine(segment.r.end, other.r.start, other.r.end) if (distance2 < config.mapGeneration.ROAD_SNAP_DISTANCE * config.mapGeneration.ROAD_SNAP_DISTANCE && lineProj2 >= 0 && lineProj2 <= length2) do (other) -> point = pointOnLine action.priority = 2 action.func = -> segment.r.end = point segment.q.severed = true # if intersecting lines are too similar don't continue if util.minDegreeDifference(other.dir(), segment.dir()) < config.mapGeneration.MINIMUM_INTERSECTION_DEVIATION return false other.split(point, segment, segments, qTree) if (debugData?) if (!debugData.intersectionsRadius?) debugData.intersectionsRadius = [] debugData.intersectionsRadius.push( x: point.x y: point.y ) return true if (action.func) return action.func() return true globalGoals = do -> return { generate: (previousSegment) -> newBranches = [] if (!previousSegment.q.severed) template = (direction, length, t, q) -> segmentFactory.usingDirection(previousSegment.r.end, direction, length, t, q) # used for highways or going straight on a normal branch templateContinue = _.partialRight(template, previousSegment.length(), 0, previousSegment.q) # not using q, i.e. not highways templateBranch = _.partialRight( template, config.mapGeneration.DEFAULT_SEGMENT_LENGTH, if previousSegment.q.highway then config.mapGeneration.NORMAL_BRANCH_TIME_DELAY_FROM_HIGHWAY else 0) continueStraight = templateContinue(previousSegment.dir()) straightPop = heatmap.popOnRoad(continueStraight.r) if (previousSegment.q.highway) randomStraight = templateContinue(previousSegment.dir() + config.mapGeneration.RANDOM_STRAIGHT_ANGLE()) randomPop = heatmap.popOnRoad(randomStraight.r) roadPop if (randomPop > straightPop) newBranches.push(randomStraight) roadPop = randomPop else newBranches.push(continueStraight) roadPop = straightPop if (roadPop > config.mapGeneration.HIGHWAY_BRANCH_POPULATION_THRESHOLD) if (Math.random() < config.mapGeneration.HIGHWAY_BRANCH_PROBABILITY) leftHighwayBranch = templateContinue(previousSegment.dir() - 90 + config.mapGeneration.RANDOM_BRANCH_ANGLE()) newBranches.push(leftHighwayBranch) else if (Math.random() < config.mapGeneration.HIGHWAY_BRANCH_PROBABILITY) rightHighwayBranch = templateContinue(previousSegment.dir() + 90 + config.mapGeneration.RANDOM_BRANCH_ANGLE()) newBranches.push(rightHighwayBranch) else if (straightPop > config.mapGeneration.NORMAL_BRANCH_POPULATION_THRESHOLD) newBranches.push(continueStraight) if (straightPop > config.mapGeneration.NORMAL_BRANCH_POPULATION_THRESHOLD) if (Math.random() < config.mapGeneration.DEFAULT_BRANCH_PROBABILITY) leftBranch = templateBranch(previousSegment.dir() - 90 + config.mapGeneration.RANDOM_BRANCH_ANGLE()) newBranches.push(leftBranch) else if (Math.random() < config.mapGeneration.DEFAULT_BRANCH_PROBABILITY) rightBranch = templateBranch(previousSegment.dir() + 90 + config.mapGeneration.RANDOM_BRANCH_ANGLE()) newBranches.push(rightBranch) for i in [0..newBranches.length-1] by 1 do (branch = newBranches[i]) -> branch.setupBranchLinks = -> # setup links between each current branch and each existing branch stemming from the previous segment _.each(previousSegment.links.f, (link) -> @links.b.push(link) link.linksForEndContaining(previousSegment).push(this) , @) previousSegment.links.f.push(@) @links.b.push(previousSegment) return newBranches } addSegment = (segment, segmentList, qTree) -> segmentList.push(segment) qTree.insert(segment.collider.limits()) generate = (seed) -> debugData = {} Math.seedrandom(seed) # this perlin noise library only supports 65536 different seeds noise.seed(Math.random()) priorityQ = [] # setup first segments in queue do -> rootSegment = new Segment({x: 0, y: 0}, {x: config.mapGeneration.HIGHWAY_SEGMENT_LENGTH, y: 0}, 0, {highway: true}) oppositeDirection = segmentFactory.fromExisting(rootSegment) newEnd = x: rootSegment.r.start.x - config.mapGeneration.HIGHWAY_SEGMENT_LENGTH y: oppositeDirection.r.end.y oppositeDirection.r.setEnd(newEnd) oppositeDirection.links.b.push(rootSegment) rootSegment.links.b.push(oppositeDirection) priorityQ.push(rootSegment) priorityQ.push(oppositeDirection) segments = [] qTree = new Quadtree(config.mapGeneration.QUADTREE_PARAMS, config.mapGeneration.QUADTREE_MAX_OBJECTS, config.mapGeneration.QUADTREE_MAX_LEVELS) while (priorityQ.length > 0 && segments.length < config.mapGeneration.SEGMENT_COUNT_LIMIT) # pop smallest r(ti, ri, qi) from Q (i.e., smallest ‘t’) minT = undefined minT_i = 0 _.each(priorityQ, (segment, i) -> if (!minT? || segment.t < minT) minT = segment.t minT_i = i ) minSegment = priorityQ.splice(minT_i, 1)[0] accepted = localConstraints(minSegment, segments, qTree, debugData) if (accepted) if (minSegment.setupBranchLinks?) minSegment.setupBranchLinks() addSegment(minSegment, segments, qTree) _.each(globalGoals.generate(minSegment), (newSegment) -> newSegment.t = minSegment.t + 1 + newSegment.t priorityQ.push(newSegment) ) id = 0 for segment in segments segment.id = id++ console.log("#{segments.length} segments generated.") return { segments: segments qTree: qTree heatmap: heatmap debugData: debugData } module.exports = { Segment: Segment generate: generate }
true
# author: PI:EMAIL:<EMAIL>END_PI PIXI = require('pixi.js/bin/pixi.js') _ = require('lodash') noise = require('perlin').noise Quadtree = require('quadtree').Quadtree seedrandom = require('seedrandom') math = require('generic_modules/math') util = require('generic_modules/utility') collision = require('generic_modules/collision') config = require('game_modules/config') class Segment extends collision.CollisionObject @End: START: "start" END: "end" constructor: (start, end, t, q) -> obj = @ start = _.cloneDeep(start) end = _.cloneDeep(end) t = util.defaultFor(t, 0) q = util.defaultFor(q, {}, true) @width = if q.highway then config.mapGeneration.HIGHWAY_SEGMENT_WIDTH else config.mapGeneration.DEFAULT_SEGMENT_WIDTH @collider = new collision.CollisionObject(this, collision.CollisionObject.Type.LINE, {start: start, end: end, width: @width}) @roadRevision = 0 @dirRevision = undefined @lengthRevision = undefined @cachedDir = undefined @cachedLength = undefined # representation of road @r = start: start end: end setStart: (val) -> @start = val obj.collider.updateCollisionProperties({start: @start}) obj.roadRevision++ setEnd: (val) -> @end = val obj.collider.updateCollisionProperties({end: @end}) obj.roadRevision++ # time-step delay before this road is evaluated @t = t # meta-information relevant to global goals @q = q # links backwards and forwards @links = b: [] f: [] @users = [] [@maxSpeed, @capacity] = if (q.highway) [1200, 12] else [800, 6] currentSpeed: -> # subtract 1 from users length so that a single user can go full speed Math.min(config.gameLogic.MIN_SPEED_PROPORTION, 1 - Math.max(0, @users.length - 1) / @capacity) * @maxSpeed # clockwise direction dir: -> if (@dirRevision != @roadRevision) @dirRevision = @roadRevision vector = math.subtractPoints(@r.end, @r.start) @cachedDir = -1 * math.sign(math.crossProduct({x:0, y: 1}, vector)) * math.angleBetween({x: 0, y: 1}, vector) return @cachedDir length: -> if (@lengthRevision != @roadRevision) @lengthRevision = @roadRevision @cachedLength = math.length(@r.start, @r.end) return @cachedLength debugLinks: -> @q.color = 0x00FF00 _.each(@links.b, (backwards) -> backwards.q.color = 0xFF0000 ) _.each(@links.f, (forwards) -> forwards.q.color = 0x0000FF ) startIsBackwards: -> if (@links.b.length > 0) math.equalV(@links.b[0].r.start, @r.start) || math.equalV(@links.b[0].r.end, @r.start) else math.equalV(@links.f[0].r.start, @r.end) || math.equalV(@links.f[0].r.end, @r.end) cost: -> @length() / @currentSpeed() costTo: (other, fromFraction) -> segmentEnd = @endContaining(other) return @cost() * if fromFraction? switch segmentEnd when Segment.End.START then fromFraction when Segment.End.END then (1-fromFraction) else 0.5 neighbours: -> @links.f.concat(@links.b) endContaining: (segment) -> startBackwards = @startIsBackwards() if @links.b.indexOf(segment) != -1 return if startBackwards then Segment.End.START else Segment.End.END else if @links.f.indexOf(segment) != -1 return if startBackwards then Segment.End.END else Segment.End.START else undefined linksForEndContaining: (segment) -> if @links.b.indexOf(segment) != -1 @links.b else if @links.f.indexOf(segment) != -1 @links.f else undefined split: (point, segment, segmentList, qTree) -> startIsBackwards = @startIsBackwards() splitPart = segmentFactory.fromExisting(this) addSegment(splitPart, segmentList, qTree) splitPart.r.setEnd(point) @r.setStart(point) # links are not copied using the preceding factory method # copy link array for the split part, keeping references the same splitPart.links.b = @links.b.slice(0) splitPart.links.f = @links.f.slice(0) # work out which links correspond to which end of the split segment if (startIsBackwards) firstSplit = splitPart secondSplit = this fixLinks = splitPart.links.b else firstSplit = this secondSplit = splitPart fixLinks = splitPart.links.f _.each(fixLinks, (link) -> index = link.links.b.indexOf(this) if (index != -1) link.links.b[index] = splitPart else index = link.links.f.indexOf(this) link.links.f[index] = splitPart , this) firstSplit.links.f = [] firstSplit.links.f.push(segment) firstSplit.links.f.push(secondSplit) secondSplit.links.b = [] secondSplit.links.b.push(segment) secondSplit.links.b.push(firstSplit) segment.links.f.push(firstSplit) segment.links.f.push(secondSplit) segmentFactory = do -> return { fromExisting: (segment, t, r, q) -> t = util.defaultFor(t, segment.t) r = util.defaultFor(r, segment.r) q = util.defaultFor(q, segment.q) return new Segment(r.start, r.end, t, q) , usingDirection: (start, dir, length, t, q) -> # default to east dir = util.defaultFor(dir, 90) length = util.defaultFor(length, config.mapGeneration.DEFAULT_SEGMENT_LENGTH) end = x: start.x + length*math.sinDegrees(dir), y: start.y + length*math.cosDegrees(dir) return new Segment(start, end, t, q) } heatmap = do -> { popOnRoad: (r) -> (@populationAt(r.start.x, r.start.y) + @populationAt(r.end.x, r.end.y))/2 populationAt: (x, y) -> value1 = (noise.simplex2(x/10000, y/10000) + 1) / 2 value2 = (noise.simplex2(x/20000 + 500, y/20000 + 500) + 1) / 2 value3 = (noise.simplex2(x/20000 + 1000, y/20000 + 1000) + 1) / 2 Math.pow((value1 * value2 + value3) / 2, 2) } doRoadSegmentsIntersect = (r1, r2) -> math.doLineSegmentsIntersect(r1.start, r1.end, r2.start, r2.end, true) localConstraints = (segment, segments, qTree, debugData) -> action = priority: 0, func: undefined, q: {} matches = qTree.retrieve(segment.collider.limits()) for i in [0..matches.length-1] by 1 other = matches[i].o # intersection check if (action.priority <= 4) intersection = doRoadSegmentsIntersect(segment.r, other.r) if (intersection) if (!action.q.t? || intersection.t < action.q.t) action.q.t = intersection.t do (other, intersection) -> action.priority = 4 action.func = -> # if intersecting lines are too similar don't continue if util.minDegreeDifference(other.dir(), segment.dir()) < config.mapGeneration.MINIMUM_INTERSECTION_DEVIATION return false other.split(intersection, segment, segments, qTree) segment.r.end = intersection segment.q.severed = true if (debugData?) if (!debugData.intersections?) debugData.intersections = [] debugData.intersections.push( x: intersection.x y: intersection.y ) return true # snap to crossing within radius check if (action.priority <= 3) # current segment's start must have been checked to have been created. # other segment's start must have a corresponding end. if (math.length(segment.r.end, other.r.end) <= config.mapGeneration.ROAD_SNAP_DISTANCE) do (other) -> point = other.r.end action.priority = 3 action.func = -> segment.r.end = point segment.q.severed = true # update links of otherSegment corresponding to other.r.end links = if other.startIsBackwards() then other.links.f else other.links.b # check for duplicate lines, don't add if it exists # this should be done before links are setup, to avoid having to undo that step if _.any(links, (link) -> ((math.equalV(link.r.start, segment.r.end) && math.equalV(link.r.end, segment.r.start)) || (math.equalV(link.r.start, segment.r.start) && math.equalV(link.r.end, segment.r.end)))) return false _.each(links, (link) -> # pick links of remaining segments at junction corresponding to other.r.end link.linksForEndContaining(other).push(segment) # add junction segments to snapped segment segment.links.f.push(link) ) links.push(segment) segment.links.f.push(other) if (debugData?) if (!debugData.snaps?) debugData.snaps = [] debugData.snaps.push( x: point.x y: point.y ) return true # intersection within radius check if (action.priority <= 2) {distance2, pointOnLine, lineProj2, length2} = math.distanceToLine(segment.r.end, other.r.start, other.r.end) if (distance2 < config.mapGeneration.ROAD_SNAP_DISTANCE * config.mapGeneration.ROAD_SNAP_DISTANCE && lineProj2 >= 0 && lineProj2 <= length2) do (other) -> point = pointOnLine action.priority = 2 action.func = -> segment.r.end = point segment.q.severed = true # if intersecting lines are too similar don't continue if util.minDegreeDifference(other.dir(), segment.dir()) < config.mapGeneration.MINIMUM_INTERSECTION_DEVIATION return false other.split(point, segment, segments, qTree) if (debugData?) if (!debugData.intersectionsRadius?) debugData.intersectionsRadius = [] debugData.intersectionsRadius.push( x: point.x y: point.y ) return true if (action.func) return action.func() return true globalGoals = do -> return { generate: (previousSegment) -> newBranches = [] if (!previousSegment.q.severed) template = (direction, length, t, q) -> segmentFactory.usingDirection(previousSegment.r.end, direction, length, t, q) # used for highways or going straight on a normal branch templateContinue = _.partialRight(template, previousSegment.length(), 0, previousSegment.q) # not using q, i.e. not highways templateBranch = _.partialRight( template, config.mapGeneration.DEFAULT_SEGMENT_LENGTH, if previousSegment.q.highway then config.mapGeneration.NORMAL_BRANCH_TIME_DELAY_FROM_HIGHWAY else 0) continueStraight = templateContinue(previousSegment.dir()) straightPop = heatmap.popOnRoad(continueStraight.r) if (previousSegment.q.highway) randomStraight = templateContinue(previousSegment.dir() + config.mapGeneration.RANDOM_STRAIGHT_ANGLE()) randomPop = heatmap.popOnRoad(randomStraight.r) roadPop if (randomPop > straightPop) newBranches.push(randomStraight) roadPop = randomPop else newBranches.push(continueStraight) roadPop = straightPop if (roadPop > config.mapGeneration.HIGHWAY_BRANCH_POPULATION_THRESHOLD) if (Math.random() < config.mapGeneration.HIGHWAY_BRANCH_PROBABILITY) leftHighwayBranch = templateContinue(previousSegment.dir() - 90 + config.mapGeneration.RANDOM_BRANCH_ANGLE()) newBranches.push(leftHighwayBranch) else if (Math.random() < config.mapGeneration.HIGHWAY_BRANCH_PROBABILITY) rightHighwayBranch = templateContinue(previousSegment.dir() + 90 + config.mapGeneration.RANDOM_BRANCH_ANGLE()) newBranches.push(rightHighwayBranch) else if (straightPop > config.mapGeneration.NORMAL_BRANCH_POPULATION_THRESHOLD) newBranches.push(continueStraight) if (straightPop > config.mapGeneration.NORMAL_BRANCH_POPULATION_THRESHOLD) if (Math.random() < config.mapGeneration.DEFAULT_BRANCH_PROBABILITY) leftBranch = templateBranch(previousSegment.dir() - 90 + config.mapGeneration.RANDOM_BRANCH_ANGLE()) newBranches.push(leftBranch) else if (Math.random() < config.mapGeneration.DEFAULT_BRANCH_PROBABILITY) rightBranch = templateBranch(previousSegment.dir() + 90 + config.mapGeneration.RANDOM_BRANCH_ANGLE()) newBranches.push(rightBranch) for i in [0..newBranches.length-1] by 1 do (branch = newBranches[i]) -> branch.setupBranchLinks = -> # setup links between each current branch and each existing branch stemming from the previous segment _.each(previousSegment.links.f, (link) -> @links.b.push(link) link.linksForEndContaining(previousSegment).push(this) , @) previousSegment.links.f.push(@) @links.b.push(previousSegment) return newBranches } addSegment = (segment, segmentList, qTree) -> segmentList.push(segment) qTree.insert(segment.collider.limits()) generate = (seed) -> debugData = {} Math.seedrandom(seed) # this perlin noise library only supports 65536 different seeds noise.seed(Math.random()) priorityQ = [] # setup first segments in queue do -> rootSegment = new Segment({x: 0, y: 0}, {x: config.mapGeneration.HIGHWAY_SEGMENT_LENGTH, y: 0}, 0, {highway: true}) oppositeDirection = segmentFactory.fromExisting(rootSegment) newEnd = x: rootSegment.r.start.x - config.mapGeneration.HIGHWAY_SEGMENT_LENGTH y: oppositeDirection.r.end.y oppositeDirection.r.setEnd(newEnd) oppositeDirection.links.b.push(rootSegment) rootSegment.links.b.push(oppositeDirection) priorityQ.push(rootSegment) priorityQ.push(oppositeDirection) segments = [] qTree = new Quadtree(config.mapGeneration.QUADTREE_PARAMS, config.mapGeneration.QUADTREE_MAX_OBJECTS, config.mapGeneration.QUADTREE_MAX_LEVELS) while (priorityQ.length > 0 && segments.length < config.mapGeneration.SEGMENT_COUNT_LIMIT) # pop smallest r(ti, ri, qi) from Q (i.e., smallest ‘t’) minT = undefined minT_i = 0 _.each(priorityQ, (segment, i) -> if (!minT? || segment.t < minT) minT = segment.t minT_i = i ) minSegment = priorityQ.splice(minT_i, 1)[0] accepted = localConstraints(minSegment, segments, qTree, debugData) if (accepted) if (minSegment.setupBranchLinks?) minSegment.setupBranchLinks() addSegment(minSegment, segments, qTree) _.each(globalGoals.generate(minSegment), (newSegment) -> newSegment.t = minSegment.t + 1 + newSegment.t priorityQ.push(newSegment) ) id = 0 for segment in segments segment.id = id++ console.log("#{segments.length} segments generated.") return { segments: segments qTree: qTree heatmap: heatmap debugData: debugData } module.exports = { Segment: Segment generate: generate }
[ { "context": "nal _props', ->\n thing = new Thing\n one: 'Hello'\n two: 'World'\n \n expect(thing._props[", "end": 242, "score": 0.9035449028015137, "start": 237, "tag": "NAME", "value": "Hello" }, { "context": "en created', ->\n thing = new Thing\n one: 'Hello'\n \n expect(thing.two).toEqual undefined\n ", "end": 532, "score": 0.9273489713668823, "start": 527, "tag": "NAME", "value": "Hello" }, { "context": "al 'Defacto!'\n\n thing2 = new Thing\n one: 'Hello'\n three: 'World'\n \n expect(thing2.thre", "end": 663, "score": 0.8019633293151855, "start": 658, "tag": "NAME", "value": "Hello" } ]
spec/model.spec.coffee
brianewing/footrest
1
Model = require('../lib/index').Model class Thing extends Model @type 'Thing' @attr 'one', 'two' @attr 'three', default: 'Defacto!' describe 'model', -> it 'should assign internal _props', -> thing = new Thing one: 'Hello' two: 'World' expect(thing._props['one']).toEqual 'Hello' expect(thing._props['two']).toEqual 'World' thing.one = 'Mad' expect(thing._props['one']).toEqual 'Mad' it 'should assign default parameters when created', -> thing = new Thing one: 'Hello' expect(thing.two).toEqual undefined expect(thing.three).toEqual 'Defacto!' thing2 = new Thing one: 'Hello' three: 'World' expect(thing2.three).toEqual 'World'
45690
Model = require('../lib/index').Model class Thing extends Model @type 'Thing' @attr 'one', 'two' @attr 'three', default: 'Defacto!' describe 'model', -> it 'should assign internal _props', -> thing = new Thing one: '<NAME>' two: 'World' expect(thing._props['one']).toEqual 'Hello' expect(thing._props['two']).toEqual 'World' thing.one = 'Mad' expect(thing._props['one']).toEqual 'Mad' it 'should assign default parameters when created', -> thing = new Thing one: '<NAME>' expect(thing.two).toEqual undefined expect(thing.three).toEqual 'Defacto!' thing2 = new Thing one: '<NAME>' three: 'World' expect(thing2.three).toEqual 'World'
true
Model = require('../lib/index').Model class Thing extends Model @type 'Thing' @attr 'one', 'two' @attr 'three', default: 'Defacto!' describe 'model', -> it 'should assign internal _props', -> thing = new Thing one: 'PI:NAME:<NAME>END_PI' two: 'World' expect(thing._props['one']).toEqual 'Hello' expect(thing._props['two']).toEqual 'World' thing.one = 'Mad' expect(thing._props['one']).toEqual 'Mad' it 'should assign default parameters when created', -> thing = new Thing one: 'PI:NAME:<NAME>END_PI' expect(thing.two).toEqual undefined expect(thing.three).toEqual 'Defacto!' thing2 = new Thing one: 'PI:NAME:<NAME>END_PI' three: 'World' expect(thing2.three).toEqual 'World'
[ { "context": "y on caffeine\n# website: http://moofx.it\n# author: Valerio Proietti (@kamicane) http://mad4milk.net http://mootools.n", "end": 118, "score": 0.9998477101325989, "start": 102, "tag": "NAME", "value": "Valerio Proietti" }, { "context": "ebsite: http://moofx.it\n# author: Valerio Proietti (@kamicane) http://mad4milk.net http://mootools.net\n# licens", "end": 129, "score": 0.9995830655097961, "start": 119, "tag": "USERNAME", "value": "(@kamicane" } ]
src/moofx.coffee
sebmarkbage/moofx
2
# moofx: a css3-enabled javascript animation library on caffeine # website: http://moofx.it # author: Valerio Proietti (@kamicane) http://mad4milk.net http://mootools.net # license: MIT µ = (nod) -> @valueOf = () -> nod @ moofx = (nod) -> if not nod then null else new µ(if nod.length? then nod else if nod.nodeType? then [nod] else []) moofx:: = µ:: # namespace: This takes advantage of coffeescript --join. When files are joined, only one global closure is used, thus making the local moofx variable available to the other scripts. If compiled files are included separately for development, then the reference to moofx in those other files will instead catch window.moofx. In CommonJS environments (or ender) window.moofx will never get written, because, instead, module.exports is used as a namespace, and the other scripts will simply reference this local moofx variable, which equals to module.exports if typeof module isnt 'undefined' then module.exports = moofx else @moofx = moofx
112466
# moofx: a css3-enabled javascript animation library on caffeine # website: http://moofx.it # author: <NAME> (@kamicane) http://mad4milk.net http://mootools.net # license: MIT µ = (nod) -> @valueOf = () -> nod @ moofx = (nod) -> if not nod then null else new µ(if nod.length? then nod else if nod.nodeType? then [nod] else []) moofx:: = µ:: # namespace: This takes advantage of coffeescript --join. When files are joined, only one global closure is used, thus making the local moofx variable available to the other scripts. If compiled files are included separately for development, then the reference to moofx in those other files will instead catch window.moofx. In CommonJS environments (or ender) window.moofx will never get written, because, instead, module.exports is used as a namespace, and the other scripts will simply reference this local moofx variable, which equals to module.exports if typeof module isnt 'undefined' then module.exports = moofx else @moofx = moofx
true
# moofx: a css3-enabled javascript animation library on caffeine # website: http://moofx.it # author: PI:NAME:<NAME>END_PI (@kamicane) http://mad4milk.net http://mootools.net # license: MIT µ = (nod) -> @valueOf = () -> nod @ moofx = (nod) -> if not nod then null else new µ(if nod.length? then nod else if nod.nodeType? then [nod] else []) moofx:: = µ:: # namespace: This takes advantage of coffeescript --join. When files are joined, only one global closure is used, thus making the local moofx variable available to the other scripts. If compiled files are included separately for development, then the reference to moofx in those other files will instead catch window.moofx. In CommonJS environments (or ender) window.moofx will never get written, because, instead, module.exports is used as a namespace, and the other scripts will simply reference this local moofx variable, which equals to module.exports if typeof module isnt 'undefined' then module.exports = moofx else @moofx = moofx
[ { "context": "I Key Authorization Middleware\n\nauthorizedKeys =\n y9c0MbNA7rkS412w: ['127.0.0.1']\n hwy4iavwi83ABUJq: ['67.23.22.71'", "end": 872, "score": 0.9972773194313049, "start": 856, "tag": "KEY", "value": "y9c0MbNA7rkS412w" }, { "context": "iddleware\n\nauthorizedKeys =\n y9c0MbNA7rkS412w: ['127.0.0.1']\n hwy4iavwi83ABUJq: ['67.23.22.71']\n fb91rfPFS", "end": 885, "score": 0.9997513890266418, "start": 876, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "MbNA7rkS412w: ['127.0.0.1']\n hwy4iavwi83ABUJq: ['67.23.22.71']\n fb91rfPFS84wmzH3: ['*']\n icecreamisdelish: [", "end": 921, "score": 0.9997476935386658, "start": 910, "tag": "IP_ADDRESS", "value": "67.23.22.71" }, { "context": "]\n fb91rfPFS84wmzH3: ['*']\n icecreamisdelish: ['198.74.6.22', '127.0.0.1']\n ripelliottcarter: ['75.72.186.16", "end": 983, "score": 0.9997405409812927, "start": 972, "tag": "IP_ADDRESS", "value": "198.74.6.22" }, { "context": "wmzH3: ['*']\n icecreamisdelish: ['198.74.6.22', '127.0.0.1']\n ripelliottcarter: ['75.72.186.169']\n\n\n# app.u", "end": 996, "score": 0.999756932258606, "start": 987, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "'198.74.6.22', '127.0.0.1']\n ripelliottcarter: ['75.72.186.169']\n\n\n# app.use '/device', (req, res, next) ->\n# ", "end": 1034, "score": 0.9997510313987732, "start": 1021, "tag": "IP_ADDRESS", "value": "75.72.186.169" }, { "context": "'\ndb = mongoose.createConnection 'mongodb://rosey:jetson@alex.mongohq.com:10092/Spark-History'\n\nSchema = mongoose.Schema\nOb", "end": 2007, "score": 0.9999020099639893, "start": 1984, "tag": "EMAIL", "value": "jetson@alex.mongohq.com" } ]
app.coffee
zsup/rosie
0
########################################## # BASIC REQUIREMENTS AND INITIALIZATION. # ########################################## # Require libraries net = require 'net' http = require 'http' # A JavaScript object helper to store devices devices = {} # Helpers for processing TCP stream. buffer = "" separator = "\n" # Ports tcpport = 1307 # Some helper functions. ts = -> d = new Date().toTimeString() index = d.indexOf " GMT" d = d.slice 0, index clog = (msg) -> console.log "#{ts()}: #{msg}" isNumber = (n) -> return !isNaN(parseFloat(n)) && isFinite(n) ### # EXPRESS WEB SERVER AND SOCKET.IO CONFIGURATION ### express = require 'express' routes = require './routes' path = require 'path' app = express() server = http.createServer app io = require('socket.io').listen(server) # API Key Authorization Middleware authorizedKeys = y9c0MbNA7rkS412w: ['127.0.0.1'] hwy4iavwi83ABUJq: ['67.23.22.71'] fb91rfPFS84wmzH3: ['*'] icecreamisdelish: ['198.74.6.22', '127.0.0.1'] ripelliottcarter: ['75.72.186.169'] # app.use '/device', (req, res, next) -> # authorizedIPs = authorizedKeys[req.query.api_key] # if authorizedIPs? and ('*' == authorizedIPs[0] or 0 <= authorizedIPs.indexOf(req.ip)) # next() # else # next "Unauthorized IP #{req.ip} for key #{req.query.api_key}" # Express configuration. app.configure -> @set 'port', process.env.ROSIE_PORT || 8080 @set 'views', "#{__dirname}/views" @set 'view engine', 'jade' @use express.favicon() @use express.bodyParser() @use express.methodOverride() @use app.router @use express.static path.join __dirname, 'public' app.configure 'development', -> @use express.errorHandler server.listen app.get('port'), -> clog "Express server listening on port " + app.get('port') # Socket.IO configuration. io.set 'log level', 1 io.set 'reconnect', false ### # MONGODB AND MONGOOSE CONFIGURATION ### mongoose = require 'mongoose' db = mongoose.createConnection 'mongodb://rosey:jetson@alex.mongohq.com:10092/Spark-History' Schema = mongoose.Schema ObjectId = Schema.ObjectId actionSchema = new Schema deviceid: String time: Date ip: String action: String param: String devicestatus: Boolean dimval: Number Action = db.model('Action', actionSchema) ### # OBJECT DEFINITIONS ### # Let's define our core object: the Device. class Device constructor: (@deviceid, @devicestatus = 0, @socket) -> @devicetype = "Device" commands: [ "turnOn" "turnOff" "toggle" "schedule" ] do: (action, params, ip) -> if @commands.indexOf(action) is -1 throw "#{action} is not a valid command" else return_values = @[action](params) @emit 'update' @store action, params, ip return_values # Update the device's status update: -> @message "getStatus" # Stringify for sharing over JSON. stringify: -> JSON.stringify deviceid: @deviceid devicetype: @devicetype devicestatus: @devicestatus turnOn: -> clog "Telling #{@deviceid} to turn on" @message "turnOn" @devicestatus = 1 turnOff: -> clog "Telling #{@deviceid} to turn off" @message "turnOff" @devicestatus = 0 toggle: -> if @devicestatus is 1 @turnOff() else @turnOn() # Schedule an action in the future. # TODO: Actually implement this schedule: (time) -> throw "Scheduling has not yet been implemented." # Send the requested message to the device message: (msg) -> # TODO: Expect a response, and add error-catching @socket.write "{#{@deviceid}:#{msg}}#{separator}" # Emit a message to the socket.IO sockets emit: (msg) -> if msg is 'add' or 'remove' or 'update' io.sockets.emit msg, @stringify else throw "Bad socket.IO message" # Add the action to the history store: (action, params, ip) -> x = new Action deviceid: @deviceid time: new Date().toISOString() ip: ip action: action params: params devicestatus: @devicestatus x.save() clog "Stored #{action} in database" # Lights are just like any other device, except they are also dimmable. # They have a special function, "pulse", that flashes the light. class Light extends Device constructor: (@deviceid, @devicestatus = 0, @dimval = 255, @socket) -> @devicetype = "Light" commands: [ "turnOn" "turnOff" "toggle" "schedule" "dim" "pulse" "fade" "color" ] # Stringify for sharing over JSON. stringify: -> JSON.stringify deviceid: @deviceid devicetype: @devicetype devicestatus: @devicestatus dimval: @dimval pulse: -> clog "Telling #{@deviceid} to pulse" @message "pulse" color: (params) -> clog "Telling #{@deviceid} to change color to #{params}" @message "led#{params}" dim: (params) -> value = parseInt params[0] if 0 <= value <= 255 clog "Sending dim #{value} to #{@deviceid}" @message "dim#{value}" @dimval = value else clog "ERROR: Bad dim value: #{value}" # TODO: Error message back to API user max_target: 12 max_duration_ms: 600000 default_duration_ms: 400 fade: (params) -> target = params[0] duration_ms = params[1] ? @default_duration_ms if isNaN(target) throw "Fade target #{target} is not a number." if target < 0 or target > @max_target throw "Fade target #{target} must be an integer between 0 and #{@max_target}, inclusive." if isNaN(duration_ms) or duration_ms < 0 then duration_ms = @default_duration_ms if duration_ms > @max_duration_ms then duration_ms = @max_duration_ms clog "Telling #{@deviceid} to fade to #{target} over #{duration_ms} milliseconds" @message "fade #{target} #{duration_ms}" [target, duration_ms] # Add the action to the history store: (action, params, ip) -> x = new Action deviceid: @deviceid time: new Date().toISOString() ip: ip action: action params: params devicestatus: @devicestatus dimval: @dimval x.save() clog "Stored #{action} in database" # Arduinos are like other devices but they have up to 6 'components' # that can be individually controlled. # # Components essentially map to 'pins' on the micro-controller, # and 'on' maps to 'HIGH' whereas 'off' maps to 'LOW'. class Arduino extends Device max_components = 6 constructor: (@deviceid, @devicestatus = "000000", @socket) -> @devicetype = "Arduino" commands: [ "turnOn" "turnOff" "toggle" "schedule" "set" "cycle" ] turnOn: (component) -> if isNumber(component) component = Number(component) throw "Too many components" if component >= max_components clog "Telling component #{component} of #{@deviceid} to turn on" @message "component #{component} 1" @devicestatus = @devicestatus.substring(0, component) + "1" + @devicestatus.substring(component+1) else clog "Telling #{@deviceid} to turn on" @message "turnOn" @devicestatus = "111111" turnOff: (component) -> if isNumber(component) component = Number(component) throw "Too many components" if component >= max_components clog "Telling component #{component} of #{@deviceid} to turn off" @message "component #{component} 0" @devicestatus = @devicestatus.substring(0, component) + "0" + @devicestatus.substring(component+1) else clog "Telling #{@deviceid} to turn off" @message "turnOff" @devicestatus = "000000" toggle: (component) -> if isNumber(component) && component < max_components if @devicestatus.charAt(component) is "0" @turnOn component else @turnOff component else throw "Bad component number." set: (levels) -> components = levels.length throw "Too many components." if components > max_components clog "Setting component levels to #{levels}" @message "set #{levels}" @devicestatus = levels cycle: -> clog "Cycling components" @message "cycle" @devicestatus = "000000" ########################################## # ROUTING FOR THE WEB APP. # ########################################## ### # FRONT-END FOR TESTING. ### app.get '/', (req, res) -> res.render 'index.jade', { devices: devices } app.get '/buttons', (req, res) -> res.render 'buttons.jade' ### # GETS. ### # Routing for 'get status' HTTP requests app.get '/device/:deviceid', (req, res) -> deviceid = req.params.deviceid device = devices[deviceid] if device? clog "Get latest status from #{device.deviceid}" device.update() clog "Sending status of #{device.deviceid} to client" clog device.stringify() res.send 200, device.stringify() else clog "ERR: Request for status of #{req.params.deviceid} received; device not found" res.send 404, "No device connected with ID #{deviceid}." # Routing for seeing device logs. app.get '/device/:deviceid/logs', (req, res) -> # TODO: Implement this feature res.send 404, "Sorry, this feature has not yet been implemented." ### # COMMANDS. ### app.put '/device/:deviceid/fade/:target/:duration_ms', (req, res) -> device = devices[req.params.deviceid] if device? target = parseInt req.params.target, 10 duration_ms = parseInt req.params.duration_ms, 10 try [target, duration_ms] = device.do('fade', [target, duration_ms], req.ip) res.send 200, "Message sent to #{device.deviceid} to fade to #{target} over #{duration_ms} milliseconds" catch err res.send 400, "Not a valid request. #{err}" else res.send 404, "No device connected with ID #{req.params.deviceid}" # Routing for 'command' http requests (API) app.put '/device/:deviceid/:action/:param?', (req, res) -> deviceid = req.params.deviceid action = req.params.action if req.params.param? param = req.params.param clog "HTTP request received for device #{deviceid} to #{action} to #{param}" else param = "" clog "HTTP request received for device #{deviceid} to #{action}" # If the device is connected, send it a message if devices[deviceid]? device = devices[deviceid] try device.do(action, [param], req.ip) res.send 200, "Message sent to #{deviceid} to #{action}." catch err res.send 460, "Not a valid request. #{err}" clog "Not a valid request." else res.send 404, "No device connected with ID #{deviceid}" ### # SCHEDULING. ### # Schedule a new action. Has not yet been implemented. app.post '/device/:deviceid/schedule/:action/:time', (req, res) -> # TODO: Implement res.send 460, "Scheduling has not yet been implemented." # Delete a scheduled action. You only need to know the timecode. # Also you must be the one who scheduled an action in the first place to delete it. app.delete '/device/:deviceid/schedule/:time', (req, res) -> # TODO: Implement res.send 460, "Scheduling has not yet been implemented." ### # HISTORY. ### app.get '/device/:deviceid/history/:entries?', (req, res) -> deviceid = req.params.deviceid Action.find { deviceid: deviceid }, null, { limit: req.params.entries || 20 }, (err, actions) -> if err res.send 404, "Database error." else if actions.length is 0 res.send 404, "No history for that device. Doesn't exist... yet." else response = {} response.deviceid = deviceid for action in actions do (action) -> response[action._id] = { time: action.time ip: action.ip action: action.action devicestatus: action.devicestatus dimval: action.dimval } res.send 200, response ########################################## # TCP SERVER FOR DEVICES. # ########################################## # Create the TCP server to communicate with the Arduino. server = net.createServer (socket) -> clog 'TCP client connected' socket.setEncoding 'ascii' socket.setKeepAlive true, 30000 socket.on 'close', -> for deviceid, device of devices if device.socket is socket device.emit 'remove' delete devices[deviceid] clog "Device #{deviceid} disconnected" clog 'TCP client disconnected' # Receive and parse incoming data socket.on 'data', (chunk) -> buffer += chunk clog "Message received: #{chunk}" separatorIndex = buffer.indexOf separator foundMessage = separatorIndex != -1 while separatorIndex != -1 message = buffer.slice 0, separatorIndex processmsg message, socket buffer = buffer.slice(separatorIndex + 1) separatorIndex = buffer.indexOf separator # Fire up the TCP server server.listen tcpport, -> clog "TCP server bound to port #{tcpport}" # Process messages. # # Note: this is only used for instantiation right now. # In the future we'll have to break this up. # processmsg = (message, socket) -> message = message.trim() clog "Processing message: #{message}" failure = false try msgobj = JSON.parse message catch SyntaxError failure = true clog "Failed to process - bad syntax" return enoughinfo = msgobj.hasOwnProperty 'deviceid' if not enoughinfo clog "Not enough info" return currentdevice = devices[msgobj.deviceid] if not currentdevice? # well formed input - add device to list of devices deviceid = msgobj.deviceid devicetype = msgobj.devicetype ? "Light" devicestatus = msgobj.devicestatus dimval = msgobj.dimval if devicetype is "Light" devices[deviceid] = new Light(deviceid, devicestatus, dimval, socket) else if devicetype is "Arduino" devices[deviceid] = new Arduino(deviceid, devicestatus, socket) else devices[deviceid] = new Device(deviceid, devicestatus, socket) devices[deviceid].emit 'add' clog "Added: #{deviceid}" else if msgobj.devicestatus? then currentdevice.devicestatus = msgobj.devicestatus if msgobj.dimval? then currentdevice.dimval = msgobj.dimval if socket isnt currentdevice.socket then currentdevice.socket = socket currentdevice.emit 'update' clog "Updated: #{msgobj.deviceid}" ############################################################################################ # SOCKET.IO communications # # # # Perfect for telling developers/apps when a device's status has changed. # # Also gives the developer a list of devices when they connect. Good for testing. # # May be implemented in a different way in the future (PubSub?) but this works for now. # # # # Emit function deprecated. Using an emit method in the device instead. # ############################################################################################ # When a socket connects, give it a list of devices by adding them in sequence. io.sockets.on 'connection', (iosocket) -> clog "Got new socket" for deviceid, device of devices clog "Add device #{device.deviceid}" device.emit 'add' iosocket.on 'disconnect', -> clog "Socket disconnected" ########################################## # OTHER JUNK. # ########################################## # Routing for a few redirects app.get '/demo', (req, res) -> res.redirect 'http://www.youtube.com/watch?v=IOncq-OM3_g' app.get '/demo2', (req, res) -> res.redirect 'http://www.youtube.com/watch?v=8hsvGO4FHNo' app.get '/demo3', (req, res) -> res.redirect 'http://www.youtube.com/watch?v=fLkIoJ3BXEw' app.get '/founders', (req, res) -> res.redirect 'http://www.youtube.com/watch?v=71ucyxj1wbk'
33502
########################################## # BASIC REQUIREMENTS AND INITIALIZATION. # ########################################## # Require libraries net = require 'net' http = require 'http' # A JavaScript object helper to store devices devices = {} # Helpers for processing TCP stream. buffer = "" separator = "\n" # Ports tcpport = 1307 # Some helper functions. ts = -> d = new Date().toTimeString() index = d.indexOf " GMT" d = d.slice 0, index clog = (msg) -> console.log "#{ts()}: #{msg}" isNumber = (n) -> return !isNaN(parseFloat(n)) && isFinite(n) ### # EXPRESS WEB SERVER AND SOCKET.IO CONFIGURATION ### express = require 'express' routes = require './routes' path = require 'path' app = express() server = http.createServer app io = require('socket.io').listen(server) # API Key Authorization Middleware authorizedKeys = <KEY>: ['127.0.0.1'] hwy4iavwi83ABUJq: ['172.16.17.32'] fb91rfPFS84wmzH3: ['*'] icecreamisdelish: ['192.168.127.12', '127.0.0.1'] ripelliottcarter: ['192.168.3.11'] # app.use '/device', (req, res, next) -> # authorizedIPs = authorizedKeys[req.query.api_key] # if authorizedIPs? and ('*' == authorizedIPs[0] or 0 <= authorizedIPs.indexOf(req.ip)) # next() # else # next "Unauthorized IP #{req.ip} for key #{req.query.api_key}" # Express configuration. app.configure -> @set 'port', process.env.ROSIE_PORT || 8080 @set 'views', "#{__dirname}/views" @set 'view engine', 'jade' @use express.favicon() @use express.bodyParser() @use express.methodOverride() @use app.router @use express.static path.join __dirname, 'public' app.configure 'development', -> @use express.errorHandler server.listen app.get('port'), -> clog "Express server listening on port " + app.get('port') # Socket.IO configuration. io.set 'log level', 1 io.set 'reconnect', false ### # MONGODB AND MONGOOSE CONFIGURATION ### mongoose = require 'mongoose' db = mongoose.createConnection 'mongodb://rosey:<EMAIL>:10092/Spark-History' Schema = mongoose.Schema ObjectId = Schema.ObjectId actionSchema = new Schema deviceid: String time: Date ip: String action: String param: String devicestatus: Boolean dimval: Number Action = db.model('Action', actionSchema) ### # OBJECT DEFINITIONS ### # Let's define our core object: the Device. class Device constructor: (@deviceid, @devicestatus = 0, @socket) -> @devicetype = "Device" commands: [ "turnOn" "turnOff" "toggle" "schedule" ] do: (action, params, ip) -> if @commands.indexOf(action) is -1 throw "#{action} is not a valid command" else return_values = @[action](params) @emit 'update' @store action, params, ip return_values # Update the device's status update: -> @message "getStatus" # Stringify for sharing over JSON. stringify: -> JSON.stringify deviceid: @deviceid devicetype: @devicetype devicestatus: @devicestatus turnOn: -> clog "Telling #{@deviceid} to turn on" @message "turnOn" @devicestatus = 1 turnOff: -> clog "Telling #{@deviceid} to turn off" @message "turnOff" @devicestatus = 0 toggle: -> if @devicestatus is 1 @turnOff() else @turnOn() # Schedule an action in the future. # TODO: Actually implement this schedule: (time) -> throw "Scheduling has not yet been implemented." # Send the requested message to the device message: (msg) -> # TODO: Expect a response, and add error-catching @socket.write "{#{@deviceid}:#{msg}}#{separator}" # Emit a message to the socket.IO sockets emit: (msg) -> if msg is 'add' or 'remove' or 'update' io.sockets.emit msg, @stringify else throw "Bad socket.IO message" # Add the action to the history store: (action, params, ip) -> x = new Action deviceid: @deviceid time: new Date().toISOString() ip: ip action: action params: params devicestatus: @devicestatus x.save() clog "Stored #{action} in database" # Lights are just like any other device, except they are also dimmable. # They have a special function, "pulse", that flashes the light. class Light extends Device constructor: (@deviceid, @devicestatus = 0, @dimval = 255, @socket) -> @devicetype = "Light" commands: [ "turnOn" "turnOff" "toggle" "schedule" "dim" "pulse" "fade" "color" ] # Stringify for sharing over JSON. stringify: -> JSON.stringify deviceid: @deviceid devicetype: @devicetype devicestatus: @devicestatus dimval: @dimval pulse: -> clog "Telling #{@deviceid} to pulse" @message "pulse" color: (params) -> clog "Telling #{@deviceid} to change color to #{params}" @message "led#{params}" dim: (params) -> value = parseInt params[0] if 0 <= value <= 255 clog "Sending dim #{value} to #{@deviceid}" @message "dim#{value}" @dimval = value else clog "ERROR: Bad dim value: #{value}" # TODO: Error message back to API user max_target: 12 max_duration_ms: 600000 default_duration_ms: 400 fade: (params) -> target = params[0] duration_ms = params[1] ? @default_duration_ms if isNaN(target) throw "Fade target #{target} is not a number." if target < 0 or target > @max_target throw "Fade target #{target} must be an integer between 0 and #{@max_target}, inclusive." if isNaN(duration_ms) or duration_ms < 0 then duration_ms = @default_duration_ms if duration_ms > @max_duration_ms then duration_ms = @max_duration_ms clog "Telling #{@deviceid} to fade to #{target} over #{duration_ms} milliseconds" @message "fade #{target} #{duration_ms}" [target, duration_ms] # Add the action to the history store: (action, params, ip) -> x = new Action deviceid: @deviceid time: new Date().toISOString() ip: ip action: action params: params devicestatus: @devicestatus dimval: @dimval x.save() clog "Stored #{action} in database" # Arduinos are like other devices but they have up to 6 'components' # that can be individually controlled. # # Components essentially map to 'pins' on the micro-controller, # and 'on' maps to 'HIGH' whereas 'off' maps to 'LOW'. class Arduino extends Device max_components = 6 constructor: (@deviceid, @devicestatus = "000000", @socket) -> @devicetype = "Arduino" commands: [ "turnOn" "turnOff" "toggle" "schedule" "set" "cycle" ] turnOn: (component) -> if isNumber(component) component = Number(component) throw "Too many components" if component >= max_components clog "Telling component #{component} of #{@deviceid} to turn on" @message "component #{component} 1" @devicestatus = @devicestatus.substring(0, component) + "1" + @devicestatus.substring(component+1) else clog "Telling #{@deviceid} to turn on" @message "turnOn" @devicestatus = "111111" turnOff: (component) -> if isNumber(component) component = Number(component) throw "Too many components" if component >= max_components clog "Telling component #{component} of #{@deviceid} to turn off" @message "component #{component} 0" @devicestatus = @devicestatus.substring(0, component) + "0" + @devicestatus.substring(component+1) else clog "Telling #{@deviceid} to turn off" @message "turnOff" @devicestatus = "000000" toggle: (component) -> if isNumber(component) && component < max_components if @devicestatus.charAt(component) is "0" @turnOn component else @turnOff component else throw "Bad component number." set: (levels) -> components = levels.length throw "Too many components." if components > max_components clog "Setting component levels to #{levels}" @message "set #{levels}" @devicestatus = levels cycle: -> clog "Cycling components" @message "cycle" @devicestatus = "000000" ########################################## # ROUTING FOR THE WEB APP. # ########################################## ### # FRONT-END FOR TESTING. ### app.get '/', (req, res) -> res.render 'index.jade', { devices: devices } app.get '/buttons', (req, res) -> res.render 'buttons.jade' ### # GETS. ### # Routing for 'get status' HTTP requests app.get '/device/:deviceid', (req, res) -> deviceid = req.params.deviceid device = devices[deviceid] if device? clog "Get latest status from #{device.deviceid}" device.update() clog "Sending status of #{device.deviceid} to client" clog device.stringify() res.send 200, device.stringify() else clog "ERR: Request for status of #{req.params.deviceid} received; device not found" res.send 404, "No device connected with ID #{deviceid}." # Routing for seeing device logs. app.get '/device/:deviceid/logs', (req, res) -> # TODO: Implement this feature res.send 404, "Sorry, this feature has not yet been implemented." ### # COMMANDS. ### app.put '/device/:deviceid/fade/:target/:duration_ms', (req, res) -> device = devices[req.params.deviceid] if device? target = parseInt req.params.target, 10 duration_ms = parseInt req.params.duration_ms, 10 try [target, duration_ms] = device.do('fade', [target, duration_ms], req.ip) res.send 200, "Message sent to #{device.deviceid} to fade to #{target} over #{duration_ms} milliseconds" catch err res.send 400, "Not a valid request. #{err}" else res.send 404, "No device connected with ID #{req.params.deviceid}" # Routing for 'command' http requests (API) app.put '/device/:deviceid/:action/:param?', (req, res) -> deviceid = req.params.deviceid action = req.params.action if req.params.param? param = req.params.param clog "HTTP request received for device #{deviceid} to #{action} to #{param}" else param = "" clog "HTTP request received for device #{deviceid} to #{action}" # If the device is connected, send it a message if devices[deviceid]? device = devices[deviceid] try device.do(action, [param], req.ip) res.send 200, "Message sent to #{deviceid} to #{action}." catch err res.send 460, "Not a valid request. #{err}" clog "Not a valid request." else res.send 404, "No device connected with ID #{deviceid}" ### # SCHEDULING. ### # Schedule a new action. Has not yet been implemented. app.post '/device/:deviceid/schedule/:action/:time', (req, res) -> # TODO: Implement res.send 460, "Scheduling has not yet been implemented." # Delete a scheduled action. You only need to know the timecode. # Also you must be the one who scheduled an action in the first place to delete it. app.delete '/device/:deviceid/schedule/:time', (req, res) -> # TODO: Implement res.send 460, "Scheduling has not yet been implemented." ### # HISTORY. ### app.get '/device/:deviceid/history/:entries?', (req, res) -> deviceid = req.params.deviceid Action.find { deviceid: deviceid }, null, { limit: req.params.entries || 20 }, (err, actions) -> if err res.send 404, "Database error." else if actions.length is 0 res.send 404, "No history for that device. Doesn't exist... yet." else response = {} response.deviceid = deviceid for action in actions do (action) -> response[action._id] = { time: action.time ip: action.ip action: action.action devicestatus: action.devicestatus dimval: action.dimval } res.send 200, response ########################################## # TCP SERVER FOR DEVICES. # ########################################## # Create the TCP server to communicate with the Arduino. server = net.createServer (socket) -> clog 'TCP client connected' socket.setEncoding 'ascii' socket.setKeepAlive true, 30000 socket.on 'close', -> for deviceid, device of devices if device.socket is socket device.emit 'remove' delete devices[deviceid] clog "Device #{deviceid} disconnected" clog 'TCP client disconnected' # Receive and parse incoming data socket.on 'data', (chunk) -> buffer += chunk clog "Message received: #{chunk}" separatorIndex = buffer.indexOf separator foundMessage = separatorIndex != -1 while separatorIndex != -1 message = buffer.slice 0, separatorIndex processmsg message, socket buffer = buffer.slice(separatorIndex + 1) separatorIndex = buffer.indexOf separator # Fire up the TCP server server.listen tcpport, -> clog "TCP server bound to port #{tcpport}" # Process messages. # # Note: this is only used for instantiation right now. # In the future we'll have to break this up. # processmsg = (message, socket) -> message = message.trim() clog "Processing message: #{message}" failure = false try msgobj = JSON.parse message catch SyntaxError failure = true clog "Failed to process - bad syntax" return enoughinfo = msgobj.hasOwnProperty 'deviceid' if not enoughinfo clog "Not enough info" return currentdevice = devices[msgobj.deviceid] if not currentdevice? # well formed input - add device to list of devices deviceid = msgobj.deviceid devicetype = msgobj.devicetype ? "Light" devicestatus = msgobj.devicestatus dimval = msgobj.dimval if devicetype is "Light" devices[deviceid] = new Light(deviceid, devicestatus, dimval, socket) else if devicetype is "Arduino" devices[deviceid] = new Arduino(deviceid, devicestatus, socket) else devices[deviceid] = new Device(deviceid, devicestatus, socket) devices[deviceid].emit 'add' clog "Added: #{deviceid}" else if msgobj.devicestatus? then currentdevice.devicestatus = msgobj.devicestatus if msgobj.dimval? then currentdevice.dimval = msgobj.dimval if socket isnt currentdevice.socket then currentdevice.socket = socket currentdevice.emit 'update' clog "Updated: #{msgobj.deviceid}" ############################################################################################ # SOCKET.IO communications # # # # Perfect for telling developers/apps when a device's status has changed. # # Also gives the developer a list of devices when they connect. Good for testing. # # May be implemented in a different way in the future (PubSub?) but this works for now. # # # # Emit function deprecated. Using an emit method in the device instead. # ############################################################################################ # When a socket connects, give it a list of devices by adding them in sequence. io.sockets.on 'connection', (iosocket) -> clog "Got new socket" for deviceid, device of devices clog "Add device #{device.deviceid}" device.emit 'add' iosocket.on 'disconnect', -> clog "Socket disconnected" ########################################## # OTHER JUNK. # ########################################## # Routing for a few redirects app.get '/demo', (req, res) -> res.redirect 'http://www.youtube.com/watch?v=IOncq-OM3_g' app.get '/demo2', (req, res) -> res.redirect 'http://www.youtube.com/watch?v=8hsvGO4FHNo' app.get '/demo3', (req, res) -> res.redirect 'http://www.youtube.com/watch?v=fLkIoJ3BXEw' app.get '/founders', (req, res) -> res.redirect 'http://www.youtube.com/watch?v=71ucyxj1wbk'
true
########################################## # BASIC REQUIREMENTS AND INITIALIZATION. # ########################################## # Require libraries net = require 'net' http = require 'http' # A JavaScript object helper to store devices devices = {} # Helpers for processing TCP stream. buffer = "" separator = "\n" # Ports tcpport = 1307 # Some helper functions. ts = -> d = new Date().toTimeString() index = d.indexOf " GMT" d = d.slice 0, index clog = (msg) -> console.log "#{ts()}: #{msg}" isNumber = (n) -> return !isNaN(parseFloat(n)) && isFinite(n) ### # EXPRESS WEB SERVER AND SOCKET.IO CONFIGURATION ### express = require 'express' routes = require './routes' path = require 'path' app = express() server = http.createServer app io = require('socket.io').listen(server) # API Key Authorization Middleware authorizedKeys = PI:KEY:<KEY>END_PI: ['127.0.0.1'] hwy4iavwi83ABUJq: ['PI:IP_ADDRESS:172.16.17.32END_PI'] fb91rfPFS84wmzH3: ['*'] icecreamisdelish: ['PI:IP_ADDRESS:192.168.127.12END_PI', '127.0.0.1'] ripelliottcarter: ['PI:IP_ADDRESS:192.168.3.11END_PI'] # app.use '/device', (req, res, next) -> # authorizedIPs = authorizedKeys[req.query.api_key] # if authorizedIPs? and ('*' == authorizedIPs[0] or 0 <= authorizedIPs.indexOf(req.ip)) # next() # else # next "Unauthorized IP #{req.ip} for key #{req.query.api_key}" # Express configuration. app.configure -> @set 'port', process.env.ROSIE_PORT || 8080 @set 'views', "#{__dirname}/views" @set 'view engine', 'jade' @use express.favicon() @use express.bodyParser() @use express.methodOverride() @use app.router @use express.static path.join __dirname, 'public' app.configure 'development', -> @use express.errorHandler server.listen app.get('port'), -> clog "Express server listening on port " + app.get('port') # Socket.IO configuration. io.set 'log level', 1 io.set 'reconnect', false ### # MONGODB AND MONGOOSE CONFIGURATION ### mongoose = require 'mongoose' db = mongoose.createConnection 'mongodb://rosey:PI:EMAIL:<EMAIL>END_PI:10092/Spark-History' Schema = mongoose.Schema ObjectId = Schema.ObjectId actionSchema = new Schema deviceid: String time: Date ip: String action: String param: String devicestatus: Boolean dimval: Number Action = db.model('Action', actionSchema) ### # OBJECT DEFINITIONS ### # Let's define our core object: the Device. class Device constructor: (@deviceid, @devicestatus = 0, @socket) -> @devicetype = "Device" commands: [ "turnOn" "turnOff" "toggle" "schedule" ] do: (action, params, ip) -> if @commands.indexOf(action) is -1 throw "#{action} is not a valid command" else return_values = @[action](params) @emit 'update' @store action, params, ip return_values # Update the device's status update: -> @message "getStatus" # Stringify for sharing over JSON. stringify: -> JSON.stringify deviceid: @deviceid devicetype: @devicetype devicestatus: @devicestatus turnOn: -> clog "Telling #{@deviceid} to turn on" @message "turnOn" @devicestatus = 1 turnOff: -> clog "Telling #{@deviceid} to turn off" @message "turnOff" @devicestatus = 0 toggle: -> if @devicestatus is 1 @turnOff() else @turnOn() # Schedule an action in the future. # TODO: Actually implement this schedule: (time) -> throw "Scheduling has not yet been implemented." # Send the requested message to the device message: (msg) -> # TODO: Expect a response, and add error-catching @socket.write "{#{@deviceid}:#{msg}}#{separator}" # Emit a message to the socket.IO sockets emit: (msg) -> if msg is 'add' or 'remove' or 'update' io.sockets.emit msg, @stringify else throw "Bad socket.IO message" # Add the action to the history store: (action, params, ip) -> x = new Action deviceid: @deviceid time: new Date().toISOString() ip: ip action: action params: params devicestatus: @devicestatus x.save() clog "Stored #{action} in database" # Lights are just like any other device, except they are also dimmable. # They have a special function, "pulse", that flashes the light. class Light extends Device constructor: (@deviceid, @devicestatus = 0, @dimval = 255, @socket) -> @devicetype = "Light" commands: [ "turnOn" "turnOff" "toggle" "schedule" "dim" "pulse" "fade" "color" ] # Stringify for sharing over JSON. stringify: -> JSON.stringify deviceid: @deviceid devicetype: @devicetype devicestatus: @devicestatus dimval: @dimval pulse: -> clog "Telling #{@deviceid} to pulse" @message "pulse" color: (params) -> clog "Telling #{@deviceid} to change color to #{params}" @message "led#{params}" dim: (params) -> value = parseInt params[0] if 0 <= value <= 255 clog "Sending dim #{value} to #{@deviceid}" @message "dim#{value}" @dimval = value else clog "ERROR: Bad dim value: #{value}" # TODO: Error message back to API user max_target: 12 max_duration_ms: 600000 default_duration_ms: 400 fade: (params) -> target = params[0] duration_ms = params[1] ? @default_duration_ms if isNaN(target) throw "Fade target #{target} is not a number." if target < 0 or target > @max_target throw "Fade target #{target} must be an integer between 0 and #{@max_target}, inclusive." if isNaN(duration_ms) or duration_ms < 0 then duration_ms = @default_duration_ms if duration_ms > @max_duration_ms then duration_ms = @max_duration_ms clog "Telling #{@deviceid} to fade to #{target} over #{duration_ms} milliseconds" @message "fade #{target} #{duration_ms}" [target, duration_ms] # Add the action to the history store: (action, params, ip) -> x = new Action deviceid: @deviceid time: new Date().toISOString() ip: ip action: action params: params devicestatus: @devicestatus dimval: @dimval x.save() clog "Stored #{action} in database" # Arduinos are like other devices but they have up to 6 'components' # that can be individually controlled. # # Components essentially map to 'pins' on the micro-controller, # and 'on' maps to 'HIGH' whereas 'off' maps to 'LOW'. class Arduino extends Device max_components = 6 constructor: (@deviceid, @devicestatus = "000000", @socket) -> @devicetype = "Arduino" commands: [ "turnOn" "turnOff" "toggle" "schedule" "set" "cycle" ] turnOn: (component) -> if isNumber(component) component = Number(component) throw "Too many components" if component >= max_components clog "Telling component #{component} of #{@deviceid} to turn on" @message "component #{component} 1" @devicestatus = @devicestatus.substring(0, component) + "1" + @devicestatus.substring(component+1) else clog "Telling #{@deviceid} to turn on" @message "turnOn" @devicestatus = "111111" turnOff: (component) -> if isNumber(component) component = Number(component) throw "Too many components" if component >= max_components clog "Telling component #{component} of #{@deviceid} to turn off" @message "component #{component} 0" @devicestatus = @devicestatus.substring(0, component) + "0" + @devicestatus.substring(component+1) else clog "Telling #{@deviceid} to turn off" @message "turnOff" @devicestatus = "000000" toggle: (component) -> if isNumber(component) && component < max_components if @devicestatus.charAt(component) is "0" @turnOn component else @turnOff component else throw "Bad component number." set: (levels) -> components = levels.length throw "Too many components." if components > max_components clog "Setting component levels to #{levels}" @message "set #{levels}" @devicestatus = levels cycle: -> clog "Cycling components" @message "cycle" @devicestatus = "000000" ########################################## # ROUTING FOR THE WEB APP. # ########################################## ### # FRONT-END FOR TESTING. ### app.get '/', (req, res) -> res.render 'index.jade', { devices: devices } app.get '/buttons', (req, res) -> res.render 'buttons.jade' ### # GETS. ### # Routing for 'get status' HTTP requests app.get '/device/:deviceid', (req, res) -> deviceid = req.params.deviceid device = devices[deviceid] if device? clog "Get latest status from #{device.deviceid}" device.update() clog "Sending status of #{device.deviceid} to client" clog device.stringify() res.send 200, device.stringify() else clog "ERR: Request for status of #{req.params.deviceid} received; device not found" res.send 404, "No device connected with ID #{deviceid}." # Routing for seeing device logs. app.get '/device/:deviceid/logs', (req, res) -> # TODO: Implement this feature res.send 404, "Sorry, this feature has not yet been implemented." ### # COMMANDS. ### app.put '/device/:deviceid/fade/:target/:duration_ms', (req, res) -> device = devices[req.params.deviceid] if device? target = parseInt req.params.target, 10 duration_ms = parseInt req.params.duration_ms, 10 try [target, duration_ms] = device.do('fade', [target, duration_ms], req.ip) res.send 200, "Message sent to #{device.deviceid} to fade to #{target} over #{duration_ms} milliseconds" catch err res.send 400, "Not a valid request. #{err}" else res.send 404, "No device connected with ID #{req.params.deviceid}" # Routing for 'command' http requests (API) app.put '/device/:deviceid/:action/:param?', (req, res) -> deviceid = req.params.deviceid action = req.params.action if req.params.param? param = req.params.param clog "HTTP request received for device #{deviceid} to #{action} to #{param}" else param = "" clog "HTTP request received for device #{deviceid} to #{action}" # If the device is connected, send it a message if devices[deviceid]? device = devices[deviceid] try device.do(action, [param], req.ip) res.send 200, "Message sent to #{deviceid} to #{action}." catch err res.send 460, "Not a valid request. #{err}" clog "Not a valid request." else res.send 404, "No device connected with ID #{deviceid}" ### # SCHEDULING. ### # Schedule a new action. Has not yet been implemented. app.post '/device/:deviceid/schedule/:action/:time', (req, res) -> # TODO: Implement res.send 460, "Scheduling has not yet been implemented." # Delete a scheduled action. You only need to know the timecode. # Also you must be the one who scheduled an action in the first place to delete it. app.delete '/device/:deviceid/schedule/:time', (req, res) -> # TODO: Implement res.send 460, "Scheduling has not yet been implemented." ### # HISTORY. ### app.get '/device/:deviceid/history/:entries?', (req, res) -> deviceid = req.params.deviceid Action.find { deviceid: deviceid }, null, { limit: req.params.entries || 20 }, (err, actions) -> if err res.send 404, "Database error." else if actions.length is 0 res.send 404, "No history for that device. Doesn't exist... yet." else response = {} response.deviceid = deviceid for action in actions do (action) -> response[action._id] = { time: action.time ip: action.ip action: action.action devicestatus: action.devicestatus dimval: action.dimval } res.send 200, response ########################################## # TCP SERVER FOR DEVICES. # ########################################## # Create the TCP server to communicate with the Arduino. server = net.createServer (socket) -> clog 'TCP client connected' socket.setEncoding 'ascii' socket.setKeepAlive true, 30000 socket.on 'close', -> for deviceid, device of devices if device.socket is socket device.emit 'remove' delete devices[deviceid] clog "Device #{deviceid} disconnected" clog 'TCP client disconnected' # Receive and parse incoming data socket.on 'data', (chunk) -> buffer += chunk clog "Message received: #{chunk}" separatorIndex = buffer.indexOf separator foundMessage = separatorIndex != -1 while separatorIndex != -1 message = buffer.slice 0, separatorIndex processmsg message, socket buffer = buffer.slice(separatorIndex + 1) separatorIndex = buffer.indexOf separator # Fire up the TCP server server.listen tcpport, -> clog "TCP server bound to port #{tcpport}" # Process messages. # # Note: this is only used for instantiation right now. # In the future we'll have to break this up. # processmsg = (message, socket) -> message = message.trim() clog "Processing message: #{message}" failure = false try msgobj = JSON.parse message catch SyntaxError failure = true clog "Failed to process - bad syntax" return enoughinfo = msgobj.hasOwnProperty 'deviceid' if not enoughinfo clog "Not enough info" return currentdevice = devices[msgobj.deviceid] if not currentdevice? # well formed input - add device to list of devices deviceid = msgobj.deviceid devicetype = msgobj.devicetype ? "Light" devicestatus = msgobj.devicestatus dimval = msgobj.dimval if devicetype is "Light" devices[deviceid] = new Light(deviceid, devicestatus, dimval, socket) else if devicetype is "Arduino" devices[deviceid] = new Arduino(deviceid, devicestatus, socket) else devices[deviceid] = new Device(deviceid, devicestatus, socket) devices[deviceid].emit 'add' clog "Added: #{deviceid}" else if msgobj.devicestatus? then currentdevice.devicestatus = msgobj.devicestatus if msgobj.dimval? then currentdevice.dimval = msgobj.dimval if socket isnt currentdevice.socket then currentdevice.socket = socket currentdevice.emit 'update' clog "Updated: #{msgobj.deviceid}" ############################################################################################ # SOCKET.IO communications # # # # Perfect for telling developers/apps when a device's status has changed. # # Also gives the developer a list of devices when they connect. Good for testing. # # May be implemented in a different way in the future (PubSub?) but this works for now. # # # # Emit function deprecated. Using an emit method in the device instead. # ############################################################################################ # When a socket connects, give it a list of devices by adding them in sequence. io.sockets.on 'connection', (iosocket) -> clog "Got new socket" for deviceid, device of devices clog "Add device #{device.deviceid}" device.emit 'add' iosocket.on 'disconnect', -> clog "Socket disconnected" ########################################## # OTHER JUNK. # ########################################## # Routing for a few redirects app.get '/demo', (req, res) -> res.redirect 'http://www.youtube.com/watch?v=IOncq-OM3_g' app.get '/demo2', (req, res) -> res.redirect 'http://www.youtube.com/watch?v=8hsvGO4FHNo' app.get '/demo3', (req, res) -> res.redirect 'http://www.youtube.com/watch?v=fLkIoJ3BXEw' app.get '/founders', (req, res) -> res.redirect 'http://www.youtube.com/watch?v=71ucyxj1wbk'
[ { "context": "tcher.folderMatchesMinimatchPrefix([ \"\", \"home\", \"commie\" ], set).should.equal(true)\n globwatcher.fol", "end": 1806, "score": 0.7911118268966675, "start": 1802, "tag": "NAME", "value": "comm" }, { "context": "tcher.folderMatchesMinimatchPrefix([ \"\", \"home\", \"robey\" ], set).should.equal(false)\n globwatcher.fold", "end": 1902, "score": 0.6913663744926453, "start": 1897, "tag": "NAME", "value": "robey" }, { "context": "tcher.folderMatchesMinimatchPrefix([ \"\", \"home\", \"commie\", \"rus\" ], set).should.equal(true)\n set = ne", "end": 1996, "score": 0.6840163469314575, "start": 1992, "tag": "NAME", "value": "comm" }, { "context": "tcher.folderMatchesMinimatchPrefix([ \"\", \"home\", \"commie\" ], set).should.equal(true)\n globwatcher.fol", "end": 2264, "score": 0.7225020527839661, "start": 2260, "tag": "NAME", "value": "comm" }, { "context": "tcher.folderMatchesMinimatchPrefix([ \"\", \"home\", \"robey\" ], set).should.equal(false)\n globwatcher.fold", "end": 2360, "score": 0.7316498756408691, "start": 2355, "tag": "NAME", "value": "robey" }, { "context": "tcher.folderMatchesMinimatchPrefix([ \"\", \"home\", \"commie\", \"rus\" ], set).should.equal(false)\n globwat", "end": 2454, "score": 0.7700428366661072, "start": 2450, "tag": "NAME", "value": "comm" }, { "context": "tcher.folderMatchesMinimatchPrefix([ \"\", \"home\", \"commie\", \"lola\" ], set).should.equal(true)\n globwat", "end": 2557, "score": 0.8336388468742371, "start": 2553, "tag": "NAME", "value": "comm" }, { "context": "erMatchesMinimatchPrefix([ \"\", \"home\", \"commie\", \"lola\" ], set).should.equal(true)\n globwatcher.fol", "end": 2565, "score": 0.5967092514038086, "start": 2563, "tag": "NAME", "value": "lo" }, { "context": "tcher.folderMatchesMinimatchPrefix([ \"\", \"home\", \"commie\", \"lola\", \"prissy\" ], set).should.equal(false)\n", "end": 2660, "score": 0.796420693397522, "start": 2656, "tag": "NAME", "value": "comm" }, { "context": "erMatchesMinimatchPrefix([ \"\", \"home\", \"commie\", \"lola\", \"prissy\" ], set).should.equal(false)\n\n it \"a", "end": 2668, "score": 0.6553336381912231, "start": 2666, "tag": "NAME", "value": "lo" }, { "context": "sMinimatchPrefix([ \"\", \"home\", \"commie\", \"lola\", \"prissy\" ], set).should.equal(false)\n\n it \"addWatch\"", "end": 2676, "score": 0.6278849244117737, "start": 2674, "tag": "NAME", "value": "pr" } ]
node_modules/parcelify/node_modules/globwatcher/test/test_globwatcher.coffee
webcoding/promises-book
2,320
fs = require 'fs' minimatch = require 'minimatch' mocha_sprinkles = require 'mocha-sprinkles' path = require 'path' Q = require 'q' shell = require 'shelljs' should = require 'should' touch = require 'touch' util = require 'util' future = mocha_sprinkles.future withTempFolder = mocha_sprinkles.withTempFolder globwatcher = require("../lib/globwatcher/globwatcher") dump = (x) -> util.inspect x, false, null, true makeFixtures = (folder, ts) -> if not ts? then ts = Date.now() - 1000 [ "#{folder}/one.x" "#{folder}/sub/one.x" "#{folder}/sub/two.x" "#{folder}/nested/three.x" "#{folder}/nested/weird.jpg" ].map (file) -> shell.mkdir "-p", path.dirname(file) touch.sync file, mtime: ts fixtures = (f) -> future withTempFolder (folder) -> makeFixtures(folder) f(folder) # create a new globwatch, run a test, and close it withGlobwatcher = (pattern, options, f) -> if not f? f = options options = {} options.persistent = false g = globwatcher.globwatcher(pattern, options) g.ready.fin -> f(g) .fin -> g.close() # capture add/remove/change into an object for later inspection capture = (g) -> summary = {} g.on "added", (filename) -> (summary["added"] or= []).push filename summary["added"].sort() g.on "deleted", (filename) -> (summary["deleted"] or= []).push filename summary["deleted"].sort() g.on "changed", (filename) -> (summary["changed"] or= []).push filename summary["changed"].sort() summary describe "globwatcher", -> it "folderMatchesMinimatchPrefix", -> set = new minimatch.Minimatch("/home/commie/**/*.js", nonegate: true).set[0] globwatcher.folderMatchesMinimatchPrefix([ "", "home" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "commie" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "robey" ], set).should.equal(false) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "commie", "rus" ], set).should.equal(true) set = new minimatch.Minimatch("/home/commie/l*/*.js", nonegate: true).set[0] globwatcher.folderMatchesMinimatchPrefix([ "", "home" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "commie" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "robey" ], set).should.equal(false) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "commie", "rus" ], set).should.equal(false) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "commie", "lola" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "commie", "lola", "prissy" ], set).should.equal(false) it "addWatch", future -> withGlobwatcher "/wut", (g) -> for f in [ "/absolute.txt" "/sub/absolute.txt" "/deeply/nested/file/why/nobody/knows.txt" ] then g.addWatch(f) g.watchMap.getFolders().sort().should.eql [ "/", "/deeply/nested/file/why/nobody/", "/sub/" ] g.watchMap.getFilenames("/").should.eql [ "/absolute.txt" ] g.watchMap.getFilenames("/sub/").should.eql [ "/sub/absolute.txt" ] g.watchMap.getFilenames("/deeply/nested/file/why/nobody/").should.eql [ "/deeply/nested/file/why/nobody/knows.txt" ] it "can parse patterns", fixtures (folder) -> withGlobwatcher "#{folder}/**/*.x", (g) -> g.patterns.should.eql [ "#{folder}/**/*.x" ] Object.keys(g.watchers).sort().should.eql [ "#{folder}/", "#{folder}/nested/", "#{folder}/sub/" ] g.watchMap.getFolders().sort().should.eql [ "#{folder}/", "#{folder}/nested/", "#{folder}/sub/" ] g.watchMap.getFilenames("#{folder}/").should.eql [ "#{folder}/one.x" ] g.watchMap.getFilenames("#{folder}/nested/").should.eql [ "#{folder}/nested/three.x" ] g.watchMap.getFilenames("#{folder}/sub/").should.eql [ "#{folder}/sub/one.x", "#{folder}/sub/two.x" ] it "can parse patterns relative to cwd", fixtures (folder) -> withGlobwatcher "**/*.x", { cwd: "#{folder}/sub" }, (g) -> g.patterns.should.eql [ "#{folder}/sub/**/*.x" ] Object.keys(g.watchers).sort().should.eql [ "#{folder}/sub/" ] g.watchMap.getFolders().sort().should.eql [ "#{folder}/sub/" ] g.watchMap.getFilenames("#{folder}/sub/").should.eql [ "#{folder}/sub/one.x", "#{folder}/sub/two.x" ] it "handles odd relative paths", fixtures (folder) -> withGlobwatcher "../sub/**/*.x", { cwd: "#{folder}/nested" }, (g) -> Object.keys(g.watchers).sort().should.eql [ "#{folder}/sub/" ] g.watchMap.getFolders().sort().should.eql [ "#{folder}/sub/" ] g.watchMap.getFilenames("#{folder}/sub/").should.eql [ "#{folder}/sub/one.x", "#{folder}/sub/two.x" ] it "notices new files", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/**/*.x", (g) -> summary = capture(g) touch.sync "#{folder}/nested/four.x" touch.sync "#{folder}/sub/not-me.txt" g.check().then -> summary.should.eql { added: [ "#{folder}/nested/four.x" ] } it "doesn't emit signals when turned off", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/**/*.x", (g) -> summary = capture(g) g.stopWatches() Q.delay(25).then -> touch.sync "#{folder}/nested/four.x" touch.sync "#{folder}/sub/not-me.txt" g.check() .then -> # just in case, make sure the timer goes off too Q.delay(g.interval * 2) .then -> summary.should.eql { } it "notices new files only in cwd", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}/sub" }, (g) -> summary = capture(g) touch.sync "#{folder}/nested/four.x" touch.sync "#{folder}/sub/not-me.txt" touch.sync "#{folder}/sub/four.x" g.check().then -> summary.should.eql { added: [ "#{folder}/sub/four.x" ] } it "notices new files nested deeply", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/**/*.x", (g) -> summary = capture(g) shell.mkdir "-p", "#{folder}/nested/more/deeply" touch.sync "#{folder}/nested/more/deeply/nine.x" g.check().then -> summary.should.eql { added: [ "#{folder}/nested/more/deeply/nine.x" ] } it "notices deleted files", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.unlinkSync("#{folder}/sub/one.x") g.check().then -> summary.should.eql { deleted: [ "#{folder}/sub/one.x" ] } it "notices a rename as an add + delete", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.renameSync "#{folder}/sub/two.x", "#{folder}/sub/twelve.x" g.check().then -> summary.should.eql { added: [ "#{folder}/sub/twelve.x" ] deleted: [ "#{folder}/sub/two.x" ] } it "handles a nested delete", fixtures (folder) -> shell.mkdir "-p", "#{folder}/nested/more/deeply" touch.sync "#{folder}/nested/more/deeply/here.x" summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) shell.rm "-r", "#{folder}/nested" g.check().then -> summary.should.eql { deleted: [ "#{folder}/nested/more/deeply/here.x", "#{folder}/nested/three.x" ] } it "handles a changed file", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.writeFileSync "#{folder}/sub/one.x", "gahhhhhh" g.check().then -> summary.should.eql { changed: [ "#{folder}/sub/one.x" ] } it "follows a safe-write", fixtures (folder) -> summary = null savee = "#{folder}/one.x" backup = "#{folder}/one.x~" withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.writeFileSync backup, fs.readFileSync(savee) fs.unlinkSync savee fs.renameSync backup, savee g.check().then -> summary.should.eql { changed: [ savee ] } it "only emits once for a changed file", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.writeFileSync "#{folder}/one.x", "whee1" g.check().then -> summary.should.eql { changed: [ "#{folder}/one.x" ] } g.check() .then -> summary.should.eql { changed: [ "#{folder}/one.x" ] } it "emits twice if a file was changed twice", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.writeFileSync "#{folder}/one.x", "whee1" g.check().then -> summary.should.eql { changed: [ "#{folder}/one.x" ] } fs.writeFileSync "#{folder}/one.x", "whee123" g.check() .then -> summary.should.eql { changed: [ "#{folder}/one.x", "#{folder}/one.x" ] } it "doesn't mind watching a nonexistent folder", fixtures (folder) -> withGlobwatcher "#{folder}/not/there/*", (g) -> 3.should.equal(3) it "sees a new matching file even if the whole folder was missing when it started", future withTempFolder (folder) -> summary = null withGlobwatcher "#{folder}/not/there/*", (g) -> summary = capture(g) shell.mkdir "-p", "#{folder}/not/there" fs.writeFileSync "#{folder}/not/there/ten.x", "wheeeeeee" g.check().then -> summary.should.eql { added: [ "#{folder}/not/there/ten.x" ] } it "sees a new matching file even if nested folders were missing when it started", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/sub/deeper/*.x", (g) -> summary = capture(g) shell.mkdir "-p", "#{folder}/sub/deeper" fs.writeFileSync "#{folder}/sub/deeper/ten.x", "wheeeeeee" g.check().then -> summary.should.eql { added: [ "#{folder}/sub/deeper/ten.x" ] } it "sees a new matching file even if the entire tree was erased and re-created", fixtures (folder) -> shell.rm "-rf", "#{folder}/nested" shell.mkdir "-p", "#{folder}/nested/deeper/still" touch.sync "#{folder}/nested/deeper/still/four.x" summary = null withGlobwatcher "#{folder}/**/*", (g) -> summary = capture(g) shell.rm "-r", "#{folder}/nested" g.check().then -> summary.should.eql { deleted: [ "#{folder}/nested/deeper/still/four.x" ] } delete summary.deleted shell.mkdir "-p", "#{folder}/nested/deeper/still" fs.writeFileSync "#{folder}/nested/deeper/still/ten.x", "wheeeeeee" g.check() .then -> summary.should.eql { added: [ "#{folder}/nested/deeper/still/ten.x" ] } it "sees a new matching file even if the folder exists but was empty", fixtures (folder) -> shell.mkdir "-p", "#{folder}/nested/deeper" summary = null withGlobwatcher "#{folder}/nested/deeper/*.x", (g) -> summary = capture(g) fs.writeFileSync "#{folder}/nested/deeper/ten.x", "wheeeeeee" g.check().then -> summary.should.eql { added: [ "#{folder}/nested/deeper/ten.x" ] } it "will watch a single, non-globbed file that doesn't exist", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/nothing.x", (g) -> summary = capture(g) fs.writeFileSync "#{folder}/nothing.x", "hi!" Q.delay(g.interval).then -> summary.should.eql { added: [ "#{folder}/nothing.x" ] } it "returns a currentSet", fixtures (folder) -> withGlobwatcher "#{folder}/**/*.x", (g) -> g.currentSet().sort().should.eql [ "#{folder}/nested/three.x" "#{folder}/one.x" "#{folder}/sub/one.x" "#{folder}/sub/two.x" ] shell.rm "#{folder}/sub/one.x" fs.writeFileSync "#{folder}/whatevs.x" g.check().then -> g.currentSet().sort().should.eql [ "#{folder}/nested/three.x" "#{folder}/one.x" "#{folder}/sub/two.x" "#{folder}/whatevs.x" ] describe "takes a snapshot", -> it "of globs", fixtures (folder) -> withGlobwatcher "#{folder}/**/*.x", { snapshot: {} }, (g) -> ts = fs.statSync("#{folder}/one.x").mtime.getTime() fs.writeFileSync "#{folder}/wut.x", "hello" touch.sync "#{folder}/wut.x", mtime: ts g.check().then -> snapshot = g.snapshot() snapshot["#{folder}/one.x"].should.eql(mtime: ts, size: 0) snapshot["#{folder}/wut.x"].should.eql(mtime: ts, size: 5) snapshot["#{folder}/nested/three.x"].should.eql(mtime: ts, size: 0) snapshot["#{folder}/sub/one.x"].should.eql(mtime: ts, size: 0) snapshot["#{folder}/sub/two.x"].should.eql(mtime: ts, size: 0) it "of normal files", fixtures (folder) -> withGlobwatcher "#{folder}/sub/two.x", { snapshot: {} }, (g) -> ts = fs.statSync("#{folder}/sub/two.x").mtime.getTime() g.check().then -> snapshot = g.snapshot() snapshot["#{folder}/sub/two.x"].should.eql(mtime: ts, size: 0) fs.writeFileSync("#{folder}/sub/two.x", "new!") ts = fs.statSync("#{folder}/sub/two.x").mtime.getTime() withGlobwatcher "#{folder}/sub/two.x", { snapshot }, (g) -> g.check().then -> snapshot = g.snapshot() snapshot["#{folder}/sub/two.x"].should.eql(mtime: ts, size: 4) it "resumes from a snapshot", fixtures (folder) -> withGlobwatcher "#{folder}/**/*.x", (g) -> summary = null snapshot = g.snapshot() g.close() Q.delay(100).then -> fs.writeFileSync "#{folder}/one.x", "hello" shell.rm "#{folder}/sub/two.x" touch.sync "#{folder}/sub/nine.x" g = globwatcher.globwatcher("#{folder}/**/*.x", persistent: false, snapshot: snapshot) summary = capture(g) g.ready .then -> summary.should.eql { added: [ "#{folder}/sub/nine.x" ] changed: [ "#{folder}/one.x" ] deleted: [ "#{folder}/sub/two.x" ] }
49193
fs = require 'fs' minimatch = require 'minimatch' mocha_sprinkles = require 'mocha-sprinkles' path = require 'path' Q = require 'q' shell = require 'shelljs' should = require 'should' touch = require 'touch' util = require 'util' future = mocha_sprinkles.future withTempFolder = mocha_sprinkles.withTempFolder globwatcher = require("../lib/globwatcher/globwatcher") dump = (x) -> util.inspect x, false, null, true makeFixtures = (folder, ts) -> if not ts? then ts = Date.now() - 1000 [ "#{folder}/one.x" "#{folder}/sub/one.x" "#{folder}/sub/two.x" "#{folder}/nested/three.x" "#{folder}/nested/weird.jpg" ].map (file) -> shell.mkdir "-p", path.dirname(file) touch.sync file, mtime: ts fixtures = (f) -> future withTempFolder (folder) -> makeFixtures(folder) f(folder) # create a new globwatch, run a test, and close it withGlobwatcher = (pattern, options, f) -> if not f? f = options options = {} options.persistent = false g = globwatcher.globwatcher(pattern, options) g.ready.fin -> f(g) .fin -> g.close() # capture add/remove/change into an object for later inspection capture = (g) -> summary = {} g.on "added", (filename) -> (summary["added"] or= []).push filename summary["added"].sort() g.on "deleted", (filename) -> (summary["deleted"] or= []).push filename summary["deleted"].sort() g.on "changed", (filename) -> (summary["changed"] or= []).push filename summary["changed"].sort() summary describe "globwatcher", -> it "folderMatchesMinimatchPrefix", -> set = new minimatch.Minimatch("/home/commie/**/*.js", nonegate: true).set[0] globwatcher.folderMatchesMinimatchPrefix([ "", "home" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "<NAME>ie" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "<NAME>" ], set).should.equal(false) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "<NAME>ie", "rus" ], set).should.equal(true) set = new minimatch.Minimatch("/home/commie/l*/*.js", nonegate: true).set[0] globwatcher.folderMatchesMinimatchPrefix([ "", "home" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "<NAME>ie" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "<NAME>" ], set).should.equal(false) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "<NAME>ie", "rus" ], set).should.equal(false) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "<NAME>ie", "<NAME>la" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "<NAME>ie", "<NAME>la", "<NAME>issy" ], set).should.equal(false) it "addWatch", future -> withGlobwatcher "/wut", (g) -> for f in [ "/absolute.txt" "/sub/absolute.txt" "/deeply/nested/file/why/nobody/knows.txt" ] then g.addWatch(f) g.watchMap.getFolders().sort().should.eql [ "/", "/deeply/nested/file/why/nobody/", "/sub/" ] g.watchMap.getFilenames("/").should.eql [ "/absolute.txt" ] g.watchMap.getFilenames("/sub/").should.eql [ "/sub/absolute.txt" ] g.watchMap.getFilenames("/deeply/nested/file/why/nobody/").should.eql [ "/deeply/nested/file/why/nobody/knows.txt" ] it "can parse patterns", fixtures (folder) -> withGlobwatcher "#{folder}/**/*.x", (g) -> g.patterns.should.eql [ "#{folder}/**/*.x" ] Object.keys(g.watchers).sort().should.eql [ "#{folder}/", "#{folder}/nested/", "#{folder}/sub/" ] g.watchMap.getFolders().sort().should.eql [ "#{folder}/", "#{folder}/nested/", "#{folder}/sub/" ] g.watchMap.getFilenames("#{folder}/").should.eql [ "#{folder}/one.x" ] g.watchMap.getFilenames("#{folder}/nested/").should.eql [ "#{folder}/nested/three.x" ] g.watchMap.getFilenames("#{folder}/sub/").should.eql [ "#{folder}/sub/one.x", "#{folder}/sub/two.x" ] it "can parse patterns relative to cwd", fixtures (folder) -> withGlobwatcher "**/*.x", { cwd: "#{folder}/sub" }, (g) -> g.patterns.should.eql [ "#{folder}/sub/**/*.x" ] Object.keys(g.watchers).sort().should.eql [ "#{folder}/sub/" ] g.watchMap.getFolders().sort().should.eql [ "#{folder}/sub/" ] g.watchMap.getFilenames("#{folder}/sub/").should.eql [ "#{folder}/sub/one.x", "#{folder}/sub/two.x" ] it "handles odd relative paths", fixtures (folder) -> withGlobwatcher "../sub/**/*.x", { cwd: "#{folder}/nested" }, (g) -> Object.keys(g.watchers).sort().should.eql [ "#{folder}/sub/" ] g.watchMap.getFolders().sort().should.eql [ "#{folder}/sub/" ] g.watchMap.getFilenames("#{folder}/sub/").should.eql [ "#{folder}/sub/one.x", "#{folder}/sub/two.x" ] it "notices new files", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/**/*.x", (g) -> summary = capture(g) touch.sync "#{folder}/nested/four.x" touch.sync "#{folder}/sub/not-me.txt" g.check().then -> summary.should.eql { added: [ "#{folder}/nested/four.x" ] } it "doesn't emit signals when turned off", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/**/*.x", (g) -> summary = capture(g) g.stopWatches() Q.delay(25).then -> touch.sync "#{folder}/nested/four.x" touch.sync "#{folder}/sub/not-me.txt" g.check() .then -> # just in case, make sure the timer goes off too Q.delay(g.interval * 2) .then -> summary.should.eql { } it "notices new files only in cwd", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}/sub" }, (g) -> summary = capture(g) touch.sync "#{folder}/nested/four.x" touch.sync "#{folder}/sub/not-me.txt" touch.sync "#{folder}/sub/four.x" g.check().then -> summary.should.eql { added: [ "#{folder}/sub/four.x" ] } it "notices new files nested deeply", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/**/*.x", (g) -> summary = capture(g) shell.mkdir "-p", "#{folder}/nested/more/deeply" touch.sync "#{folder}/nested/more/deeply/nine.x" g.check().then -> summary.should.eql { added: [ "#{folder}/nested/more/deeply/nine.x" ] } it "notices deleted files", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.unlinkSync("#{folder}/sub/one.x") g.check().then -> summary.should.eql { deleted: [ "#{folder}/sub/one.x" ] } it "notices a rename as an add + delete", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.renameSync "#{folder}/sub/two.x", "#{folder}/sub/twelve.x" g.check().then -> summary.should.eql { added: [ "#{folder}/sub/twelve.x" ] deleted: [ "#{folder}/sub/two.x" ] } it "handles a nested delete", fixtures (folder) -> shell.mkdir "-p", "#{folder}/nested/more/deeply" touch.sync "#{folder}/nested/more/deeply/here.x" summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) shell.rm "-r", "#{folder}/nested" g.check().then -> summary.should.eql { deleted: [ "#{folder}/nested/more/deeply/here.x", "#{folder}/nested/three.x" ] } it "handles a changed file", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.writeFileSync "#{folder}/sub/one.x", "gahhhhhh" g.check().then -> summary.should.eql { changed: [ "#{folder}/sub/one.x" ] } it "follows a safe-write", fixtures (folder) -> summary = null savee = "#{folder}/one.x" backup = "#{folder}/one.x~" withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.writeFileSync backup, fs.readFileSync(savee) fs.unlinkSync savee fs.renameSync backup, savee g.check().then -> summary.should.eql { changed: [ savee ] } it "only emits once for a changed file", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.writeFileSync "#{folder}/one.x", "whee1" g.check().then -> summary.should.eql { changed: [ "#{folder}/one.x" ] } g.check() .then -> summary.should.eql { changed: [ "#{folder}/one.x" ] } it "emits twice if a file was changed twice", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.writeFileSync "#{folder}/one.x", "whee1" g.check().then -> summary.should.eql { changed: [ "#{folder}/one.x" ] } fs.writeFileSync "#{folder}/one.x", "whee123" g.check() .then -> summary.should.eql { changed: [ "#{folder}/one.x", "#{folder}/one.x" ] } it "doesn't mind watching a nonexistent folder", fixtures (folder) -> withGlobwatcher "#{folder}/not/there/*", (g) -> 3.should.equal(3) it "sees a new matching file even if the whole folder was missing when it started", future withTempFolder (folder) -> summary = null withGlobwatcher "#{folder}/not/there/*", (g) -> summary = capture(g) shell.mkdir "-p", "#{folder}/not/there" fs.writeFileSync "#{folder}/not/there/ten.x", "wheeeeeee" g.check().then -> summary.should.eql { added: [ "#{folder}/not/there/ten.x" ] } it "sees a new matching file even if nested folders were missing when it started", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/sub/deeper/*.x", (g) -> summary = capture(g) shell.mkdir "-p", "#{folder}/sub/deeper" fs.writeFileSync "#{folder}/sub/deeper/ten.x", "wheeeeeee" g.check().then -> summary.should.eql { added: [ "#{folder}/sub/deeper/ten.x" ] } it "sees a new matching file even if the entire tree was erased and re-created", fixtures (folder) -> shell.rm "-rf", "#{folder}/nested" shell.mkdir "-p", "#{folder}/nested/deeper/still" touch.sync "#{folder}/nested/deeper/still/four.x" summary = null withGlobwatcher "#{folder}/**/*", (g) -> summary = capture(g) shell.rm "-r", "#{folder}/nested" g.check().then -> summary.should.eql { deleted: [ "#{folder}/nested/deeper/still/four.x" ] } delete summary.deleted shell.mkdir "-p", "#{folder}/nested/deeper/still" fs.writeFileSync "#{folder}/nested/deeper/still/ten.x", "wheeeeeee" g.check() .then -> summary.should.eql { added: [ "#{folder}/nested/deeper/still/ten.x" ] } it "sees a new matching file even if the folder exists but was empty", fixtures (folder) -> shell.mkdir "-p", "#{folder}/nested/deeper" summary = null withGlobwatcher "#{folder}/nested/deeper/*.x", (g) -> summary = capture(g) fs.writeFileSync "#{folder}/nested/deeper/ten.x", "wheeeeeee" g.check().then -> summary.should.eql { added: [ "#{folder}/nested/deeper/ten.x" ] } it "will watch a single, non-globbed file that doesn't exist", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/nothing.x", (g) -> summary = capture(g) fs.writeFileSync "#{folder}/nothing.x", "hi!" Q.delay(g.interval).then -> summary.should.eql { added: [ "#{folder}/nothing.x" ] } it "returns a currentSet", fixtures (folder) -> withGlobwatcher "#{folder}/**/*.x", (g) -> g.currentSet().sort().should.eql [ "#{folder}/nested/three.x" "#{folder}/one.x" "#{folder}/sub/one.x" "#{folder}/sub/two.x" ] shell.rm "#{folder}/sub/one.x" fs.writeFileSync "#{folder}/whatevs.x" g.check().then -> g.currentSet().sort().should.eql [ "#{folder}/nested/three.x" "#{folder}/one.x" "#{folder}/sub/two.x" "#{folder}/whatevs.x" ] describe "takes a snapshot", -> it "of globs", fixtures (folder) -> withGlobwatcher "#{folder}/**/*.x", { snapshot: {} }, (g) -> ts = fs.statSync("#{folder}/one.x").mtime.getTime() fs.writeFileSync "#{folder}/wut.x", "hello" touch.sync "#{folder}/wut.x", mtime: ts g.check().then -> snapshot = g.snapshot() snapshot["#{folder}/one.x"].should.eql(mtime: ts, size: 0) snapshot["#{folder}/wut.x"].should.eql(mtime: ts, size: 5) snapshot["#{folder}/nested/three.x"].should.eql(mtime: ts, size: 0) snapshot["#{folder}/sub/one.x"].should.eql(mtime: ts, size: 0) snapshot["#{folder}/sub/two.x"].should.eql(mtime: ts, size: 0) it "of normal files", fixtures (folder) -> withGlobwatcher "#{folder}/sub/two.x", { snapshot: {} }, (g) -> ts = fs.statSync("#{folder}/sub/two.x").mtime.getTime() g.check().then -> snapshot = g.snapshot() snapshot["#{folder}/sub/two.x"].should.eql(mtime: ts, size: 0) fs.writeFileSync("#{folder}/sub/two.x", "new!") ts = fs.statSync("#{folder}/sub/two.x").mtime.getTime() withGlobwatcher "#{folder}/sub/two.x", { snapshot }, (g) -> g.check().then -> snapshot = g.snapshot() snapshot["#{folder}/sub/two.x"].should.eql(mtime: ts, size: 4) it "resumes from a snapshot", fixtures (folder) -> withGlobwatcher "#{folder}/**/*.x", (g) -> summary = null snapshot = g.snapshot() g.close() Q.delay(100).then -> fs.writeFileSync "#{folder}/one.x", "hello" shell.rm "#{folder}/sub/two.x" touch.sync "#{folder}/sub/nine.x" g = globwatcher.globwatcher("#{folder}/**/*.x", persistent: false, snapshot: snapshot) summary = capture(g) g.ready .then -> summary.should.eql { added: [ "#{folder}/sub/nine.x" ] changed: [ "#{folder}/one.x" ] deleted: [ "#{folder}/sub/two.x" ] }
true
fs = require 'fs' minimatch = require 'minimatch' mocha_sprinkles = require 'mocha-sprinkles' path = require 'path' Q = require 'q' shell = require 'shelljs' should = require 'should' touch = require 'touch' util = require 'util' future = mocha_sprinkles.future withTempFolder = mocha_sprinkles.withTempFolder globwatcher = require("../lib/globwatcher/globwatcher") dump = (x) -> util.inspect x, false, null, true makeFixtures = (folder, ts) -> if not ts? then ts = Date.now() - 1000 [ "#{folder}/one.x" "#{folder}/sub/one.x" "#{folder}/sub/two.x" "#{folder}/nested/three.x" "#{folder}/nested/weird.jpg" ].map (file) -> shell.mkdir "-p", path.dirname(file) touch.sync file, mtime: ts fixtures = (f) -> future withTempFolder (folder) -> makeFixtures(folder) f(folder) # create a new globwatch, run a test, and close it withGlobwatcher = (pattern, options, f) -> if not f? f = options options = {} options.persistent = false g = globwatcher.globwatcher(pattern, options) g.ready.fin -> f(g) .fin -> g.close() # capture add/remove/change into an object for later inspection capture = (g) -> summary = {} g.on "added", (filename) -> (summary["added"] or= []).push filename summary["added"].sort() g.on "deleted", (filename) -> (summary["deleted"] or= []).push filename summary["deleted"].sort() g.on "changed", (filename) -> (summary["changed"] or= []).push filename summary["changed"].sort() summary describe "globwatcher", -> it "folderMatchesMinimatchPrefix", -> set = new minimatch.Minimatch("/home/commie/**/*.js", nonegate: true).set[0] globwatcher.folderMatchesMinimatchPrefix([ "", "home" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "PI:NAME:<NAME>END_PIie" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "PI:NAME:<NAME>END_PI" ], set).should.equal(false) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "PI:NAME:<NAME>END_PIie", "rus" ], set).should.equal(true) set = new minimatch.Minimatch("/home/commie/l*/*.js", nonegate: true).set[0] globwatcher.folderMatchesMinimatchPrefix([ "", "home" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "PI:NAME:<NAME>END_PIie" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "PI:NAME:<NAME>END_PI" ], set).should.equal(false) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "PI:NAME:<NAME>END_PIie", "rus" ], set).should.equal(false) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "PI:NAME:<NAME>END_PIie", "PI:NAME:<NAME>END_PIla" ], set).should.equal(true) globwatcher.folderMatchesMinimatchPrefix([ "", "home", "PI:NAME:<NAME>END_PIie", "PI:NAME:<NAME>END_PIla", "PI:NAME:<NAME>END_PIissy" ], set).should.equal(false) it "addWatch", future -> withGlobwatcher "/wut", (g) -> for f in [ "/absolute.txt" "/sub/absolute.txt" "/deeply/nested/file/why/nobody/knows.txt" ] then g.addWatch(f) g.watchMap.getFolders().sort().should.eql [ "/", "/deeply/nested/file/why/nobody/", "/sub/" ] g.watchMap.getFilenames("/").should.eql [ "/absolute.txt" ] g.watchMap.getFilenames("/sub/").should.eql [ "/sub/absolute.txt" ] g.watchMap.getFilenames("/deeply/nested/file/why/nobody/").should.eql [ "/deeply/nested/file/why/nobody/knows.txt" ] it "can parse patterns", fixtures (folder) -> withGlobwatcher "#{folder}/**/*.x", (g) -> g.patterns.should.eql [ "#{folder}/**/*.x" ] Object.keys(g.watchers).sort().should.eql [ "#{folder}/", "#{folder}/nested/", "#{folder}/sub/" ] g.watchMap.getFolders().sort().should.eql [ "#{folder}/", "#{folder}/nested/", "#{folder}/sub/" ] g.watchMap.getFilenames("#{folder}/").should.eql [ "#{folder}/one.x" ] g.watchMap.getFilenames("#{folder}/nested/").should.eql [ "#{folder}/nested/three.x" ] g.watchMap.getFilenames("#{folder}/sub/").should.eql [ "#{folder}/sub/one.x", "#{folder}/sub/two.x" ] it "can parse patterns relative to cwd", fixtures (folder) -> withGlobwatcher "**/*.x", { cwd: "#{folder}/sub" }, (g) -> g.patterns.should.eql [ "#{folder}/sub/**/*.x" ] Object.keys(g.watchers).sort().should.eql [ "#{folder}/sub/" ] g.watchMap.getFolders().sort().should.eql [ "#{folder}/sub/" ] g.watchMap.getFilenames("#{folder}/sub/").should.eql [ "#{folder}/sub/one.x", "#{folder}/sub/two.x" ] it "handles odd relative paths", fixtures (folder) -> withGlobwatcher "../sub/**/*.x", { cwd: "#{folder}/nested" }, (g) -> Object.keys(g.watchers).sort().should.eql [ "#{folder}/sub/" ] g.watchMap.getFolders().sort().should.eql [ "#{folder}/sub/" ] g.watchMap.getFilenames("#{folder}/sub/").should.eql [ "#{folder}/sub/one.x", "#{folder}/sub/two.x" ] it "notices new files", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/**/*.x", (g) -> summary = capture(g) touch.sync "#{folder}/nested/four.x" touch.sync "#{folder}/sub/not-me.txt" g.check().then -> summary.should.eql { added: [ "#{folder}/nested/four.x" ] } it "doesn't emit signals when turned off", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/**/*.x", (g) -> summary = capture(g) g.stopWatches() Q.delay(25).then -> touch.sync "#{folder}/nested/four.x" touch.sync "#{folder}/sub/not-me.txt" g.check() .then -> # just in case, make sure the timer goes off too Q.delay(g.interval * 2) .then -> summary.should.eql { } it "notices new files only in cwd", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}/sub" }, (g) -> summary = capture(g) touch.sync "#{folder}/nested/four.x" touch.sync "#{folder}/sub/not-me.txt" touch.sync "#{folder}/sub/four.x" g.check().then -> summary.should.eql { added: [ "#{folder}/sub/four.x" ] } it "notices new files nested deeply", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/**/*.x", (g) -> summary = capture(g) shell.mkdir "-p", "#{folder}/nested/more/deeply" touch.sync "#{folder}/nested/more/deeply/nine.x" g.check().then -> summary.should.eql { added: [ "#{folder}/nested/more/deeply/nine.x" ] } it "notices deleted files", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.unlinkSync("#{folder}/sub/one.x") g.check().then -> summary.should.eql { deleted: [ "#{folder}/sub/one.x" ] } it "notices a rename as an add + delete", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.renameSync "#{folder}/sub/two.x", "#{folder}/sub/twelve.x" g.check().then -> summary.should.eql { added: [ "#{folder}/sub/twelve.x" ] deleted: [ "#{folder}/sub/two.x" ] } it "handles a nested delete", fixtures (folder) -> shell.mkdir "-p", "#{folder}/nested/more/deeply" touch.sync "#{folder}/nested/more/deeply/here.x" summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) shell.rm "-r", "#{folder}/nested" g.check().then -> summary.should.eql { deleted: [ "#{folder}/nested/more/deeply/here.x", "#{folder}/nested/three.x" ] } it "handles a changed file", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.writeFileSync "#{folder}/sub/one.x", "gahhhhhh" g.check().then -> summary.should.eql { changed: [ "#{folder}/sub/one.x" ] } it "follows a safe-write", fixtures (folder) -> summary = null savee = "#{folder}/one.x" backup = "#{folder}/one.x~" withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.writeFileSync backup, fs.readFileSync(savee) fs.unlinkSync savee fs.renameSync backup, savee g.check().then -> summary.should.eql { changed: [ savee ] } it "only emits once for a changed file", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.writeFileSync "#{folder}/one.x", "whee1" g.check().then -> summary.should.eql { changed: [ "#{folder}/one.x" ] } g.check() .then -> summary.should.eql { changed: [ "#{folder}/one.x" ] } it "emits twice if a file was changed twice", fixtures (folder) -> summary = null withGlobwatcher "**/*.x", { cwd: "#{folder}" }, (g) -> summary = capture(g) fs.writeFileSync "#{folder}/one.x", "whee1" g.check().then -> summary.should.eql { changed: [ "#{folder}/one.x" ] } fs.writeFileSync "#{folder}/one.x", "whee123" g.check() .then -> summary.should.eql { changed: [ "#{folder}/one.x", "#{folder}/one.x" ] } it "doesn't mind watching a nonexistent folder", fixtures (folder) -> withGlobwatcher "#{folder}/not/there/*", (g) -> 3.should.equal(3) it "sees a new matching file even if the whole folder was missing when it started", future withTempFolder (folder) -> summary = null withGlobwatcher "#{folder}/not/there/*", (g) -> summary = capture(g) shell.mkdir "-p", "#{folder}/not/there" fs.writeFileSync "#{folder}/not/there/ten.x", "wheeeeeee" g.check().then -> summary.should.eql { added: [ "#{folder}/not/there/ten.x" ] } it "sees a new matching file even if nested folders were missing when it started", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/sub/deeper/*.x", (g) -> summary = capture(g) shell.mkdir "-p", "#{folder}/sub/deeper" fs.writeFileSync "#{folder}/sub/deeper/ten.x", "wheeeeeee" g.check().then -> summary.should.eql { added: [ "#{folder}/sub/deeper/ten.x" ] } it "sees a new matching file even if the entire tree was erased and re-created", fixtures (folder) -> shell.rm "-rf", "#{folder}/nested" shell.mkdir "-p", "#{folder}/nested/deeper/still" touch.sync "#{folder}/nested/deeper/still/four.x" summary = null withGlobwatcher "#{folder}/**/*", (g) -> summary = capture(g) shell.rm "-r", "#{folder}/nested" g.check().then -> summary.should.eql { deleted: [ "#{folder}/nested/deeper/still/four.x" ] } delete summary.deleted shell.mkdir "-p", "#{folder}/nested/deeper/still" fs.writeFileSync "#{folder}/nested/deeper/still/ten.x", "wheeeeeee" g.check() .then -> summary.should.eql { added: [ "#{folder}/nested/deeper/still/ten.x" ] } it "sees a new matching file even if the folder exists but was empty", fixtures (folder) -> shell.mkdir "-p", "#{folder}/nested/deeper" summary = null withGlobwatcher "#{folder}/nested/deeper/*.x", (g) -> summary = capture(g) fs.writeFileSync "#{folder}/nested/deeper/ten.x", "wheeeeeee" g.check().then -> summary.should.eql { added: [ "#{folder}/nested/deeper/ten.x" ] } it "will watch a single, non-globbed file that doesn't exist", fixtures (folder) -> summary = null withGlobwatcher "#{folder}/nothing.x", (g) -> summary = capture(g) fs.writeFileSync "#{folder}/nothing.x", "hi!" Q.delay(g.interval).then -> summary.should.eql { added: [ "#{folder}/nothing.x" ] } it "returns a currentSet", fixtures (folder) -> withGlobwatcher "#{folder}/**/*.x", (g) -> g.currentSet().sort().should.eql [ "#{folder}/nested/three.x" "#{folder}/one.x" "#{folder}/sub/one.x" "#{folder}/sub/two.x" ] shell.rm "#{folder}/sub/one.x" fs.writeFileSync "#{folder}/whatevs.x" g.check().then -> g.currentSet().sort().should.eql [ "#{folder}/nested/three.x" "#{folder}/one.x" "#{folder}/sub/two.x" "#{folder}/whatevs.x" ] describe "takes a snapshot", -> it "of globs", fixtures (folder) -> withGlobwatcher "#{folder}/**/*.x", { snapshot: {} }, (g) -> ts = fs.statSync("#{folder}/one.x").mtime.getTime() fs.writeFileSync "#{folder}/wut.x", "hello" touch.sync "#{folder}/wut.x", mtime: ts g.check().then -> snapshot = g.snapshot() snapshot["#{folder}/one.x"].should.eql(mtime: ts, size: 0) snapshot["#{folder}/wut.x"].should.eql(mtime: ts, size: 5) snapshot["#{folder}/nested/three.x"].should.eql(mtime: ts, size: 0) snapshot["#{folder}/sub/one.x"].should.eql(mtime: ts, size: 0) snapshot["#{folder}/sub/two.x"].should.eql(mtime: ts, size: 0) it "of normal files", fixtures (folder) -> withGlobwatcher "#{folder}/sub/two.x", { snapshot: {} }, (g) -> ts = fs.statSync("#{folder}/sub/two.x").mtime.getTime() g.check().then -> snapshot = g.snapshot() snapshot["#{folder}/sub/two.x"].should.eql(mtime: ts, size: 0) fs.writeFileSync("#{folder}/sub/two.x", "new!") ts = fs.statSync("#{folder}/sub/two.x").mtime.getTime() withGlobwatcher "#{folder}/sub/two.x", { snapshot }, (g) -> g.check().then -> snapshot = g.snapshot() snapshot["#{folder}/sub/two.x"].should.eql(mtime: ts, size: 4) it "resumes from a snapshot", fixtures (folder) -> withGlobwatcher "#{folder}/**/*.x", (g) -> summary = null snapshot = g.snapshot() g.close() Q.delay(100).then -> fs.writeFileSync "#{folder}/one.x", "hello" shell.rm "#{folder}/sub/two.x" touch.sync "#{folder}/sub/nine.x" g = globwatcher.globwatcher("#{folder}/**/*.x", persistent: false, snapshot: snapshot) summary = capture(g) g.ready .then -> summary.should.eql { added: [ "#{folder}/sub/nine.x" ] changed: [ "#{folder}/one.x" ] deleted: [ "#{folder}/sub/two.x" ] }
[ { "context": "ext\", (test) ->\n doTestCase test,\n text: \"Hello\"\n caretIsBefore: /^/\n bold: \"**bold tex", "end": 7173, "score": 0.9542251825332642, "start": 7168, "tag": "NAME", "value": "Hello" }, { "context": "ext\", (test) ->\n doTestCase test,\n text: \"Hello\"\n caretIsBefore: /$/\n bold: \"Hello**bol", "end": 7361, "score": 0.9581199288368225, "start": 7356, "tag": "NAME", "value": "Hello" }, { "context": "ext\", (test) ->\n doTestCase test,\n text: \"Hello\"\n caretIsBefore: \"lo\"\n bold: \"Hel**bold", "end": 7552, "score": 0.9514905214309692, "start": 7547, "tag": "NAME", "value": "Hello" } ]
test/bold-italic.coffee
evan-dickinson/md4mefi
1
(() -> injectUtils = window.md4mefiInjectUtils QUnit.module("Bold/Italic") testDomElements = $('#test-dom-elements') boldItalic = $('<div>').addClass('bold-italic') mdComment = $('<textarea>').addClass('md-comment') boldItalic.append(mdComment) testDomElements.append(boldItalic) boldToItalic = (text) -> text.replace(/\*\*/g, "*").replace(/bold/g, "italic") doTest = (test, boldOrItalic, text, selectedText, range, expectedResult, expectedSelected) -> mdComment.val(text) mdComment.selection 'setPos', range test.strictEqual(mdComment.selection('get'), selectedText) injectUtils.doBoldOrItalic(boldOrItalic, mdComment) actualResult = mdComment.val() test.strictEqual(actualResult, expectedResult) test.strictEqual(mdComment.selection('get'), expectedSelected) doTestCase = (test, options) -> options.text ?= throw new Error("Argument error: text not specified") options.bold ?= throw new Error options.italic ?= boldToItalic(options.bold) if options.caretIsBefore? if options.selectionPos? # Can't specify both throw new Error # If match succeeds, get the index. Else, throw error options.selectionPos = options.text.match(options.caretIsBefore)?.index ? throw new Error if options.selectedText? && options.selectionPos? # Can't specify both selectedText and selectionPos throw new Error if !options.selectedText? && !options.selectionPos? # Neither specified, so select the entire text options.selectedText = options.text if options.selectedText? && !options.selectionPos? start = options.text.indexOf(options.selectedText) range = start: start end: start + options.selectedText.length # Default the bold/italic selected text to the # text that's selected options.boldSelected ?= options.selectedText options.italicSelected ?= boldToItalic(options.boldSelected) if !options.selectedText? && options.selectionPos? range = start: options.selectionPos end: options.selectionPos # Default the bold/italic selected text to the filler copy that's # used with a zero-length selection options.boldSelected ?= "bold text" options.italicSelected ?= "italic text" options.selectedText = "" test.expect 2 * 3 doTest test, 'bold', options.text, options.selectedText, range, options.bold, options.boldSelected doTest test, 'italic', options.text, options.selectedText, range, options.italic, options.italicSelected QUnit.test 'simple bolding', (test) -> doTestCase test, text: "One" bold: "**One**" QUnit.test 'trailing newline', (test) -> doTestCase test, text: "One\n" bold: "**One**\n" boldSelected: "One" QUnit.test 'two trailing newlines', (test) -> doTestCase test, text: "One\n\n" bold: "**One**\n\n" boldSelected: "One" QUnit.test 'three trailing newlines', (test) -> doTestCase test, text: "One\n\n\n" bold: "**One**\n\n\n" boldSelected: "One" QUnit.test 'leading newline', (test) -> doTestCase test, text: "\nOne" bold: "\n**One**" boldSelected: "One" QUnit.test 'two leading newlines', (test) -> doTestCase test, text: "\n\nOne" bold: "\n\n**One**" boldSelected: "One" QUnit.test 'three leading newlines', (test) -> doTestCase test, text: "\n\n\nOne" bold: "\n\n\n**One**" boldSelected: "One" QUnit.test 'two consecutive lines', (test) -> doTestCase test, text: "One\nTwo" bold: "**One**\n**Two**" boldSelected: "One**\n**Two" QUnit.test 'three consecutive lines', (test) -> doTestCase test, text: "One\nTwo\nThree" bold: "**One**\n**Two**\n**Three**" boldSelected: "One**\n**Two**\n**Three" QUnit.test 'two consecutive lines with double newlines', (test) -> doTestCase test, text: "One\n\nTwo" bold: "**One**\n\n**Two**" boldSelected: "One**\n\n**Two" QUnit.test 'three consecutive lines with double newlines', (test) -> doTestCase test, text: """ One Two Three """ bold: """ **One** **Two** **Three** """ boldSelected: """ One** **Two** **Three """ QUnit.test 'empty string', (test) -> doTestCase test, text: "" bold: "**bold text**" boldSelected: "bold text" QUnit.test 'only newlines - one', (test) -> doTestCase test, text: "\n" bold: "\n**bold text**" boldSelected: "bold text" # Leave the entire text selected QUnit.test 'only newlines - two', (test) -> doTestCase test, text: "\n\n" bold: "\n\n**bold text**" boldSelected: "bold text" # Leave the entire text selected QUnit.test "slected text at start of string, before newline", (test) -> doTestCase test, text: """ One Two """ selectedText: "One" bold: """ **One** Two """ QUnit.test "slected text at start of string, includes newline", (test) -> doTestCase test, text: """ One Two """ selectedText: "One\n" bold: """ **One** Two """ boldSelected: "One" # After bold, selection won't include newline QUnit.test "selected text preceded by newlines", (test) -> doTestCase test, text: """ One Two """ selectedText: "One" bold: """ **One** Two """ QUnit.test "selected text includes preceding newlines", (test) -> doTestCase test, text: """ One Two """ selectedText: "\n\nOne" bold: """ **One** Two """ boldSelected: "One" # After trim, won't include newlines QUnit.test "multi-line selection - two paragraphs", (test) -> doTestCase test, text: """ one two three four five six seven eight nine """ selectedText: """ one two three four five six """ bold: """ **one two three** **four five six** seven eight nine """ boldSelected: """ one two three** **four five six """ QUnit.test "multi-line selection - three paragraphs", (test) -> doTestCase test, text: """ one two three four five six seven eight nine ten eleven twelve """ selectedText: """ one two three four five six seven eight nine """ bold: """ **one two three** **four five six** **seven eight nine** ten eleven twelve """ boldSelected: """ one two three** **four five six** **seven eight nine """ QUnit.test "no selection - empty string", (test) -> doTestCase test, text: "" caretIsBefore: /^/ bold: "**bold text**" italic: "*italic text*" QUnit.test "no selection - start of text", (test) -> doTestCase test, text: "Hello" caretIsBefore: /^/ bold: "**bold text**Hello" italic: "*italic text*Hello" QUnit.test "no selection - end of text", (test) -> doTestCase test, text: "Hello" caretIsBefore: /$/ bold: "Hello**bold text**" italic: "Hello*italic text*" QUnit.test "no selection - middle of text", (test) -> doTestCase test, text: "Hello" caretIsBefore: "lo" bold: "Hel**bold text**lo" italic: "Hel*italic text*lo" QUnit.test "no selection - between lines", (test) -> doTestCase test, text: """ One two three Four five six """ caretIsBefore: "Four" bold: """ One two three **bold text**Four five six """, italic: """ One two three *italic text*Four five six """ QUnit.test "no selection - between paragraphs", (test) -> doTestCase test, text: """ One two three Four five six """ caretIsBefore: "\nFour" bold: """ One two three **bold text** Four five six """, italic: """ One two three *italic text* Four five six """ )()
13412
(() -> injectUtils = window.md4mefiInjectUtils QUnit.module("Bold/Italic") testDomElements = $('#test-dom-elements') boldItalic = $('<div>').addClass('bold-italic') mdComment = $('<textarea>').addClass('md-comment') boldItalic.append(mdComment) testDomElements.append(boldItalic) boldToItalic = (text) -> text.replace(/\*\*/g, "*").replace(/bold/g, "italic") doTest = (test, boldOrItalic, text, selectedText, range, expectedResult, expectedSelected) -> mdComment.val(text) mdComment.selection 'setPos', range test.strictEqual(mdComment.selection('get'), selectedText) injectUtils.doBoldOrItalic(boldOrItalic, mdComment) actualResult = mdComment.val() test.strictEqual(actualResult, expectedResult) test.strictEqual(mdComment.selection('get'), expectedSelected) doTestCase = (test, options) -> options.text ?= throw new Error("Argument error: text not specified") options.bold ?= throw new Error options.italic ?= boldToItalic(options.bold) if options.caretIsBefore? if options.selectionPos? # Can't specify both throw new Error # If match succeeds, get the index. Else, throw error options.selectionPos = options.text.match(options.caretIsBefore)?.index ? throw new Error if options.selectedText? && options.selectionPos? # Can't specify both selectedText and selectionPos throw new Error if !options.selectedText? && !options.selectionPos? # Neither specified, so select the entire text options.selectedText = options.text if options.selectedText? && !options.selectionPos? start = options.text.indexOf(options.selectedText) range = start: start end: start + options.selectedText.length # Default the bold/italic selected text to the # text that's selected options.boldSelected ?= options.selectedText options.italicSelected ?= boldToItalic(options.boldSelected) if !options.selectedText? && options.selectionPos? range = start: options.selectionPos end: options.selectionPos # Default the bold/italic selected text to the filler copy that's # used with a zero-length selection options.boldSelected ?= "bold text" options.italicSelected ?= "italic text" options.selectedText = "" test.expect 2 * 3 doTest test, 'bold', options.text, options.selectedText, range, options.bold, options.boldSelected doTest test, 'italic', options.text, options.selectedText, range, options.italic, options.italicSelected QUnit.test 'simple bolding', (test) -> doTestCase test, text: "One" bold: "**One**" QUnit.test 'trailing newline', (test) -> doTestCase test, text: "One\n" bold: "**One**\n" boldSelected: "One" QUnit.test 'two trailing newlines', (test) -> doTestCase test, text: "One\n\n" bold: "**One**\n\n" boldSelected: "One" QUnit.test 'three trailing newlines', (test) -> doTestCase test, text: "One\n\n\n" bold: "**One**\n\n\n" boldSelected: "One" QUnit.test 'leading newline', (test) -> doTestCase test, text: "\nOne" bold: "\n**One**" boldSelected: "One" QUnit.test 'two leading newlines', (test) -> doTestCase test, text: "\n\nOne" bold: "\n\n**One**" boldSelected: "One" QUnit.test 'three leading newlines', (test) -> doTestCase test, text: "\n\n\nOne" bold: "\n\n\n**One**" boldSelected: "One" QUnit.test 'two consecutive lines', (test) -> doTestCase test, text: "One\nTwo" bold: "**One**\n**Two**" boldSelected: "One**\n**Two" QUnit.test 'three consecutive lines', (test) -> doTestCase test, text: "One\nTwo\nThree" bold: "**One**\n**Two**\n**Three**" boldSelected: "One**\n**Two**\n**Three" QUnit.test 'two consecutive lines with double newlines', (test) -> doTestCase test, text: "One\n\nTwo" bold: "**One**\n\n**Two**" boldSelected: "One**\n\n**Two" QUnit.test 'three consecutive lines with double newlines', (test) -> doTestCase test, text: """ One Two Three """ bold: """ **One** **Two** **Three** """ boldSelected: """ One** **Two** **Three """ QUnit.test 'empty string', (test) -> doTestCase test, text: "" bold: "**bold text**" boldSelected: "bold text" QUnit.test 'only newlines - one', (test) -> doTestCase test, text: "\n" bold: "\n**bold text**" boldSelected: "bold text" # Leave the entire text selected QUnit.test 'only newlines - two', (test) -> doTestCase test, text: "\n\n" bold: "\n\n**bold text**" boldSelected: "bold text" # Leave the entire text selected QUnit.test "slected text at start of string, before newline", (test) -> doTestCase test, text: """ One Two """ selectedText: "One" bold: """ **One** Two """ QUnit.test "slected text at start of string, includes newline", (test) -> doTestCase test, text: """ One Two """ selectedText: "One\n" bold: """ **One** Two """ boldSelected: "One" # After bold, selection won't include newline QUnit.test "selected text preceded by newlines", (test) -> doTestCase test, text: """ One Two """ selectedText: "One" bold: """ **One** Two """ QUnit.test "selected text includes preceding newlines", (test) -> doTestCase test, text: """ One Two """ selectedText: "\n\nOne" bold: """ **One** Two """ boldSelected: "One" # After trim, won't include newlines QUnit.test "multi-line selection - two paragraphs", (test) -> doTestCase test, text: """ one two three four five six seven eight nine """ selectedText: """ one two three four five six """ bold: """ **one two three** **four five six** seven eight nine """ boldSelected: """ one two three** **four five six """ QUnit.test "multi-line selection - three paragraphs", (test) -> doTestCase test, text: """ one two three four five six seven eight nine ten eleven twelve """ selectedText: """ one two three four five six seven eight nine """ bold: """ **one two three** **four five six** **seven eight nine** ten eleven twelve """ boldSelected: """ one two three** **four five six** **seven eight nine """ QUnit.test "no selection - empty string", (test) -> doTestCase test, text: "" caretIsBefore: /^/ bold: "**bold text**" italic: "*italic text*" QUnit.test "no selection - start of text", (test) -> doTestCase test, text: "<NAME>" caretIsBefore: /^/ bold: "**bold text**Hello" italic: "*italic text*Hello" QUnit.test "no selection - end of text", (test) -> doTestCase test, text: "<NAME>" caretIsBefore: /$/ bold: "Hello**bold text**" italic: "Hello*italic text*" QUnit.test "no selection - middle of text", (test) -> doTestCase test, text: "<NAME>" caretIsBefore: "lo" bold: "Hel**bold text**lo" italic: "Hel*italic text*lo" QUnit.test "no selection - between lines", (test) -> doTestCase test, text: """ One two three Four five six """ caretIsBefore: "Four" bold: """ One two three **bold text**Four five six """, italic: """ One two three *italic text*Four five six """ QUnit.test "no selection - between paragraphs", (test) -> doTestCase test, text: """ One two three Four five six """ caretIsBefore: "\nFour" bold: """ One two three **bold text** Four five six """, italic: """ One two three *italic text* Four five six """ )()
true
(() -> injectUtils = window.md4mefiInjectUtils QUnit.module("Bold/Italic") testDomElements = $('#test-dom-elements') boldItalic = $('<div>').addClass('bold-italic') mdComment = $('<textarea>').addClass('md-comment') boldItalic.append(mdComment) testDomElements.append(boldItalic) boldToItalic = (text) -> text.replace(/\*\*/g, "*").replace(/bold/g, "italic") doTest = (test, boldOrItalic, text, selectedText, range, expectedResult, expectedSelected) -> mdComment.val(text) mdComment.selection 'setPos', range test.strictEqual(mdComment.selection('get'), selectedText) injectUtils.doBoldOrItalic(boldOrItalic, mdComment) actualResult = mdComment.val() test.strictEqual(actualResult, expectedResult) test.strictEqual(mdComment.selection('get'), expectedSelected) doTestCase = (test, options) -> options.text ?= throw new Error("Argument error: text not specified") options.bold ?= throw new Error options.italic ?= boldToItalic(options.bold) if options.caretIsBefore? if options.selectionPos? # Can't specify both throw new Error # If match succeeds, get the index. Else, throw error options.selectionPos = options.text.match(options.caretIsBefore)?.index ? throw new Error if options.selectedText? && options.selectionPos? # Can't specify both selectedText and selectionPos throw new Error if !options.selectedText? && !options.selectionPos? # Neither specified, so select the entire text options.selectedText = options.text if options.selectedText? && !options.selectionPos? start = options.text.indexOf(options.selectedText) range = start: start end: start + options.selectedText.length # Default the bold/italic selected text to the # text that's selected options.boldSelected ?= options.selectedText options.italicSelected ?= boldToItalic(options.boldSelected) if !options.selectedText? && options.selectionPos? range = start: options.selectionPos end: options.selectionPos # Default the bold/italic selected text to the filler copy that's # used with a zero-length selection options.boldSelected ?= "bold text" options.italicSelected ?= "italic text" options.selectedText = "" test.expect 2 * 3 doTest test, 'bold', options.text, options.selectedText, range, options.bold, options.boldSelected doTest test, 'italic', options.text, options.selectedText, range, options.italic, options.italicSelected QUnit.test 'simple bolding', (test) -> doTestCase test, text: "One" bold: "**One**" QUnit.test 'trailing newline', (test) -> doTestCase test, text: "One\n" bold: "**One**\n" boldSelected: "One" QUnit.test 'two trailing newlines', (test) -> doTestCase test, text: "One\n\n" bold: "**One**\n\n" boldSelected: "One" QUnit.test 'three trailing newlines', (test) -> doTestCase test, text: "One\n\n\n" bold: "**One**\n\n\n" boldSelected: "One" QUnit.test 'leading newline', (test) -> doTestCase test, text: "\nOne" bold: "\n**One**" boldSelected: "One" QUnit.test 'two leading newlines', (test) -> doTestCase test, text: "\n\nOne" bold: "\n\n**One**" boldSelected: "One" QUnit.test 'three leading newlines', (test) -> doTestCase test, text: "\n\n\nOne" bold: "\n\n\n**One**" boldSelected: "One" QUnit.test 'two consecutive lines', (test) -> doTestCase test, text: "One\nTwo" bold: "**One**\n**Two**" boldSelected: "One**\n**Two" QUnit.test 'three consecutive lines', (test) -> doTestCase test, text: "One\nTwo\nThree" bold: "**One**\n**Two**\n**Three**" boldSelected: "One**\n**Two**\n**Three" QUnit.test 'two consecutive lines with double newlines', (test) -> doTestCase test, text: "One\n\nTwo" bold: "**One**\n\n**Two**" boldSelected: "One**\n\n**Two" QUnit.test 'three consecutive lines with double newlines', (test) -> doTestCase test, text: """ One Two Three """ bold: """ **One** **Two** **Three** """ boldSelected: """ One** **Two** **Three """ QUnit.test 'empty string', (test) -> doTestCase test, text: "" bold: "**bold text**" boldSelected: "bold text" QUnit.test 'only newlines - one', (test) -> doTestCase test, text: "\n" bold: "\n**bold text**" boldSelected: "bold text" # Leave the entire text selected QUnit.test 'only newlines - two', (test) -> doTestCase test, text: "\n\n" bold: "\n\n**bold text**" boldSelected: "bold text" # Leave the entire text selected QUnit.test "slected text at start of string, before newline", (test) -> doTestCase test, text: """ One Two """ selectedText: "One" bold: """ **One** Two """ QUnit.test "slected text at start of string, includes newline", (test) -> doTestCase test, text: """ One Two """ selectedText: "One\n" bold: """ **One** Two """ boldSelected: "One" # After bold, selection won't include newline QUnit.test "selected text preceded by newlines", (test) -> doTestCase test, text: """ One Two """ selectedText: "One" bold: """ **One** Two """ QUnit.test "selected text includes preceding newlines", (test) -> doTestCase test, text: """ One Two """ selectedText: "\n\nOne" bold: """ **One** Two """ boldSelected: "One" # After trim, won't include newlines QUnit.test "multi-line selection - two paragraphs", (test) -> doTestCase test, text: """ one two three four five six seven eight nine """ selectedText: """ one two three four five six """ bold: """ **one two three** **four five six** seven eight nine """ boldSelected: """ one two three** **four five six """ QUnit.test "multi-line selection - three paragraphs", (test) -> doTestCase test, text: """ one two three four five six seven eight nine ten eleven twelve """ selectedText: """ one two three four five six seven eight nine """ bold: """ **one two three** **four five six** **seven eight nine** ten eleven twelve """ boldSelected: """ one two three** **four five six** **seven eight nine """ QUnit.test "no selection - empty string", (test) -> doTestCase test, text: "" caretIsBefore: /^/ bold: "**bold text**" italic: "*italic text*" QUnit.test "no selection - start of text", (test) -> doTestCase test, text: "PI:NAME:<NAME>END_PI" caretIsBefore: /^/ bold: "**bold text**Hello" italic: "*italic text*Hello" QUnit.test "no selection - end of text", (test) -> doTestCase test, text: "PI:NAME:<NAME>END_PI" caretIsBefore: /$/ bold: "Hello**bold text**" italic: "Hello*italic text*" QUnit.test "no selection - middle of text", (test) -> doTestCase test, text: "PI:NAME:<NAME>END_PI" caretIsBefore: "lo" bold: "Hel**bold text**lo" italic: "Hel*italic text*lo" QUnit.test "no selection - between lines", (test) -> doTestCase test, text: """ One two three Four five six """ caretIsBefore: "Four" bold: """ One two three **bold text**Four five six """, italic: """ One two three *italic text*Four five six """ QUnit.test "no selection - between paragraphs", (test) -> doTestCase test, text: """ One two three Four five six """ caretIsBefore: "\nFour" bold: """ One two three **bold text** Four five six """, italic: """ One two three *italic text* Four five six """ )()
[ { "context": "$('#editor').click()\n alice.$('#editor').type 'hello Bob'\n wait.until (-> bob.$('#editor').text != oldT", "end": 456, "score": 0.702520489692688, "start": 447, "tag": "NAME", "value": "hello Bob" } ]
examples/stypi.coffee
carbonfive/webspecter
33
feature "Stypi collaborative editing", (context) -> alice = context.newContext() bob = context.newContext() before (done) -> alice.browser.visit 'https://www.stypi.com/', -> bob.browser.visit alice.browser.url, done after -> console.log "\tCheck for yourself: #{alice.browser.url}" it "shows other user's text", (done) -> oldText = alice.$('#editor').text alice.$('#editor').click() alice.$('#editor').type 'hello Bob' wait.until (-> bob.$('#editor').text != oldText), -> #bob.browser.page.render 'bob.png' done()
10494
feature "Stypi collaborative editing", (context) -> alice = context.newContext() bob = context.newContext() before (done) -> alice.browser.visit 'https://www.stypi.com/', -> bob.browser.visit alice.browser.url, done after -> console.log "\tCheck for yourself: #{alice.browser.url}" it "shows other user's text", (done) -> oldText = alice.$('#editor').text alice.$('#editor').click() alice.$('#editor').type '<NAME>' wait.until (-> bob.$('#editor').text != oldText), -> #bob.browser.page.render 'bob.png' done()
true
feature "Stypi collaborative editing", (context) -> alice = context.newContext() bob = context.newContext() before (done) -> alice.browser.visit 'https://www.stypi.com/', -> bob.browser.visit alice.browser.url, done after -> console.log "\tCheck for yourself: #{alice.browser.url}" it "shows other user's text", (done) -> oldText = alice.$('#editor').text alice.$('#editor').click() alice.$('#editor').type 'PI:NAME:<NAME>END_PI' wait.until (-> bob.$('#editor').text != oldText), -> #bob.browser.page.render 'bob.png' done()
[ { "context": ".dict[key]\n return value\n\nDEFAULT_STORAGE_KEY = 'mnemosyne.pendingRequests'\n\nmodule.exports = class MagicQueue\n\n # Keep the", "end": 166, "score": 0.9796016812324524, "start": 141, "tag": "KEY", "value": "mnemosyne.pendingRequests" } ]
source/app/magic_queue.coffee
azendoo/mnemosyne
0
### - MagicQueue - ### removeValue = (ctx, key) -> value = ctx.dict[key] delete ctx.dict[key] return value DEFAULT_STORAGE_KEY = 'mnemosyne.pendingRequests' module.exports = class MagicQueue # Keep the order state, only store keys. orderedKeys: [] # Store all value with constant access. dict: {} addHead: (key, value) -> @retrieveItem(key) @orderedKeys.push(key) @dict[key] = value addTail: (key, value) -> @retrieveItem(key) @orderedKeys.unshift(key) @dict[key] = value getHead: -> @dict[_.last(@orderedKeys)] getTail: -> @dict[@orderedKeys[0]] getItem: (key) -> @dict[key] or null rotate: -> return if @orderedKeys.length < 1 @orderedKeys.unshift(@orderedKeys.pop()) retrieveHead: -> return null if @orderedKeys.length is 0 key = @orderedKeys.pop() value = removeValue(@, key) return value retrieveTail: -> return null if @orderedKeys.length is 0 key = @orderedKeys.shift() value = removeValue(@, key) return value retrieveItem: (key) -> return null if not @dict[key]? indexKey = @orderedKeys.indexOf(key) @orderedKeys.splice(indexKey, 1) value = removeValue(@, key) return value isEmpty: -> return @orderedKeys.length is 0 getQueue: () -> _.map(@orderedKeys, (key) => return @dict[key] ) clear: -> @orderedKeys = [] @dict = {}
214540
### - MagicQueue - ### removeValue = (ctx, key) -> value = ctx.dict[key] delete ctx.dict[key] return value DEFAULT_STORAGE_KEY = '<KEY>' module.exports = class MagicQueue # Keep the order state, only store keys. orderedKeys: [] # Store all value with constant access. dict: {} addHead: (key, value) -> @retrieveItem(key) @orderedKeys.push(key) @dict[key] = value addTail: (key, value) -> @retrieveItem(key) @orderedKeys.unshift(key) @dict[key] = value getHead: -> @dict[_.last(@orderedKeys)] getTail: -> @dict[@orderedKeys[0]] getItem: (key) -> @dict[key] or null rotate: -> return if @orderedKeys.length < 1 @orderedKeys.unshift(@orderedKeys.pop()) retrieveHead: -> return null if @orderedKeys.length is 0 key = @orderedKeys.pop() value = removeValue(@, key) return value retrieveTail: -> return null if @orderedKeys.length is 0 key = @orderedKeys.shift() value = removeValue(@, key) return value retrieveItem: (key) -> return null if not @dict[key]? indexKey = @orderedKeys.indexOf(key) @orderedKeys.splice(indexKey, 1) value = removeValue(@, key) return value isEmpty: -> return @orderedKeys.length is 0 getQueue: () -> _.map(@orderedKeys, (key) => return @dict[key] ) clear: -> @orderedKeys = [] @dict = {}
true
### - MagicQueue - ### removeValue = (ctx, key) -> value = ctx.dict[key] delete ctx.dict[key] return value DEFAULT_STORAGE_KEY = 'PI:KEY:<KEY>END_PI' module.exports = class MagicQueue # Keep the order state, only store keys. orderedKeys: [] # Store all value with constant access. dict: {} addHead: (key, value) -> @retrieveItem(key) @orderedKeys.push(key) @dict[key] = value addTail: (key, value) -> @retrieveItem(key) @orderedKeys.unshift(key) @dict[key] = value getHead: -> @dict[_.last(@orderedKeys)] getTail: -> @dict[@orderedKeys[0]] getItem: (key) -> @dict[key] or null rotate: -> return if @orderedKeys.length < 1 @orderedKeys.unshift(@orderedKeys.pop()) retrieveHead: -> return null if @orderedKeys.length is 0 key = @orderedKeys.pop() value = removeValue(@, key) return value retrieveTail: -> return null if @orderedKeys.length is 0 key = @orderedKeys.shift() value = removeValue(@, key) return value retrieveItem: (key) -> return null if not @dict[key]? indexKey = @orderedKeys.indexOf(key) @orderedKeys.splice(indexKey, 1) value = removeValue(@, key) return value isEmpty: -> return @orderedKeys.length is 0 getQueue: () -> _.map(@orderedKeys, (key) => return @dict[key] ) clear: -> @orderedKeys = [] @dict = {}
[ { "context": "kg, \"package.json\"), JSON.stringify(\n author: \"Evan Lucas\"\n name: \"404-parent-test\"\n version: \"0.0.0\"", "end": 163, "score": 0.9998489618301392, "start": 153, "tag": "NAME", "value": "Evan Lucas" } ]
deps/npm/test/tap/404-parent.coffee
lxe/io.coffee
0
setup = -> mkdirp.sync pkg mkdirp.sync path.resolve(pkg, "cache") fs.writeFileSync path.resolve(pkg, "package.json"), JSON.stringify( author: "Evan Lucas" name: "404-parent-test" version: "0.0.0" description: "Test for 404-parent" dependencies: "test-npm-404-parent-test": "*" ), "utf8" process.chdir pkg return performInstall = (cb) -> mr common.port, (s) -> # create mock registry. npm.load registry: common.registry , -> npm.commands.install pkg, [], (err) -> cb err s.close() # shutdown mock npm server. return return return return common = require("../common-tap.js") test = require("tap").test npm = require("../../") osenv = require("osenv") path = require("path") fs = require("fs") rimraf = require("rimraf") mkdirp = require("mkdirp") pkg = path.resolve(__dirname, "404-parent") mr = require("npm-registry-mock") test "404-parent: if parent exists, specify parent in error message", (t) -> setup() rimraf.sync path.resolve(pkg, "node_modules") performInstall (err) -> t.ok err instanceof Error, "error was returned" t.ok err.parent is "404-parent-test", "error's parent set" t.end() return return test "cleanup", (t) -> process.chdir osenv.tmpdir() rimraf.sync pkg t.end() return
209256
setup = -> mkdirp.sync pkg mkdirp.sync path.resolve(pkg, "cache") fs.writeFileSync path.resolve(pkg, "package.json"), JSON.stringify( author: "<NAME>" name: "404-parent-test" version: "0.0.0" description: "Test for 404-parent" dependencies: "test-npm-404-parent-test": "*" ), "utf8" process.chdir pkg return performInstall = (cb) -> mr common.port, (s) -> # create mock registry. npm.load registry: common.registry , -> npm.commands.install pkg, [], (err) -> cb err s.close() # shutdown mock npm server. return return return return common = require("../common-tap.js") test = require("tap").test npm = require("../../") osenv = require("osenv") path = require("path") fs = require("fs") rimraf = require("rimraf") mkdirp = require("mkdirp") pkg = path.resolve(__dirname, "404-parent") mr = require("npm-registry-mock") test "404-parent: if parent exists, specify parent in error message", (t) -> setup() rimraf.sync path.resolve(pkg, "node_modules") performInstall (err) -> t.ok err instanceof Error, "error was returned" t.ok err.parent is "404-parent-test", "error's parent set" t.end() return return test "cleanup", (t) -> process.chdir osenv.tmpdir() rimraf.sync pkg t.end() return
true
setup = -> mkdirp.sync pkg mkdirp.sync path.resolve(pkg, "cache") fs.writeFileSync path.resolve(pkg, "package.json"), JSON.stringify( author: "PI:NAME:<NAME>END_PI" name: "404-parent-test" version: "0.0.0" description: "Test for 404-parent" dependencies: "test-npm-404-parent-test": "*" ), "utf8" process.chdir pkg return performInstall = (cb) -> mr common.port, (s) -> # create mock registry. npm.load registry: common.registry , -> npm.commands.install pkg, [], (err) -> cb err s.close() # shutdown mock npm server. return return return return common = require("../common-tap.js") test = require("tap").test npm = require("../../") osenv = require("osenv") path = require("path") fs = require("fs") rimraf = require("rimraf") mkdirp = require("mkdirp") pkg = path.resolve(__dirname, "404-parent") mr = require("npm-registry-mock") test "404-parent: if parent exists, specify parent in error message", (t) -> setup() rimraf.sync path.resolve(pkg, "node_modules") performInstall (err) -> t.ok err instanceof Error, "error was returned" t.ok err.parent is "404-parent-test", "error's parent set" t.end() return return test "cleanup", (t) -> process.chdir osenv.tmpdir() rimraf.sync pkg t.end() return
[ { "context": "terWithPin.returns @q.when(uuid: 'shock', token: 'and-aww-yeah')\n\n describe 'when called with the pin 1234'", "end": 1669, "score": 0.9951852560043335, "start": 1657, "tag": "PASSWORD", "value": "and-aww-yeah" }, { "context": "', ->\n expect(@cookies.uuid).to.equal 'shock'\n\n it 'should set the uuid in the cookies'", "end": 2160, "score": 0.9769183993339539, "start": 2157, "tag": "PASSWORD", "value": "ock" }, { "context": "s', ->\n expect(@cookies.token).to.equal 'and-aww-yeah'\n\n describe 'when registerWithPin fulfills the", "end": 2270, "score": 0.927628219127655, "start": 2258, "tag": "PASSWORD", "value": "and-aww-yeah" }, { "context": "ns @q.when(uuid: 'slow-turning-windmill', token: 'how-quixotic')\n\n describe 'when called with the pin 6543'", "end": 2469, "score": 0.9987139701843262, "start": 2457, "tag": "PASSWORD", "value": "how-quixotic" }, { "context": " uuid: 'some-uuid'\n token: 'some-token'\n $location: @location\n Au", "end": 3433, "score": 0.4980444312095642, "start": 3433, "tag": "PASSWORD", "value": "" } ]
test/register/register-controller-spec.coffee
octoblu/blu-web
3
describe 'RegisterController', -> beforeEach -> module 'blu' inject ($controller, $q, $rootScope) -> @q = $q @rootScope = $rootScope describe 'when the user has no existing session', -> beforeEach -> inject ($controller, $rootScope) -> @location = path: sinon.stub() @authenticatorService = registerWithPin: sinon.stub() @cookies = {} @sut = $controller 'RegisterController', $cookies: @cookies $location: @location AuthenticatorService: @authenticatorService describe 'when register is called with an empty string', -> beforeEach -> @sut.register '' it 'should set an errorMessage explaining that a pin is required', -> expect(@sut.errorMessage).to.equal @sut.ERROR_NO_PIN describe 'when register is called with not-a-number', -> beforeEach -> @sut.register 'not-a-number' it 'should set an errorMessage explaining that the pin needs to be a number', -> expect(@sut.errorMessage).to.equal @sut.ERROR_PIN_NOT_NUMERIC describe 'when authenticatorService rejects its promise', -> beforeEach -> @authenticatorService.registerWithPin.returns @q.reject(new Error('oh no')) it "should tell the user that it couldn't register a device", -> @sut.register '1234' @rootScope.$digest() expect(@sut.errorMessage).to.equal 'Unable to register a new device. Please try again.' describe 'when registerWithPin fulfills its promise with shock', -> beforeEach -> @authenticatorService.registerWithPin.returns @q.when(uuid: 'shock', token: 'and-aww-yeah') describe 'when called with the pin 1234', -> beforeEach -> @sut.register '1234' @rootScope.$digest() it 'should call authenticatorService registerWithPin with the pin', -> expect(@authenticatorService.registerWithPin).to.have.been.calledWith '1234' it 'should not have an error', -> expect(@sut.error).to.not.exist it 'should set the uuid in the cookies', -> expect(@cookies.uuid).to.equal 'shock' it 'should set the uuid in the cookies', -> expect(@cookies.token).to.equal 'and-aww-yeah' describe 'when registerWithPin fulfills their promise', -> beforeEach -> @authenticatorService.registerWithPin.returns @q.when(uuid: 'slow-turning-windmill', token: 'how-quixotic') describe 'when called with the pin 6543', -> beforeEach -> @sut.register '6543' @rootScope.$digest() it 'should call authenticatorService registerWithPin with the pin', -> expect(@authenticatorService.registerWithPin).to.have.been.calledWith '6543' it 'should set the uuid in the cookies', -> expect(@cookies.uuid).to.equal 'slow-turning-windmill' it 'should set the token in the cookies', -> expect(@cookies.uuid).to.equal 'slow-turning-windmill' it 'should redirect the user to the home page', -> expect(@location.path).to.have.been.calledWith '/slow-turning-windmill' describe 'when the user has an existing session', -> beforeEach -> @location = path: sinon.spy() inject ($controller, $rootScope) => @sut = $controller 'RegisterController', $cookies: uuid: 'some-uuid' token: 'some-token' $location: @location AuthenticatorService: {} it 'should call location.path', -> expect(@location.path).to.have.been.calledWith '/some-uuid' describe 'when a different user has an existing session', -> beforeEach -> @location = path: sinon.spy() inject ($controller, $rootScope) => @sut = $controller 'RegisterController', $cookies: uuid: 'voracious-animals' token: 'token' $location: @location AuthenticatorService: {} it 'should call location.path', -> expect(@location.path).to.have.been.calledWith '/voracious-animals'
207153
describe 'RegisterController', -> beforeEach -> module 'blu' inject ($controller, $q, $rootScope) -> @q = $q @rootScope = $rootScope describe 'when the user has no existing session', -> beforeEach -> inject ($controller, $rootScope) -> @location = path: sinon.stub() @authenticatorService = registerWithPin: sinon.stub() @cookies = {} @sut = $controller 'RegisterController', $cookies: @cookies $location: @location AuthenticatorService: @authenticatorService describe 'when register is called with an empty string', -> beforeEach -> @sut.register '' it 'should set an errorMessage explaining that a pin is required', -> expect(@sut.errorMessage).to.equal @sut.ERROR_NO_PIN describe 'when register is called with not-a-number', -> beforeEach -> @sut.register 'not-a-number' it 'should set an errorMessage explaining that the pin needs to be a number', -> expect(@sut.errorMessage).to.equal @sut.ERROR_PIN_NOT_NUMERIC describe 'when authenticatorService rejects its promise', -> beforeEach -> @authenticatorService.registerWithPin.returns @q.reject(new Error('oh no')) it "should tell the user that it couldn't register a device", -> @sut.register '1234' @rootScope.$digest() expect(@sut.errorMessage).to.equal 'Unable to register a new device. Please try again.' describe 'when registerWithPin fulfills its promise with shock', -> beforeEach -> @authenticatorService.registerWithPin.returns @q.when(uuid: 'shock', token: '<PASSWORD>') describe 'when called with the pin 1234', -> beforeEach -> @sut.register '1234' @rootScope.$digest() it 'should call authenticatorService registerWithPin with the pin', -> expect(@authenticatorService.registerWithPin).to.have.been.calledWith '1234' it 'should not have an error', -> expect(@sut.error).to.not.exist it 'should set the uuid in the cookies', -> expect(@cookies.uuid).to.equal 'sh<PASSWORD>' it 'should set the uuid in the cookies', -> expect(@cookies.token).to.equal '<PASSWORD>' describe 'when registerWithPin fulfills their promise', -> beforeEach -> @authenticatorService.registerWithPin.returns @q.when(uuid: 'slow-turning-windmill', token: '<PASSWORD>') describe 'when called with the pin 6543', -> beforeEach -> @sut.register '6543' @rootScope.$digest() it 'should call authenticatorService registerWithPin with the pin', -> expect(@authenticatorService.registerWithPin).to.have.been.calledWith '6543' it 'should set the uuid in the cookies', -> expect(@cookies.uuid).to.equal 'slow-turning-windmill' it 'should set the token in the cookies', -> expect(@cookies.uuid).to.equal 'slow-turning-windmill' it 'should redirect the user to the home page', -> expect(@location.path).to.have.been.calledWith '/slow-turning-windmill' describe 'when the user has an existing session', -> beforeEach -> @location = path: sinon.spy() inject ($controller, $rootScope) => @sut = $controller 'RegisterController', $cookies: uuid: 'some-uuid' token: 'some<PASSWORD>-token' $location: @location AuthenticatorService: {} it 'should call location.path', -> expect(@location.path).to.have.been.calledWith '/some-uuid' describe 'when a different user has an existing session', -> beforeEach -> @location = path: sinon.spy() inject ($controller, $rootScope) => @sut = $controller 'RegisterController', $cookies: uuid: 'voracious-animals' token: 'token' $location: @location AuthenticatorService: {} it 'should call location.path', -> expect(@location.path).to.have.been.calledWith '/voracious-animals'
true
describe 'RegisterController', -> beforeEach -> module 'blu' inject ($controller, $q, $rootScope) -> @q = $q @rootScope = $rootScope describe 'when the user has no existing session', -> beforeEach -> inject ($controller, $rootScope) -> @location = path: sinon.stub() @authenticatorService = registerWithPin: sinon.stub() @cookies = {} @sut = $controller 'RegisterController', $cookies: @cookies $location: @location AuthenticatorService: @authenticatorService describe 'when register is called with an empty string', -> beforeEach -> @sut.register '' it 'should set an errorMessage explaining that a pin is required', -> expect(@sut.errorMessage).to.equal @sut.ERROR_NO_PIN describe 'when register is called with not-a-number', -> beforeEach -> @sut.register 'not-a-number' it 'should set an errorMessage explaining that the pin needs to be a number', -> expect(@sut.errorMessage).to.equal @sut.ERROR_PIN_NOT_NUMERIC describe 'when authenticatorService rejects its promise', -> beforeEach -> @authenticatorService.registerWithPin.returns @q.reject(new Error('oh no')) it "should tell the user that it couldn't register a device", -> @sut.register '1234' @rootScope.$digest() expect(@sut.errorMessage).to.equal 'Unable to register a new device. Please try again.' describe 'when registerWithPin fulfills its promise with shock', -> beforeEach -> @authenticatorService.registerWithPin.returns @q.when(uuid: 'shock', token: 'PI:PASSWORD:<PASSWORD>END_PI') describe 'when called with the pin 1234', -> beforeEach -> @sut.register '1234' @rootScope.$digest() it 'should call authenticatorService registerWithPin with the pin', -> expect(@authenticatorService.registerWithPin).to.have.been.calledWith '1234' it 'should not have an error', -> expect(@sut.error).to.not.exist it 'should set the uuid in the cookies', -> expect(@cookies.uuid).to.equal 'shPI:PASSWORD:<PASSWORD>END_PI' it 'should set the uuid in the cookies', -> expect(@cookies.token).to.equal 'PI:PASSWORD:<PASSWORD>END_PI' describe 'when registerWithPin fulfills their promise', -> beforeEach -> @authenticatorService.registerWithPin.returns @q.when(uuid: 'slow-turning-windmill', token: 'PI:PASSWORD:<PASSWORD>END_PI') describe 'when called with the pin 6543', -> beforeEach -> @sut.register '6543' @rootScope.$digest() it 'should call authenticatorService registerWithPin with the pin', -> expect(@authenticatorService.registerWithPin).to.have.been.calledWith '6543' it 'should set the uuid in the cookies', -> expect(@cookies.uuid).to.equal 'slow-turning-windmill' it 'should set the token in the cookies', -> expect(@cookies.uuid).to.equal 'slow-turning-windmill' it 'should redirect the user to the home page', -> expect(@location.path).to.have.been.calledWith '/slow-turning-windmill' describe 'when the user has an existing session', -> beforeEach -> @location = path: sinon.spy() inject ($controller, $rootScope) => @sut = $controller 'RegisterController', $cookies: uuid: 'some-uuid' token: 'somePI:PASSWORD:<PASSWORD>END_PI-token' $location: @location AuthenticatorService: {} it 'should call location.path', -> expect(@location.path).to.have.been.calledWith '/some-uuid' describe 'when a different user has an existing session', -> beforeEach -> @location = path: sinon.spy() inject ($controller, $rootScope) => @sut = $controller 'RegisterController', $cookies: uuid: 'voracious-animals' token: 'token' $location: @location AuthenticatorService: {} it 'should call location.path', -> expect(@location.path).to.have.been.calledWith '/voracious-animals'
[ { "context": ".createElement('input')\n user_password.type = 'password'\n user_password.classList.add('freelog-credent", "end": 628, "score": 0.9415736794471741, "start": 620, "tag": "PASSWORD", "value": "password" }, { "context": "ype = 'password'\n user_password.classList.add('freelog-credential-password')\n #submit button\n s", "end": 667, "score": 0.575351357460022, "start": 663, "tag": "PASSWORD", "value": "free" } ]
lib/freelog-mdpub-view.coffee
miushock/freelog-mdpub
0
module.exports = class FreelogMdpubView constructor: (serializedState) -> # Create root element @element = document.createElement('div') @element.classList.add('freelog-mdpub') message = document.createElement('div') @element.appendChild(message) # enter user info user_info = document.createElement('div') user_info.classList.add('freelog-credential') #email and pw user_email = document.createElement('input') user_email.type = 'email' user_email.classList.add('freelog-credential-email') user_password = document.createElement('input') user_password.type = 'password' user_password.classList.add('freelog-credential-password') #submit button submit_button = document.createElement('button') submit_button.textContent = 'submit' submit_button.classList.add('freelog-submit') user_info.appendChild(user_email) user_info.appendChild(user_password) @element.appendChild(user_info) @element.appendChild(submit_button) # Returns an object that can be retrieved when package is activated serialize: -> # Tear down any state and detach destroy: -> @element.remove() getElement: -> @element setMsg: (m) -> @element.children[0].textContent = m
115174
module.exports = class FreelogMdpubView constructor: (serializedState) -> # Create root element @element = document.createElement('div') @element.classList.add('freelog-mdpub') message = document.createElement('div') @element.appendChild(message) # enter user info user_info = document.createElement('div') user_info.classList.add('freelog-credential') #email and pw user_email = document.createElement('input') user_email.type = 'email' user_email.classList.add('freelog-credential-email') user_password = document.createElement('input') user_password.type = '<PASSWORD>' user_password.classList.add('<PASSWORD>log-credential-password') #submit button submit_button = document.createElement('button') submit_button.textContent = 'submit' submit_button.classList.add('freelog-submit') user_info.appendChild(user_email) user_info.appendChild(user_password) @element.appendChild(user_info) @element.appendChild(submit_button) # Returns an object that can be retrieved when package is activated serialize: -> # Tear down any state and detach destroy: -> @element.remove() getElement: -> @element setMsg: (m) -> @element.children[0].textContent = m
true
module.exports = class FreelogMdpubView constructor: (serializedState) -> # Create root element @element = document.createElement('div') @element.classList.add('freelog-mdpub') message = document.createElement('div') @element.appendChild(message) # enter user info user_info = document.createElement('div') user_info.classList.add('freelog-credential') #email and pw user_email = document.createElement('input') user_email.type = 'email' user_email.classList.add('freelog-credential-email') user_password = document.createElement('input') user_password.type = 'PI:PASSWORD:<PASSWORD>END_PI' user_password.classList.add('PI:PASSWORD:<PASSWORD>END_PIlog-credential-password') #submit button submit_button = document.createElement('button') submit_button.textContent = 'submit' submit_button.classList.add('freelog-submit') user_info.appendChild(user_email) user_info.appendChild(user_password) @element.appendChild(user_info) @element.appendChild(submit_button) # Returns an object that can be retrieved when package is activated serialize: -> # Tear down any state and detach destroy: -> @element.remove() getElement: -> @element setMsg: (m) -> @element.children[0].textContent = m
[ { "context": "ructor: ->\n console.log('Init')\n @list1 = ['Bob', 'John', 'Jane']\n @list2 = []\n\n onDragList1:", "end": 140, "score": 0.99982750415802, "start": 137, "tag": "NAME", "value": "Bob" }, { "context": " ->\n console.log('Init')\n @list1 = ['Bob', 'John', 'Jane']\n @list2 = []\n\n onDragList1: ->\n ", "end": 148, "score": 0.999832034111023, "start": 144, "tag": "NAME", "value": "John" }, { "context": "console.log('Init')\n @list1 = ['Bob', 'John', 'Jane']\n @list2 = []\n\n onDragList1: ->\n console.", "end": 156, "score": 0.9996451139450073, "start": 152, "tag": "NAME", "value": "Jane" } ]
src/test/resources/app/app.coffee
benweizhu/simplelenium
52
dnd = angular.module 'dnd', ['ngDraggable'] .controller 'DndController', class constructor: -> console.log('Init') @list1 = ['Bob', 'John', 'Jane'] @list2 = [] onDragList1: -> console.log('Drag from list1') onDragList2: -> console.log('Drag from list2') onEnterList2: -> console.log('Enter list2') onDropList1: (data) -> return unless data? console.log('Drop on list1') @removeFromLists(data) @list1.push(data) onDropList2: (data) -> return unless data? console.log('Drop on list2') @removeFromLists(data) @list2.push(data) removeFromLists: (data) -> @list2 = (item for item in @list2 when item isnt data) @list1 = (item for item in @list1 when item isnt data)
117141
dnd = angular.module 'dnd', ['ngDraggable'] .controller 'DndController', class constructor: -> console.log('Init') @list1 = ['<NAME>', '<NAME>', '<NAME>'] @list2 = [] onDragList1: -> console.log('Drag from list1') onDragList2: -> console.log('Drag from list2') onEnterList2: -> console.log('Enter list2') onDropList1: (data) -> return unless data? console.log('Drop on list1') @removeFromLists(data) @list1.push(data) onDropList2: (data) -> return unless data? console.log('Drop on list2') @removeFromLists(data) @list2.push(data) removeFromLists: (data) -> @list2 = (item for item in @list2 when item isnt data) @list1 = (item for item in @list1 when item isnt data)
true
dnd = angular.module 'dnd', ['ngDraggable'] .controller 'DndController', class constructor: -> console.log('Init') @list1 = ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] @list2 = [] onDragList1: -> console.log('Drag from list1') onDragList2: -> console.log('Drag from list2') onEnterList2: -> console.log('Enter list2') onDropList1: (data) -> return unless data? console.log('Drop on list1') @removeFromLists(data) @list1.push(data) onDropList2: (data) -> return unless data? console.log('Drop on list2') @removeFromLists(data) @list2.push(data) removeFromLists: (data) -> @list2 = (item for item in @list2 when item isnt data) @list1 = (item for item in @list1 when item isnt data)
[ { "context": "@namespace Atoms.Molecule\n@class Calendar\n\n@author Javier Jimenez Villar @soyjavi\n###\n\"use strict\"\n\nclass Atoms.Molecule.C", "end": 83, "score": 0.9997739195823669, "start": 62, "tag": "NAME", "value": "Javier Jimenez Villar" }, { "context": "ule\n@class Calendar\n\n@author Javier Jimenez Villar @soyjavi\n###\n\"use strict\"\n\nclass Atoms.Molecule.Calendar e", "end": 92, "score": 0.9945244789123535, "start": 84, "tag": "USERNAME", "value": "@soyjavi" } ]
molecule/calendar.coffee
tapquo/atoms-app-calendar
0
### @TODO @namespace Atoms.Molecule @class Calendar @author Javier Jimenez Villar @soyjavi ### "use strict" class Atoms.Molecule.Calendar extends Atoms.Molecule.Div @extends : true @available : ["Atom.Day", "Molecule.Div"] @events : ["select"] @default : months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] days : ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] children: [ "Molecule.Div": id: "header", children: [ "Atom.Button": icon:"angle-left", style: "transparent", callbacks: ["onPreviousMonth"] , "Atom.Heading": id: "literal", value: "Year", size: "h4" , "Atom.Button": icon:"angle-right", style: "transparent", callbacks: ["onNextMonth"] ] ] @child_class: "App.Extension.Calendar.Day" constructor: (attributes = {}) -> for key in ["months", "days"] when not attributes[key] attributes[key] = @constructor.default[key] super attributes @events = {} @today = new Date() @today = new Date(@today.getFullYear(), @today.getMonth(), @today.getDate()) @date new Date attributes.date or @today refresh: -> super @date new Date @attributes.date or @today # -- Instance methods ---------------------------------------------------------- date: (@current = new Date()) -> @_showMonth @current setEvent: (values, data = {}) -> values = [values] unless Array.isArray(values) for value in values @events[value] = data @_find(value)?.setEvent?(data) removeEvent: (values) -> values = [values] unless Array.isArray(values) for value in values delete @events[value] @_find(value)?.removeEvent?() removeAllEvents: -> @events = [] @date @current # -- Bubble Children Events -------------------------------------------------- onPreviousMonth: -> @_showMonth @_previousMonth() false onNextMonth: -> @_showMonth @_nextMonth() false onDayTouch: (event, atom) -> atom.el .addClass "active" .siblings()?.removeClass "active" if atom.attributes.date.getMonth() isnt @current.getMonth() @date atom.attributes.date else @current = atom.attributes.date @bubble "select", atom false # -- Private Events ---------------------------------------------------------- _showMonth: (date) -> @year = date.getFullYear() @month = date.getMonth() # Header @header.literal.el.html "#{@attributes.months[@month]} <small>#{@year}</small>" @el.removeClass key for key in ["disabled", "disable_previous_days"] @el.addClass "disabled" if @attributes.disabled if @attributes.disable_previous_days and @month is new Date().getMonth() @el.addClass "disable_previous_days" child.destroy() for child in @children when child?.constructor.name is "Day" @children = [@children[0]] # Days header for day in @attributes.days @appendChild @constructor.child_class, day: day, summary: true # Previous Month visible Days first_day_of_month = new Date(@year, @month).getDay() - 1 first_day_of_month = 6 if first_day_of_month < 0 previous_month = @_previousMonth() previous_days = @_daysInMonth(previous_month) - (first_day_of_month - 1) for day in [0...first_day_of_month] @appendChild @constructor.child_class, day : previous_days current : false previous_days++ # Current Month Days for day in [1..@_daysInMonth(date)] date = new Date(@year, @month, day) values = day : day date : date month : true today : @today.toString().substring(4, 15) is date.toString().substring(4, 15) active: @current.toString().substring(4, 15) is date.toString().substring(4, 15) values.event = @events[date] if @events[date]? values.events = ["touch"] if @_active date @appendChild @constructor.child_class, values # Next Month visible Days last_day_of_month = new Date(@year, @month, @_daysInMonth(date)).getDay() day = 1 for index in [6..last_day_of_month] @appendChild @constructor.child_class, day : day current : false day++ _previousMonth: -> new Date @year, (@month - 1), 1 _nextMonth: -> new Date @year, (@month + 1), 1 _daysInMonth: (date) -> 32 - new Date(date.getYear(), date.getMonth(), 32).getDate() _find: (date) -> return day for day in @children when date - day.attributes.date is 0 _active: (date) -> return false if @attributes.disable_previous_days and date < @today format_date = @_format date return false if @attributes.available? and format_date not in @attributes.available return false if @attributes.from? and @attributes.from > format_date return false if @attributes.to? and @attributes.to < format_date return true _format: (date) -> date = new Date(date) str = "#{date.getFullYear()}/" month = date.getMonth() + 1 str += if month < 10 then "0#{month}/" else "#{month}/" day = date.getDate() str += if day < 10 then "0#{day}" else "#{day}" str
18428
### @TODO @namespace Atoms.Molecule @class Calendar @author <NAME> @soyjavi ### "use strict" class Atoms.Molecule.Calendar extends Atoms.Molecule.Div @extends : true @available : ["Atom.Day", "Molecule.Div"] @events : ["select"] @default : months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] days : ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] children: [ "Molecule.Div": id: "header", children: [ "Atom.Button": icon:"angle-left", style: "transparent", callbacks: ["onPreviousMonth"] , "Atom.Heading": id: "literal", value: "Year", size: "h4" , "Atom.Button": icon:"angle-right", style: "transparent", callbacks: ["onNextMonth"] ] ] @child_class: "App.Extension.Calendar.Day" constructor: (attributes = {}) -> for key in ["months", "days"] when not attributes[key] attributes[key] = @constructor.default[key] super attributes @events = {} @today = new Date() @today = new Date(@today.getFullYear(), @today.getMonth(), @today.getDate()) @date new Date attributes.date or @today refresh: -> super @date new Date @attributes.date or @today # -- Instance methods ---------------------------------------------------------- date: (@current = new Date()) -> @_showMonth @current setEvent: (values, data = {}) -> values = [values] unless Array.isArray(values) for value in values @events[value] = data @_find(value)?.setEvent?(data) removeEvent: (values) -> values = [values] unless Array.isArray(values) for value in values delete @events[value] @_find(value)?.removeEvent?() removeAllEvents: -> @events = [] @date @current # -- Bubble Children Events -------------------------------------------------- onPreviousMonth: -> @_showMonth @_previousMonth() false onNextMonth: -> @_showMonth @_nextMonth() false onDayTouch: (event, atom) -> atom.el .addClass "active" .siblings()?.removeClass "active" if atom.attributes.date.getMonth() isnt @current.getMonth() @date atom.attributes.date else @current = atom.attributes.date @bubble "select", atom false # -- Private Events ---------------------------------------------------------- _showMonth: (date) -> @year = date.getFullYear() @month = date.getMonth() # Header @header.literal.el.html "#{@attributes.months[@month]} <small>#{@year}</small>" @el.removeClass key for key in ["disabled", "disable_previous_days"] @el.addClass "disabled" if @attributes.disabled if @attributes.disable_previous_days and @month is new Date().getMonth() @el.addClass "disable_previous_days" child.destroy() for child in @children when child?.constructor.name is "Day" @children = [@children[0]] # Days header for day in @attributes.days @appendChild @constructor.child_class, day: day, summary: true # Previous Month visible Days first_day_of_month = new Date(@year, @month).getDay() - 1 first_day_of_month = 6 if first_day_of_month < 0 previous_month = @_previousMonth() previous_days = @_daysInMonth(previous_month) - (first_day_of_month - 1) for day in [0...first_day_of_month] @appendChild @constructor.child_class, day : previous_days current : false previous_days++ # Current Month Days for day in [1..@_daysInMonth(date)] date = new Date(@year, @month, day) values = day : day date : date month : true today : @today.toString().substring(4, 15) is date.toString().substring(4, 15) active: @current.toString().substring(4, 15) is date.toString().substring(4, 15) values.event = @events[date] if @events[date]? values.events = ["touch"] if @_active date @appendChild @constructor.child_class, values # Next Month visible Days last_day_of_month = new Date(@year, @month, @_daysInMonth(date)).getDay() day = 1 for index in [6..last_day_of_month] @appendChild @constructor.child_class, day : day current : false day++ _previousMonth: -> new Date @year, (@month - 1), 1 _nextMonth: -> new Date @year, (@month + 1), 1 _daysInMonth: (date) -> 32 - new Date(date.getYear(), date.getMonth(), 32).getDate() _find: (date) -> return day for day in @children when date - day.attributes.date is 0 _active: (date) -> return false if @attributes.disable_previous_days and date < @today format_date = @_format date return false if @attributes.available? and format_date not in @attributes.available return false if @attributes.from? and @attributes.from > format_date return false if @attributes.to? and @attributes.to < format_date return true _format: (date) -> date = new Date(date) str = "#{date.getFullYear()}/" month = date.getMonth() + 1 str += if month < 10 then "0#{month}/" else "#{month}/" day = date.getDate() str += if day < 10 then "0#{day}" else "#{day}" str
true
### @TODO @namespace Atoms.Molecule @class Calendar @author PI:NAME:<NAME>END_PI @soyjavi ### "use strict" class Atoms.Molecule.Calendar extends Atoms.Molecule.Div @extends : true @available : ["Atom.Day", "Molecule.Div"] @events : ["select"] @default : months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] days : ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] children: [ "Molecule.Div": id: "header", children: [ "Atom.Button": icon:"angle-left", style: "transparent", callbacks: ["onPreviousMonth"] , "Atom.Heading": id: "literal", value: "Year", size: "h4" , "Atom.Button": icon:"angle-right", style: "transparent", callbacks: ["onNextMonth"] ] ] @child_class: "App.Extension.Calendar.Day" constructor: (attributes = {}) -> for key in ["months", "days"] when not attributes[key] attributes[key] = @constructor.default[key] super attributes @events = {} @today = new Date() @today = new Date(@today.getFullYear(), @today.getMonth(), @today.getDate()) @date new Date attributes.date or @today refresh: -> super @date new Date @attributes.date or @today # -- Instance methods ---------------------------------------------------------- date: (@current = new Date()) -> @_showMonth @current setEvent: (values, data = {}) -> values = [values] unless Array.isArray(values) for value in values @events[value] = data @_find(value)?.setEvent?(data) removeEvent: (values) -> values = [values] unless Array.isArray(values) for value in values delete @events[value] @_find(value)?.removeEvent?() removeAllEvents: -> @events = [] @date @current # -- Bubble Children Events -------------------------------------------------- onPreviousMonth: -> @_showMonth @_previousMonth() false onNextMonth: -> @_showMonth @_nextMonth() false onDayTouch: (event, atom) -> atom.el .addClass "active" .siblings()?.removeClass "active" if atom.attributes.date.getMonth() isnt @current.getMonth() @date atom.attributes.date else @current = atom.attributes.date @bubble "select", atom false # -- Private Events ---------------------------------------------------------- _showMonth: (date) -> @year = date.getFullYear() @month = date.getMonth() # Header @header.literal.el.html "#{@attributes.months[@month]} <small>#{@year}</small>" @el.removeClass key for key in ["disabled", "disable_previous_days"] @el.addClass "disabled" if @attributes.disabled if @attributes.disable_previous_days and @month is new Date().getMonth() @el.addClass "disable_previous_days" child.destroy() for child in @children when child?.constructor.name is "Day" @children = [@children[0]] # Days header for day in @attributes.days @appendChild @constructor.child_class, day: day, summary: true # Previous Month visible Days first_day_of_month = new Date(@year, @month).getDay() - 1 first_day_of_month = 6 if first_day_of_month < 0 previous_month = @_previousMonth() previous_days = @_daysInMonth(previous_month) - (first_day_of_month - 1) for day in [0...first_day_of_month] @appendChild @constructor.child_class, day : previous_days current : false previous_days++ # Current Month Days for day in [1..@_daysInMonth(date)] date = new Date(@year, @month, day) values = day : day date : date month : true today : @today.toString().substring(4, 15) is date.toString().substring(4, 15) active: @current.toString().substring(4, 15) is date.toString().substring(4, 15) values.event = @events[date] if @events[date]? values.events = ["touch"] if @_active date @appendChild @constructor.child_class, values # Next Month visible Days last_day_of_month = new Date(@year, @month, @_daysInMonth(date)).getDay() day = 1 for index in [6..last_day_of_month] @appendChild @constructor.child_class, day : day current : false day++ _previousMonth: -> new Date @year, (@month - 1), 1 _nextMonth: -> new Date @year, (@month + 1), 1 _daysInMonth: (date) -> 32 - new Date(date.getYear(), date.getMonth(), 32).getDate() _find: (date) -> return day for day in @children when date - day.attributes.date is 0 _active: (date) -> return false if @attributes.disable_previous_days and date < @today format_date = @_format date return false if @attributes.available? and format_date not in @attributes.available return false if @attributes.from? and @attributes.from > format_date return false if @attributes.to? and @attributes.to < format_date return true _format: (date) -> date = new Date(date) str = "#{date.getFullYear()}/" month = date.getMonth() + 1 str += if month < 10 then "0#{month}/" else "#{month}/" day = date.getDate() str += if day < 10 then "0#{day}" else "#{day}" str
[ { "context": "#\n# Initialisation CoffeeScript file.\n#\n# @author Matthew Casey\n#\n# (c) University of Surrey 2019\n#\n\n# Initialise", "end": 63, "score": 0.9998499155044556, "start": 50, "tag": "NAME", "value": "Matthew Casey" } ]
app/assets/javascripts/init.coffee
saschneider/VMVLedger
0
# # Initialisation CoffeeScript file. # # @author Matthew Casey # # (c) University of Surrey 2019 # # Initialise the application object. Based on: # http://brandonhilkert.com/blog/organizing-javascript-in-rails-application-with-turbolinks/ window.VMV ||= {} # # Initialise whenever the page is loaded. # $ -> VMV.init() # # Initialisation for all pages. # VMV.init = -> # Confirm modal dialogue defaults. dataConfirmModal.setDefaults( title: gon.modal_confirm_title commit: gon.modal_confirm_commit cancel: gon.modal_confirm_cancel ) return
208673
# # Initialisation CoffeeScript file. # # @author <NAME> # # (c) University of Surrey 2019 # # Initialise the application object. Based on: # http://brandonhilkert.com/blog/organizing-javascript-in-rails-application-with-turbolinks/ window.VMV ||= {} # # Initialise whenever the page is loaded. # $ -> VMV.init() # # Initialisation for all pages. # VMV.init = -> # Confirm modal dialogue defaults. dataConfirmModal.setDefaults( title: gon.modal_confirm_title commit: gon.modal_confirm_commit cancel: gon.modal_confirm_cancel ) return
true
# # Initialisation CoffeeScript file. # # @author PI:NAME:<NAME>END_PI # # (c) University of Surrey 2019 # # Initialise the application object. Based on: # http://brandonhilkert.com/blog/organizing-javascript-in-rails-application-with-turbolinks/ window.VMV ||= {} # # Initialise whenever the page is loaded. # $ -> VMV.init() # # Initialisation for all pages. # VMV.init = -> # Confirm modal dialogue defaults. dataConfirmModal.setDefaults( title: gon.modal_confirm_title commit: gon.modal_confirm_commit cancel: gon.modal_confirm_cancel ) return
[ { "context": "view Rule to flag unnecessary bind calls\n# @author Bence Dányi <bence@danyi.me>\n###\n'use strict'\n\n#-------------", "end": 78, "score": 0.9998512268066406, "start": 67, "tag": "NAME", "value": "Bence Dányi" }, { "context": "lag unnecessary bind calls\n# @author Bence Dányi <bence@danyi.me>\n###\n'use strict'\n\n#-----------------------------", "end": 94, "score": 0.9999312162399292, "start": 80, "tag": "EMAIL", "value": "bence@danyi.me" } ]
src/rules/no-extra-bind.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Rule to flag unnecessary bind calls # @author Bence Dányi <bence@danyi.me> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow unnecessary calls to `.bind()`' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/no-extra-bind' schema: [] fixable: 'code' messages: unexpected: 'The function binding is unnecessary.' create: (context) -> scopeInfo = null ###* # Reports a given function node. # # @param {ASTNode} node - A node to report. This is a FunctionExpression or # an ArrowFunctionExpression. # @returns {void} ### report = (node) -> context.report node: node.parent.parent messageId: 'unexpected' loc: node.parent.property.loc.start fix: (fixer) -> firstTokenToRemove = context .getSourceCode() .getFirstTokenBetween( node.parent.object node.parent.property astUtils.isNotClosingParenToken ) fixer.removeRange [ firstTokenToRemove.range[0] node.parent.parent.range[1] ] ###* # Checks whether or not a given function node is the callee of `.bind()` # method. # # e.g. `(function() {}.bind(foo))` # # @param {ASTNode} node - A node to report. This is a FunctionExpression or # an ArrowFunctionExpression. # @returns {boolean} `true` if the node is the callee of `.bind()` method. ### isCalleeOfBindMethod = (node) -> {parent} = node grandparent = parent.parent grandparent and grandparent.type is 'CallExpression' and grandparent.callee is parent and grandparent.arguments.length is 1 and parent.type is 'MemberExpression' and parent.object is node and astUtils.getStaticPropertyName(parent) is 'bind' ###* # Adds a scope information object to the stack. # # @param {ASTNode} node - A node to add. This node is a FunctionExpression # or a FunctionDeclaration node. # @returns {void} ### enterFunction = (node) -> scopeInfo = isBound: isCalleeOfBindMethod node thisFound: no upper: scopeInfo ###* # Reports a given arrow function if the function is callee of `.bind()` # method. # # @param {ASTNode} node - A node to report. This node is an # ArrowFunctionExpression. # @returns {void} ### exitArrowFunction = (node) -> if isCalleeOfBindMethod node then report node ###* # Removes the scope information object from the top of the stack. # At the same time, this reports the function node if the function has # `.bind()` and the `this` keywords found. # # @param {ASTNode} node - A node to remove. This node is a # FunctionExpression or a FunctionDeclaration node. # @returns {void} ### exitFunction = (node) -> return exitArrowFunction node if node.bound if scopeInfo.isBound and not scopeInfo.thisFound then report node scopeInfo ###:### = scopeInfo.upper ###* # Set the mark as the `this` keyword was found in this scope. # # @returns {void} ### markAsThisFound = -> if scopeInfo then scopeInfo.thisFound = yes 'ArrowFunctionExpression:exit': exitArrowFunction FunctionDeclaration: enterFunction 'FunctionDeclaration:exit': exitFunction FunctionExpression: enterFunction 'FunctionExpression:exit': exitFunction ThisExpression: markAsThisFound
15963
###* # @fileoverview Rule to flag unnecessary bind calls # @author <NAME> <<EMAIL>> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow unnecessary calls to `.bind()`' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/no-extra-bind' schema: [] fixable: 'code' messages: unexpected: 'The function binding is unnecessary.' create: (context) -> scopeInfo = null ###* # Reports a given function node. # # @param {ASTNode} node - A node to report. This is a FunctionExpression or # an ArrowFunctionExpression. # @returns {void} ### report = (node) -> context.report node: node.parent.parent messageId: 'unexpected' loc: node.parent.property.loc.start fix: (fixer) -> firstTokenToRemove = context .getSourceCode() .getFirstTokenBetween( node.parent.object node.parent.property astUtils.isNotClosingParenToken ) fixer.removeRange [ firstTokenToRemove.range[0] node.parent.parent.range[1] ] ###* # Checks whether or not a given function node is the callee of `.bind()` # method. # # e.g. `(function() {}.bind(foo))` # # @param {ASTNode} node - A node to report. This is a FunctionExpression or # an ArrowFunctionExpression. # @returns {boolean} `true` if the node is the callee of `.bind()` method. ### isCalleeOfBindMethod = (node) -> {parent} = node grandparent = parent.parent grandparent and grandparent.type is 'CallExpression' and grandparent.callee is parent and grandparent.arguments.length is 1 and parent.type is 'MemberExpression' and parent.object is node and astUtils.getStaticPropertyName(parent) is 'bind' ###* # Adds a scope information object to the stack. # # @param {ASTNode} node - A node to add. This node is a FunctionExpression # or a FunctionDeclaration node. # @returns {void} ### enterFunction = (node) -> scopeInfo = isBound: isCalleeOfBindMethod node thisFound: no upper: scopeInfo ###* # Reports a given arrow function if the function is callee of `.bind()` # method. # # @param {ASTNode} node - A node to report. This node is an # ArrowFunctionExpression. # @returns {void} ### exitArrowFunction = (node) -> if isCalleeOfBindMethod node then report node ###* # Removes the scope information object from the top of the stack. # At the same time, this reports the function node if the function has # `.bind()` and the `this` keywords found. # # @param {ASTNode} node - A node to remove. This node is a # FunctionExpression or a FunctionDeclaration node. # @returns {void} ### exitFunction = (node) -> return exitArrowFunction node if node.bound if scopeInfo.isBound and not scopeInfo.thisFound then report node scopeInfo ###:### = scopeInfo.upper ###* # Set the mark as the `this` keyword was found in this scope. # # @returns {void} ### markAsThisFound = -> if scopeInfo then scopeInfo.thisFound = yes 'ArrowFunctionExpression:exit': exitArrowFunction FunctionDeclaration: enterFunction 'FunctionDeclaration:exit': exitFunction FunctionExpression: enterFunction 'FunctionExpression:exit': exitFunction ThisExpression: markAsThisFound
true
###* # @fileoverview Rule to flag unnecessary bind calls # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow unnecessary calls to `.bind()`' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/no-extra-bind' schema: [] fixable: 'code' messages: unexpected: 'The function binding is unnecessary.' create: (context) -> scopeInfo = null ###* # Reports a given function node. # # @param {ASTNode} node - A node to report. This is a FunctionExpression or # an ArrowFunctionExpression. # @returns {void} ### report = (node) -> context.report node: node.parent.parent messageId: 'unexpected' loc: node.parent.property.loc.start fix: (fixer) -> firstTokenToRemove = context .getSourceCode() .getFirstTokenBetween( node.parent.object node.parent.property astUtils.isNotClosingParenToken ) fixer.removeRange [ firstTokenToRemove.range[0] node.parent.parent.range[1] ] ###* # Checks whether or not a given function node is the callee of `.bind()` # method. # # e.g. `(function() {}.bind(foo))` # # @param {ASTNode} node - A node to report. This is a FunctionExpression or # an ArrowFunctionExpression. # @returns {boolean} `true` if the node is the callee of `.bind()` method. ### isCalleeOfBindMethod = (node) -> {parent} = node grandparent = parent.parent grandparent and grandparent.type is 'CallExpression' and grandparent.callee is parent and grandparent.arguments.length is 1 and parent.type is 'MemberExpression' and parent.object is node and astUtils.getStaticPropertyName(parent) is 'bind' ###* # Adds a scope information object to the stack. # # @param {ASTNode} node - A node to add. This node is a FunctionExpression # or a FunctionDeclaration node. # @returns {void} ### enterFunction = (node) -> scopeInfo = isBound: isCalleeOfBindMethod node thisFound: no upper: scopeInfo ###* # Reports a given arrow function if the function is callee of `.bind()` # method. # # @param {ASTNode} node - A node to report. This node is an # ArrowFunctionExpression. # @returns {void} ### exitArrowFunction = (node) -> if isCalleeOfBindMethod node then report node ###* # Removes the scope information object from the top of the stack. # At the same time, this reports the function node if the function has # `.bind()` and the `this` keywords found. # # @param {ASTNode} node - A node to remove. This node is a # FunctionExpression or a FunctionDeclaration node. # @returns {void} ### exitFunction = (node) -> return exitArrowFunction node if node.bound if scopeInfo.isBound and not scopeInfo.thisFound then report node scopeInfo ###:### = scopeInfo.upper ###* # Set the mark as the `this` keyword was found in this scope. # # @returns {void} ### markAsThisFound = -> if scopeInfo then scopeInfo.thisFound = yes 'ArrowFunctionExpression:exit': exitArrowFunction FunctionDeclaration: enterFunction 'FunctionDeclaration:exit': exitFunction FunctionExpression: enterFunction 'FunctionExpression:exit': exitFunction ThisExpression: markAsThisFound
[ { "context": "#\n# Copyright 2015 Volcra\n#\n# Licensed under the Apache License, Version 2.", "end": 25, "score": 0.9996500015258789, "start": 19, "tag": "NAME", "value": "Volcra" } ]
src/DisableMixin.coffee
volcra/react-foundation
0
# # Copyright 2015 Volcra # # 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. # # A React Mixin for disabled components DisableMixin = propTypes: disabled: React.PropTypes.bool getDisabled: -> if @.props.disabled then 'disabled' else '' module.exports = DisableMixin
151205
# # Copyright 2015 <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. # # A React Mixin for disabled components DisableMixin = propTypes: disabled: React.PropTypes.bool getDisabled: -> if @.props.disabled then 'disabled' else '' module.exports = DisableMixin
true
# # Copyright 2015 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. # # A React Mixin for disabled components DisableMixin = propTypes: disabled: React.PropTypes.bool getDisabled: -> if @.props.disabled then 'disabled' else '' module.exports = DisableMixin
[ { "context": "tion: \"/login\", method: \"POST\", ->\n input id: \"username\", type: \"text\", name: \"username\", 'data-default-t", "end": 165, "score": 0.998191773891449, "start": 157, "tag": "USERNAME", "value": "username" }, { "context": "->\n input id: \"username\", type: \"text\", name: \"username\", 'data-default-text': \"username\"\n br()\n in", "end": 197, "score": 0.9973102807998657, "start": 189, "tag": "USERNAME", "value": "username" }, { "context": ": \"text\", name: \"username\", 'data-default-text': \"username\"\n br()\n input id: \"password\", type: \"passwo", "end": 230, "score": 0.9990040063858032, "start": 222, "tag": "USERNAME", "value": "username" }, { "context": "ername\"\n br()\n input id: \"password\", type: \"password\", name: \"password\", 'data-default-text': \"****\"\n ", "end": 282, "score": 0.9960225224494934, "start": 274, "tag": "PASSWORD", "value": "password" }, { "context": "n: \"/register\", method: \"POST\", ->\n input id: \"username\", type: \"text\", name: \"username\", 'data-default-t", "end": 591, "score": 0.9934654235839844, "start": 583, "tag": "USERNAME", "value": "username" }, { "context": "->\n input id: \"username\", type: \"text\", name: \"username\", 'data-default-text': \"desired username\"\n br(", "end": 623, "score": 0.949903130531311, "start": 615, "tag": "USERNAME", "value": "username" }, { "context": "ername\"\n br()\n input id: \"password\", type: \"password\", name: \"password\", 'data-default-text': \"****\"\n ", "end": 716, "score": 0.9970683455467224, "start": 708, "tag": "PASSWORD", "value": "password" }, { "context": "sword\"\n br()\n input id: \"password2\", type: \"password\", name: \"password2\", 'data-default-text': \"****\"\n", "end": 838, "score": 0.9564161896705627, "start": 830, "tag": "PASSWORD", "value": "password" } ]
templates/login.coffee
jaekwon/YCatalyst
3
exports.template = -> if typeof message != "undefined" p message else p "Login here" form action: "/login", method: "POST", -> input id: "username", type: "text", name: "username", 'data-default-text': "username" br() input id: "password", type: "password", name: "password", 'data-default-text': "****" label " password" br() input type: "submit", value: "login" p -> text "New user?" br() text "Please register if you have an invite code. We're in private alpha!" form action: "/register", method: "POST", -> input id: "username", type: "text", name: "username", 'data-default-text': "desired username" br() input id: "password", type: "password", name: "password", 'data-default-text': "****" label " password" br() input id: "password2", type: "password", name: "password2", 'data-default-text': "****" label " password repeat" br() input id: "email", type: "text", name: "email", 'data-default-text': "email", value: @email or '' br() input id: "invite", type: "text", name: "invite", 'data-default-text': "invite code", value: @invite_code or '' br() input type: "submit", value: "register" p -> text "Forgot your password? " a href: "/password_reset", -> "Reset it!" exports.sass = """ #username, #password, #password2, #email, #invite :width 200px """ exports.coffeescript = -> $(document).ready -> $('input[data-default-text]').set_default_text()
54337
exports.template = -> if typeof message != "undefined" p message else p "Login here" form action: "/login", method: "POST", -> input id: "username", type: "text", name: "username", 'data-default-text': "username" br() input id: "password", type: "<PASSWORD>", name: "password", 'data-default-text': "****" label " password" br() input type: "submit", value: "login" p -> text "New user?" br() text "Please register if you have an invite code. We're in private alpha!" form action: "/register", method: "POST", -> input id: "username", type: "text", name: "username", 'data-default-text': "desired username" br() input id: "password", type: "<PASSWORD>", name: "password", 'data-default-text': "****" label " password" br() input id: "password2", type: "<PASSWORD>", name: "password2", 'data-default-text': "****" label " password repeat" br() input id: "email", type: "text", name: "email", 'data-default-text': "email", value: @email or '' br() input id: "invite", type: "text", name: "invite", 'data-default-text': "invite code", value: @invite_code or '' br() input type: "submit", value: "register" p -> text "Forgot your password? " a href: "/password_reset", -> "Reset it!" exports.sass = """ #username, #password, #password2, #email, #invite :width 200px """ exports.coffeescript = -> $(document).ready -> $('input[data-default-text]').set_default_text()
true
exports.template = -> if typeof message != "undefined" p message else p "Login here" form action: "/login", method: "POST", -> input id: "username", type: "text", name: "username", 'data-default-text': "username" br() input id: "password", type: "PI:PASSWORD:<PASSWORD>END_PI", name: "password", 'data-default-text': "****" label " password" br() input type: "submit", value: "login" p -> text "New user?" br() text "Please register if you have an invite code. We're in private alpha!" form action: "/register", method: "POST", -> input id: "username", type: "text", name: "username", 'data-default-text': "desired username" br() input id: "password", type: "PI:PASSWORD:<PASSWORD>END_PI", name: "password", 'data-default-text': "****" label " password" br() input id: "password2", type: "PI:PASSWORD:<PASSWORD>END_PI", name: "password2", 'data-default-text': "****" label " password repeat" br() input id: "email", type: "text", name: "email", 'data-default-text': "email", value: @email or '' br() input id: "invite", type: "text", name: "invite", 'data-default-text': "invite code", value: @invite_code or '' br() input type: "submit", value: "register" p -> text "Forgot your password? " a href: "/password_reset", -> "Reset it!" exports.sass = """ #username, #password, #password2, #email, #invite :width 200px """ exports.coffeescript = -> $(document).ready -> $('input[data-default-text]').set_default_text()
[ { "context": "\n###\n\n (c) 2006 Douglas Crockford\n\n Produce an array of simple token objects from ", "end": 34, "score": 0.9998632073402405, "start": 17, "tag": "NAME", "value": "Douglas Crockford" } ]
src/tokens.coffee
loveencounterflow/tdop
0
### (c) 2006 Douglas Crockford Produce an array of simple token objects from a string. A simple token object contains these members: type: 'name', 'string', 'number', 'operator' value: string or number value of the token from: index of first character of the token to: index of the last character + 1 Comments of the // type are ignored. Operators are by default single characters. Multicharacter operators can be made by supplying a string of prefix and suffix characters. characters. For example, '<>+-&', '=>&:' will match any of these: <= >> >>> <> >= +: -: &: &&: && ### #----------------------------------------------------------------------------------------------------------- String::tokens = (prefix, suffix) -> ### TAINT modifies `String.prototype` ### #--------------------------------------------------------------------------------------------------------- c = undefined # The current character. from = undefined # The index of the start of the token. i = 0 # The index of the current character. length = @length n = undefined # The number value. q = undefined # The quote character. str = undefined # The string value. R = [] # An array to hold the results. #--------------------------------------------------------------------------------------------------------- make = (type, value) -> # Make a token object. type: type value: value from: from to: i #--------------------------------------------------------------------------------------------------------- # Begin tokenization. If the source string is empty, return nothing. return unless this # If prefix and suffix strings are not provided, supply defaults. prefix = '<>+-&' if typeof prefix isnt 'string' suffix = '=>&:' if typeof suffix isnt 'string' # Loop through this text, one character at a time. c = @charAt(i) while c from = i # Ignore whitespace. if c <= ' ' i += 1 c = @charAt(i) # name. else if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') str = c i += 1 loop c = @charAt(i) if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or (c >= '0' and c <= '9') or c is '_' str += c i += 1 else break R.push make('name', str) # number. # A number cannot start with a decimal point. It must start with a digit, # possibly '0'. else if c >= '0' and c <= '9' str = c i += 1 # Look for more digits. loop c = @charAt(i) break if c < '0' or c > '9' i += 1 str += c # Look for a decimal fraction part. if c is '.' i += 1 str += c loop c = @charAt(i) break if c < '0' or c > '9' i += 1 str += c # Look for an exponent part. if c is 'e' or c is 'E' i += 1 str += c c = @charAt(i) if c is '-' or c is '+' i += 1 str += c c = @charAt(i) make('number', str).error 'Bad exponent' if c < '0' or c > '9' loop i += 1 str += c c = @charAt(i) break unless c >= '0' and c <= '9' # Make sure the next character is not a letter. if c >= 'a' and c <= 'z' str += c i += 1 make('number', str).error 'Bad number' # Convert the string value to a number. If it is finite, then it is a good # token. n = +str if isFinite(n) R.push make('number', n) else make('number', str).error 'Bad number' # string else if c is '\'' or c is '"' str = '' q = c i += 1 loop c = @charAt(i) make('string', str).error (if c is '\n' or c is '\r' or c is '' then 'Unterminated string.' else 'Control character in string.'), make('', str) if c < ' ' # Look for the closing quote. break if c is q # Look for escapement. if c is '\\' i += 1 make('string', str).error 'Unterminated string' if i >= length c = @charAt(i) switch c when 'b' c = '\b' when 'f' c = '\f' when 'n' c = '\n' when 'r' c = '\r' when 't' c = '\t' when 'u' make('string', str).error 'Unterminated string' if i >= length c = parseInt(@substr(i + 1, 4), 16) make('string', str).error 'Unterminated string' if not isFinite(c) or c < 0 c = String.fromCharCode(c) i += 4 str += c i += 1 i += 1 R.push make('string', str) c = @charAt(i) # comment. else if c is '/' and @charAt(i + 1) is '/' i += 1 loop c = @charAt(i) break if c is '\n' or c is '\r' or c is '' i += 1 # combining else if prefix.indexOf(c) >= 0 str = c i += 1 loop c = @charAt(i) break if i >= length or suffix.indexOf(c) < 0 str += c i += 1 R.push make('operator', str) # single-character operator else i += 1 R.push make('operator', c) c = @charAt(i) return R
122560
### (c) 2006 <NAME> Produce an array of simple token objects from a string. A simple token object contains these members: type: 'name', 'string', 'number', 'operator' value: string or number value of the token from: index of first character of the token to: index of the last character + 1 Comments of the // type are ignored. Operators are by default single characters. Multicharacter operators can be made by supplying a string of prefix and suffix characters. characters. For example, '<>+-&', '=>&:' will match any of these: <= >> >>> <> >= +: -: &: &&: && ### #----------------------------------------------------------------------------------------------------------- String::tokens = (prefix, suffix) -> ### TAINT modifies `String.prototype` ### #--------------------------------------------------------------------------------------------------------- c = undefined # The current character. from = undefined # The index of the start of the token. i = 0 # The index of the current character. length = @length n = undefined # The number value. q = undefined # The quote character. str = undefined # The string value. R = [] # An array to hold the results. #--------------------------------------------------------------------------------------------------------- make = (type, value) -> # Make a token object. type: type value: value from: from to: i #--------------------------------------------------------------------------------------------------------- # Begin tokenization. If the source string is empty, return nothing. return unless this # If prefix and suffix strings are not provided, supply defaults. prefix = '<>+-&' if typeof prefix isnt 'string' suffix = '=>&:' if typeof suffix isnt 'string' # Loop through this text, one character at a time. c = @charAt(i) while c from = i # Ignore whitespace. if c <= ' ' i += 1 c = @charAt(i) # name. else if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') str = c i += 1 loop c = @charAt(i) if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or (c >= '0' and c <= '9') or c is '_' str += c i += 1 else break R.push make('name', str) # number. # A number cannot start with a decimal point. It must start with a digit, # possibly '0'. else if c >= '0' and c <= '9' str = c i += 1 # Look for more digits. loop c = @charAt(i) break if c < '0' or c > '9' i += 1 str += c # Look for a decimal fraction part. if c is '.' i += 1 str += c loop c = @charAt(i) break if c < '0' or c > '9' i += 1 str += c # Look for an exponent part. if c is 'e' or c is 'E' i += 1 str += c c = @charAt(i) if c is '-' or c is '+' i += 1 str += c c = @charAt(i) make('number', str).error 'Bad exponent' if c < '0' or c > '9' loop i += 1 str += c c = @charAt(i) break unless c >= '0' and c <= '9' # Make sure the next character is not a letter. if c >= 'a' and c <= 'z' str += c i += 1 make('number', str).error 'Bad number' # Convert the string value to a number. If it is finite, then it is a good # token. n = +str if isFinite(n) R.push make('number', n) else make('number', str).error 'Bad number' # string else if c is '\'' or c is '"' str = '' q = c i += 1 loop c = @charAt(i) make('string', str).error (if c is '\n' or c is '\r' or c is '' then 'Unterminated string.' else 'Control character in string.'), make('', str) if c < ' ' # Look for the closing quote. break if c is q # Look for escapement. if c is '\\' i += 1 make('string', str).error 'Unterminated string' if i >= length c = @charAt(i) switch c when 'b' c = '\b' when 'f' c = '\f' when 'n' c = '\n' when 'r' c = '\r' when 't' c = '\t' when 'u' make('string', str).error 'Unterminated string' if i >= length c = parseInt(@substr(i + 1, 4), 16) make('string', str).error 'Unterminated string' if not isFinite(c) or c < 0 c = String.fromCharCode(c) i += 4 str += c i += 1 i += 1 R.push make('string', str) c = @charAt(i) # comment. else if c is '/' and @charAt(i + 1) is '/' i += 1 loop c = @charAt(i) break if c is '\n' or c is '\r' or c is '' i += 1 # combining else if prefix.indexOf(c) >= 0 str = c i += 1 loop c = @charAt(i) break if i >= length or suffix.indexOf(c) < 0 str += c i += 1 R.push make('operator', str) # single-character operator else i += 1 R.push make('operator', c) c = @charAt(i) return R
true
### (c) 2006 PI:NAME:<NAME>END_PI Produce an array of simple token objects from a string. A simple token object contains these members: type: 'name', 'string', 'number', 'operator' value: string or number value of the token from: index of first character of the token to: index of the last character + 1 Comments of the // type are ignored. Operators are by default single characters. Multicharacter operators can be made by supplying a string of prefix and suffix characters. characters. For example, '<>+-&', '=>&:' will match any of these: <= >> >>> <> >= +: -: &: &&: && ### #----------------------------------------------------------------------------------------------------------- String::tokens = (prefix, suffix) -> ### TAINT modifies `String.prototype` ### #--------------------------------------------------------------------------------------------------------- c = undefined # The current character. from = undefined # The index of the start of the token. i = 0 # The index of the current character. length = @length n = undefined # The number value. q = undefined # The quote character. str = undefined # The string value. R = [] # An array to hold the results. #--------------------------------------------------------------------------------------------------------- make = (type, value) -> # Make a token object. type: type value: value from: from to: i #--------------------------------------------------------------------------------------------------------- # Begin tokenization. If the source string is empty, return nothing. return unless this # If prefix and suffix strings are not provided, supply defaults. prefix = '<>+-&' if typeof prefix isnt 'string' suffix = '=>&:' if typeof suffix isnt 'string' # Loop through this text, one character at a time. c = @charAt(i) while c from = i # Ignore whitespace. if c <= ' ' i += 1 c = @charAt(i) # name. else if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') str = c i += 1 loop c = @charAt(i) if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or (c >= '0' and c <= '9') or c is '_' str += c i += 1 else break R.push make('name', str) # number. # A number cannot start with a decimal point. It must start with a digit, # possibly '0'. else if c >= '0' and c <= '9' str = c i += 1 # Look for more digits. loop c = @charAt(i) break if c < '0' or c > '9' i += 1 str += c # Look for a decimal fraction part. if c is '.' i += 1 str += c loop c = @charAt(i) break if c < '0' or c > '9' i += 1 str += c # Look for an exponent part. if c is 'e' or c is 'E' i += 1 str += c c = @charAt(i) if c is '-' or c is '+' i += 1 str += c c = @charAt(i) make('number', str).error 'Bad exponent' if c < '0' or c > '9' loop i += 1 str += c c = @charAt(i) break unless c >= '0' and c <= '9' # Make sure the next character is not a letter. if c >= 'a' and c <= 'z' str += c i += 1 make('number', str).error 'Bad number' # Convert the string value to a number. If it is finite, then it is a good # token. n = +str if isFinite(n) R.push make('number', n) else make('number', str).error 'Bad number' # string else if c is '\'' or c is '"' str = '' q = c i += 1 loop c = @charAt(i) make('string', str).error (if c is '\n' or c is '\r' or c is '' then 'Unterminated string.' else 'Control character in string.'), make('', str) if c < ' ' # Look for the closing quote. break if c is q # Look for escapement. if c is '\\' i += 1 make('string', str).error 'Unterminated string' if i >= length c = @charAt(i) switch c when 'b' c = '\b' when 'f' c = '\f' when 'n' c = '\n' when 'r' c = '\r' when 't' c = '\t' when 'u' make('string', str).error 'Unterminated string' if i >= length c = parseInt(@substr(i + 1, 4), 16) make('string', str).error 'Unterminated string' if not isFinite(c) or c < 0 c = String.fromCharCode(c) i += 4 str += c i += 1 i += 1 R.push make('string', str) c = @charAt(i) # comment. else if c is '/' and @charAt(i + 1) is '/' i += 1 loop c = @charAt(i) break if c is '\n' or c is '\r' or c is '' i += 1 # combining else if prefix.indexOf(c) >= 0 str = c i += 1 loop c = @charAt(i) break if i >= length or suffix.indexOf(c) < 0 str += c i += 1 R.push make('operator', str) # single-character operator else i += 1 R.push make('operator', c) c = @charAt(i) return R
[ { "context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L", "end": 35, "score": 0.9998748898506165, "start": 21, "tag": "NAME", "value": "JeongHoon Byun" }, { "context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# Licensed under ", "end": 49, "score": 0.9825436472892761, "start": 41, "tag": "USERNAME", "value": "Outsider" }, { "context": " repository:\n name: \"test\"\n owner: \"mockrepo\"\n\n urls = timeline.getCommitUrls fixture\n u", "end": 793, "score": 0.9586567878723145, "start": 785, "tag": "USERNAME", "value": "mockrepo" } ]
test/timeline.test.coffee
uppalapatisujitha/CodingConventionofCommitHistory
421
# Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> should = require 'should' fs = require 'fs' timeline = require '../src/timeline' describe 'timeline >', -> timelineFixture = '' before -> timelineFixture = fs.readFileSync "#{__dirname}/fixture/timelineFixture.json", 'utf8' it 'generating blob urls from timeline json', -> urls = timeline.getCommitUrls timelineFixture urls.length.should.equal 2 it 'check commits urls', -> fixture = payload: shas: [ ["dff0c78f5af1d1bb38ac07363ea881f0df0f7535", true] ["0649e5e9d2f71c96517bca1b582c706e665bca6a", true] ] repository: name: "test" owner: "mockrepo" urls = timeline.getCommitUrls fixture urls[0].should.equal "/repos/mockrepo/test/commits/dff0c78f5af1d1bb38ac07363ea881f0df0f7535" it 'should get commit info', (done) -> timeline.getCommitInfo "/repos/outsideris/curlybrace/commits/29321fd1ec6a83af4813d7dee76a348e1fe034ed", (err, commits) -> should.not.exist err commits.sha.should.equal "29321fd1ec6a83af4813d7dee76a348e1fe034ed" done()
81697
# Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> should = require 'should' fs = require 'fs' timeline = require '../src/timeline' describe 'timeline >', -> timelineFixture = '' before -> timelineFixture = fs.readFileSync "#{__dirname}/fixture/timelineFixture.json", 'utf8' it 'generating blob urls from timeline json', -> urls = timeline.getCommitUrls timelineFixture urls.length.should.equal 2 it 'check commits urls', -> fixture = payload: shas: [ ["dff0c78f5af1d1bb38ac07363ea881f0df0f7535", true] ["0649e5e9d2f71c96517bca1b582c706e665bca6a", true] ] repository: name: "test" owner: "mockrepo" urls = timeline.getCommitUrls fixture urls[0].should.equal "/repos/mockrepo/test/commits/dff0c78f5af1d1bb38ac07363ea881f0df0f7535" it 'should get commit info', (done) -> timeline.getCommitInfo "/repos/outsideris/curlybrace/commits/29321fd1ec6a83af4813d7dee76a348e1fe034ed", (err, commits) -> should.not.exist err commits.sha.should.equal "29321fd1ec6a83af4813d7dee76a348e1fe034ed" done()
true
# Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> should = require 'should' fs = require 'fs' timeline = require '../src/timeline' describe 'timeline >', -> timelineFixture = '' before -> timelineFixture = fs.readFileSync "#{__dirname}/fixture/timelineFixture.json", 'utf8' it 'generating blob urls from timeline json', -> urls = timeline.getCommitUrls timelineFixture urls.length.should.equal 2 it 'check commits urls', -> fixture = payload: shas: [ ["dff0c78f5af1d1bb38ac07363ea881f0df0f7535", true] ["0649e5e9d2f71c96517bca1b582c706e665bca6a", true] ] repository: name: "test" owner: "mockrepo" urls = timeline.getCommitUrls fixture urls[0].should.equal "/repos/mockrepo/test/commits/dff0c78f5af1d1bb38ac07363ea881f0df0f7535" it 'should get commit info', (done) -> timeline.getCommitInfo "/repos/outsideris/curlybrace/commits/29321fd1ec6a83af4813d7dee76a348e1fe034ed", (err, commits) -> should.not.exist err commits.sha.should.equal "29321fd1ec6a83af4813d7dee76a348e1fe034ed" done()
[ { "context": " been helped along thanks to the fine work of'\n 'Eric Meyer http://meyerweb.com/eric/tools/css/reset/index.ht", "end": 894, "score": 0.9992694854736328, "start": 884, "tag": "NAME", "value": "Eric Meyer" }, { "context": "com/eric/tools/css/reset/index.html'\n 'along with Nicolas Gallagher and Jonathan Neal http://necolas.github.com/norma", "end": 979, "score": 0.9998153448104858, "start": 962, "tag": "NAME", "value": "Nicolas Gallagher" }, { "context": "et/index.html'\n 'along with Nicolas Gallagher and Jonathan Neal http://necolas.github.com/normalize.css/'\n 'and ", "end": 997, "score": 0.9998196363449097, "start": 984, "tag": "NAME", "value": "Jonathan Neal" } ]
gulp/tasks/style.coffee
tanshio/webpack-react-starter
0
gulp = require "gulp" gulpif = require "gulp-if" $ = require("gulp-load-plugins")() config = require "../../config/config.json" browserSync = require "browser-Sync" cssbanner = ['/*' 'Theme Name: <%= config.wp.title %>' 'Theme URI: <%= config.wp.homepage %>' 'Author: <%= config.wp.author.name %>' 'Author URI: <%= config.wp.author.url %>' 'Description: <%= config.wp.description %>' 'Version: <%= config.wp.version %>' 'License: GNU General Public License v2 or later' 'License URI: http://www.gnu.org/licenses/gpl-2.0.html' 'Text Domain: <%= config.wp.author.name %>' 'Tags:' '' 'This theme, like WordPress, is licensed under the GPL.' 'Use it to make something cool, have fun, and share what you\'ve learned with others.' '' 'Resetting and rebuilding styles have been helped along thanks to the fine work of' 'Eric Meyer http://meyerweb.com/eric/tools/css/reset/index.html' 'along with Nicolas Gallagher and Jonathan Neal http://necolas.github.com/normalize.css/' 'and Blueprint http://www.blueprintcss.org/' '*/'].join('\n') # SCSS # lissass gulp.task 'scss', -> gulp.src(config.scss.src+"style.scss") .pipe $.plumber errorHandler: $.notify.onError "<%= error.message %>" .pipe($.sass({ includePaths: require('node-neat').includePaths })) .pipe $.pleeease( "autoprefixer": { "browsers": ["ie 9"] }, "rem": false, ) .pipe gulp.dest config.scss.dist .on "end" , browserSync.stream # stylus gulp.task "stylus", -> gulp.src config.stylus.app+"stylus/style.styl" .pipe $.plumber errorHandler: $.notify.onError "<%= error.message %>" .pipe $.stylus compress: true .pipe $.pleeease "autoprefixer": { "browsers": ["ie 9"] }, "rem": false, .pipe gulp.dest config.stylus.dist+"style" .on 'end' , browserSync.stream
34288
gulp = require "gulp" gulpif = require "gulp-if" $ = require("gulp-load-plugins")() config = require "../../config/config.json" browserSync = require "browser-Sync" cssbanner = ['/*' 'Theme Name: <%= config.wp.title %>' 'Theme URI: <%= config.wp.homepage %>' 'Author: <%= config.wp.author.name %>' 'Author URI: <%= config.wp.author.url %>' 'Description: <%= config.wp.description %>' 'Version: <%= config.wp.version %>' 'License: GNU General Public License v2 or later' 'License URI: http://www.gnu.org/licenses/gpl-2.0.html' 'Text Domain: <%= config.wp.author.name %>' 'Tags:' '' 'This theme, like WordPress, is licensed under the GPL.' 'Use it to make something cool, have fun, and share what you\'ve learned with others.' '' 'Resetting and rebuilding styles have been helped along thanks to the fine work of' '<NAME> http://meyerweb.com/eric/tools/css/reset/index.html' 'along with <NAME> and <NAME> http://necolas.github.com/normalize.css/' 'and Blueprint http://www.blueprintcss.org/' '*/'].join('\n') # SCSS # lissass gulp.task 'scss', -> gulp.src(config.scss.src+"style.scss") .pipe $.plumber errorHandler: $.notify.onError "<%= error.message %>" .pipe($.sass({ includePaths: require('node-neat').includePaths })) .pipe $.pleeease( "autoprefixer": { "browsers": ["ie 9"] }, "rem": false, ) .pipe gulp.dest config.scss.dist .on "end" , browserSync.stream # stylus gulp.task "stylus", -> gulp.src config.stylus.app+"stylus/style.styl" .pipe $.plumber errorHandler: $.notify.onError "<%= error.message %>" .pipe $.stylus compress: true .pipe $.pleeease "autoprefixer": { "browsers": ["ie 9"] }, "rem": false, .pipe gulp.dest config.stylus.dist+"style" .on 'end' , browserSync.stream
true
gulp = require "gulp" gulpif = require "gulp-if" $ = require("gulp-load-plugins")() config = require "../../config/config.json" browserSync = require "browser-Sync" cssbanner = ['/*' 'Theme Name: <%= config.wp.title %>' 'Theme URI: <%= config.wp.homepage %>' 'Author: <%= config.wp.author.name %>' 'Author URI: <%= config.wp.author.url %>' 'Description: <%= config.wp.description %>' 'Version: <%= config.wp.version %>' 'License: GNU General Public License v2 or later' 'License URI: http://www.gnu.org/licenses/gpl-2.0.html' 'Text Domain: <%= config.wp.author.name %>' 'Tags:' '' 'This theme, like WordPress, is licensed under the GPL.' 'Use it to make something cool, have fun, and share what you\'ve learned with others.' '' 'Resetting and rebuilding styles have been helped along thanks to the fine work of' 'PI:NAME:<NAME>END_PI http://meyerweb.com/eric/tools/css/reset/index.html' 'along with PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI http://necolas.github.com/normalize.css/' 'and Blueprint http://www.blueprintcss.org/' '*/'].join('\n') # SCSS # lissass gulp.task 'scss', -> gulp.src(config.scss.src+"style.scss") .pipe $.plumber errorHandler: $.notify.onError "<%= error.message %>" .pipe($.sass({ includePaths: require('node-neat').includePaths })) .pipe $.pleeease( "autoprefixer": { "browsers": ["ie 9"] }, "rem": false, ) .pipe gulp.dest config.scss.dist .on "end" , browserSync.stream # stylus gulp.task "stylus", -> gulp.src config.stylus.app+"stylus/style.styl" .pipe $.plumber errorHandler: $.notify.onError "<%= error.message %>" .pipe $.stylus compress: true .pipe $.pleeease "autoprefixer": { "browsers": ["ie 9"] }, "rem": false, .pipe gulp.dest config.stylus.dist+"style" .on 'end' , browserSync.stream
[ { "context": "ync().then ()=>\n @Model.createAsync({name:\"first\", description:\"original\"})\n\n it \"strictFindOne", "end": 686, "score": 0.9669221043586731, "start": 681, "tag": "NAME", "value": "first" }, { "context": ">\n @Model.strictFindOneAsync(\n {name:\"first\"}\n ).done (result)=>\n expect(result.d", "end": 822, "score": 0.9556052684783936, "start": 817, "tag": "NAME", "value": "first" }, { "context": ">\n @Model.strictFindOneAsync(\n {name:\"second\"}\n ).catch (e)=>\n expect(e.errorCode)", "end": 1025, "score": 0.9269868731498718, "start": 1019, "tag": "NAME", "value": "second" } ]
test/unit/strictFindOnePluginSpec.coffee
opentable/spur-mongoosemanager
3
describe "strictFindOnePlugin", -> beforeEach ()-> injector().inject (@strictFindOnePlugin, @MongooseManager, @mongoose, @Promise, @config)=> @MongooseManager.connect(@config.Mongo.ConnectionUrl) afterEach ()-> @MongooseManager.disconnect() it "should exist", -> expect(@strictFindOnePlugin).to.exist describe "db tests", -> beforeEach -> @Schema = new @mongoose.Schema({ name:String description:String }) @Schema.plugin(@strictFindOnePlugin) @Model = @mongoose.model "strict-find-one", @Schema @MongooseManager._promisifyAll() @Model.removeAsync().then ()=> @Model.createAsync({name:"first", description:"original"}) it "strictFindOnePlugin - get existing", (done)-> @Model.strictFindOneAsync( {name:"first"} ).done (result)=> expect(result.description).to.equal "original" done() it "strictFindOnePlugin - not found", (done)-> @Model.strictFindOneAsync( {name:"second"} ).catch (e)=> expect(e.errorCode).to.equal "not_found_error" done()
114547
describe "strictFindOnePlugin", -> beforeEach ()-> injector().inject (@strictFindOnePlugin, @MongooseManager, @mongoose, @Promise, @config)=> @MongooseManager.connect(@config.Mongo.ConnectionUrl) afterEach ()-> @MongooseManager.disconnect() it "should exist", -> expect(@strictFindOnePlugin).to.exist describe "db tests", -> beforeEach -> @Schema = new @mongoose.Schema({ name:String description:String }) @Schema.plugin(@strictFindOnePlugin) @Model = @mongoose.model "strict-find-one", @Schema @MongooseManager._promisifyAll() @Model.removeAsync().then ()=> @Model.createAsync({name:"<NAME>", description:"original"}) it "strictFindOnePlugin - get existing", (done)-> @Model.strictFindOneAsync( {name:"<NAME>"} ).done (result)=> expect(result.description).to.equal "original" done() it "strictFindOnePlugin - not found", (done)-> @Model.strictFindOneAsync( {name:"<NAME>"} ).catch (e)=> expect(e.errorCode).to.equal "not_found_error" done()
true
describe "strictFindOnePlugin", -> beforeEach ()-> injector().inject (@strictFindOnePlugin, @MongooseManager, @mongoose, @Promise, @config)=> @MongooseManager.connect(@config.Mongo.ConnectionUrl) afterEach ()-> @MongooseManager.disconnect() it "should exist", -> expect(@strictFindOnePlugin).to.exist describe "db tests", -> beforeEach -> @Schema = new @mongoose.Schema({ name:String description:String }) @Schema.plugin(@strictFindOnePlugin) @Model = @mongoose.model "strict-find-one", @Schema @MongooseManager._promisifyAll() @Model.removeAsync().then ()=> @Model.createAsync({name:"PI:NAME:<NAME>END_PI", description:"original"}) it "strictFindOnePlugin - get existing", (done)-> @Model.strictFindOneAsync( {name:"PI:NAME:<NAME>END_PI"} ).done (result)=> expect(result.description).to.equal "original" done() it "strictFindOnePlugin - not found", (done)-> @Model.strictFindOneAsync( {name:"PI:NAME:<NAME>END_PI"} ).catch (e)=> expect(e.errorCode).to.equal "not_found_error" done()
[ { "context": "#\n# Copyright 2014 Carsten Klein\n#\n# Licensed under the Apache License, Version 2.", "end": 32, "score": 0.9998639822006226, "start": 19, "tag": "NAME", "value": "Carsten Klein" } ]
src/subclassof.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 always export globally exports = window ? global # guard preventing us from installing twice unless exports.subclassof? _subclassofCoffee = (constructor, base) -> result = false b = constructor.__super__.constructor while true if b == base result = true break if b.__super__ is undefined break b = b.__super__.constructor if not result && b.super_ result = _subclassofNode b, base result _subclassofNode = (constructor, base) -> result = false b = constructor.super_ while true if b == base result = true break if b.__super__ break if b.super_ is undefined break b = b.super_ if not result && b.__super__ result = _subclassofCoffee b, base result exports.subclassof = (constructor, base) -> result = false if 'function' != typeof constructor throw new TypeError 'constructor must be a function.' if 'function' != typeof base throw new TypeError 'base must be a function.' if base == Object # everything is a subclass of Object result = true else if constructor.__super__ result = _subclassofCoffee constructor, base else if constructor.super_ result = _subclassofNode constructor, base result
77062
# # 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 always export globally exports = window ? global # guard preventing us from installing twice unless exports.subclassof? _subclassofCoffee = (constructor, base) -> result = false b = constructor.__super__.constructor while true if b == base result = true break if b.__super__ is undefined break b = b.__super__.constructor if not result && b.super_ result = _subclassofNode b, base result _subclassofNode = (constructor, base) -> result = false b = constructor.super_ while true if b == base result = true break if b.__super__ break if b.super_ is undefined break b = b.super_ if not result && b.__super__ result = _subclassofCoffee b, base result exports.subclassof = (constructor, base) -> result = false if 'function' != typeof constructor throw new TypeError 'constructor must be a function.' if 'function' != typeof base throw new TypeError 'base must be a function.' if base == Object # everything is a subclass of Object result = true else if constructor.__super__ result = _subclassofCoffee constructor, base else if constructor.super_ result = _subclassofNode constructor, base result
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 always export globally exports = window ? global # guard preventing us from installing twice unless exports.subclassof? _subclassofCoffee = (constructor, base) -> result = false b = constructor.__super__.constructor while true if b == base result = true break if b.__super__ is undefined break b = b.__super__.constructor if not result && b.super_ result = _subclassofNode b, base result _subclassofNode = (constructor, base) -> result = false b = constructor.super_ while true if b == base result = true break if b.__super__ break if b.super_ is undefined break b = b.super_ if not result && b.__super__ result = _subclassofCoffee b, base result exports.subclassof = (constructor, base) -> result = false if 'function' != typeof constructor throw new TypeError 'constructor must be a function.' if 'function' != typeof base throw new TypeError 'base must be a function.' if base == Object # everything is a subclass of Object result = true else if constructor.__super__ result = _subclassofCoffee constructor, base else if constructor.super_ result = _subclassofNode constructor, base result
[ { "context": "http://localhost:9991'\n\nusers = [\n {username: 'iago@zulip.com', password: 'JhwLkBydEG1tAL5P'}\n {username", "end": 4092, "score": 0.9999256730079651, "start": 4078, "tag": "EMAIL", "value": "iago@zulip.com" }, { "context": "[\n {username: 'iago@zulip.com', password: 'JhwLkBydEG1tAL5P'}\n {username: 'othello@zulip.com', password: ", "end": 4126, "score": 0.9994353652000427, "start": 4110, "tag": "PASSWORD", "value": "JhwLkBydEG1tAL5P" }, { "context": " password: 'JhwLkBydEG1tAL5P'}\n {username: 'othello@zulip.com', password: 'GX5MTQ+qYSzcmDoH'}\n {username: '", "end": 4162, "score": 0.9999247789382935, "start": 4145, "tag": "EMAIL", "value": "othello@zulip.com" }, { "context": "}\n {username: 'othello@zulip.com', password: 'GX5MTQ+qYSzcmDoH'}\n {username: 'cordelia@zulip.com', password: ", "end": 4193, "score": 0.9994533061981201, "start": 4177, "tag": "PASSWORD", "value": "GX5MTQ+qYSzcmDoH" }, { "context": "', password: 'GX5MTQ+qYSzcmDoH'}\n {username: 'cordelia@zulip.com', password: '+1pkoQiP0wEbEvv/'}\n {username: 'h", "end": 4230, "score": 0.9999265670776367, "start": 4212, "tag": "EMAIL", "value": "cordelia@zulip.com" }, { "context": "H'}\n {username: 'cordelia@zulip.com', password: '+1pkoQiP0wEbEvv/'}\n {username: 'hamlet@zulip.com', password: ", "end": 4259, "score": 0.9994314312934875, "start": 4243, "tag": "PASSWORD", "value": "'+1pkoQiP0wEbEvv" }, { "context": "m', password: '+1pkoQiP0wEbEvv/'}\n {username: 'hamlet@zulip.com', password: 'Z/hx5nEcXRQBGzk3'}\n {username: ", "end": 4295, "score": 0.9999231100082397, "start": 4279, "tag": "EMAIL", "value": "hamlet@zulip.com" }, { "context": "}\n {username: 'hamlet@zulip.com', password: 'Z/hx5nEcXRQBGzk3'}\n {username: 'prospero@zulip.com', password: ", "end": 4327, "score": 0.9994109869003296, "start": 4311, "tag": "PASSWORD", "value": "Z/hx5nEcXRQBGzk3" }, { "context": ", password: 'Z/hx5nEcXRQBGzk3'}\n {username: 'prospero@zulip.com', password: 'j+XqHkQ2cycwCQJE'}\n]\n\nuser_start_ste", "end": 4364, "score": 0.9999239444732666, "start": 4346, "tag": "EMAIL", "value": "prospero@zulip.com" }, { "context": "}\n {username: 'prospero@zulip.com', password: 'j+XqHkQ2cycwCQJE'}\n]\n\nuser_start_step = 1000*1\n\nif argv.users > us", "end": 4394, "score": 0.9994143843650818, "start": 4378, "tag": "PASSWORD", "value": "j+XqHkQ2cycwCQJE" } ]
tools/deprecated/stress-test/stress-test.coffee
enterstudio/zulip
1
{Session, Stat} = require './support' assert = require 'assert' argv = require('optimist').default({ time: 60 users: 5 'min-wait': 5 'max-wait': 10 }).argv class ZulipSession extends Session constructor: (id, host, {@username, @password}) -> user = @username.split('@')[0] super(host, "#{id} #{user}") @last_csrf_token = undefined @page_params = undefined parse_csrf: -> match = @last_body.match /name='csrfmiddlewaretoken' value='([a-zA-Z0-9]+)/ assert match, "Expected CSRF token in form" @last_csrf_token = match[1] @headers['X-CSRFToken'] = @last_csrf_token parse_page_params: -> match = @last_body.match /^var page_params = (.*);$/m assert match, "Expected page_params" @page_params = JSON.parse match[1] {@max_message_id, @event_queue_id} = @page_params @pointer = @page_params.initial_pointer @last_event_id = -1 login: (cb) -> @get '/', => #@get_all(@static) @parse_csrf() @post '/accounts/login/?next=', {@username, @password}, => @on_app_load(cb) on_app_load: (cb) -> #@get_all(@app_static) @parse_csrf() @parse_page_params() @update_active_status() @get '/json/bots' @post '/json/get_old_messages', { anchor: @pointer num_before: 200 num_after: 200 }, get_old_messages_time.cbTimer cb reload: (cb) -> @get '/', => @on_app_load(cb) get_events: -> @post '/json/get_events', { @pointer last: @max_message_id dont_block: false queue_id: @event_queue_id @last_event_id }, (r, body) => response = JSON.parse(body) for event in response.events @last_event_id = Math.max(@last_event_id, event.id) if event.type == 'message' @on_message(event.message) @get_events() on_message: (message) -> if (m = message.content.match /Test message sent at (\d+)/) message_latency.update(+new Date() - parseInt(m[1], 10)) update_active_status: -> @post "/json/update_active_status", {status: "active"}, update_status_time.cbTimer() send_stream_message: (stream, subject, content) -> @post '/json/send_message', { client: 'website' type: 'stream' to: JSON.stringify([stream]) stream subject content }, message_send_time.cbTimer() send_private_message: (recipients, content) -> @post '/json/send_message', { client: 'website' type: 'private' to: JSON.stringify(recipients) reply_to: recipients.join(', ') private_message_recipient: recipients.join(', ') content }, message_send_time.cbTimer() random_sends: => s = Math.round(Math.random()*5) msg = "Test message sent at #{+new Date()}" @send_stream_message("test", "test#{s}", msg) setTimeout(@random_sends, @rand_time()) # TODO: update_message_flags # TODO: get_old_messages run_message_test: => @login => @get_events() setInterval((=> @update_active_status()), 60*1000) @random_sends() run_reload_test: => @login @random_reloads random_reloads: => @reload total_reload_time.cbTimer => setTimeout(@random_reloads, @rand_time()) run_test: => opts = argv @min_wait = opts['min-wait'] @max_wait = opts['max-wait'] switch opts._[0] when 'reload' then @run_reload_test() when 'message' then @run_message_test() else throw new Error("No test selected") rand_time: -> Math.round(1000 * (@min_wait + Math.random() * (@max_wait - @min_wait))) host = 'http://localhost:9991' users = [ {username: 'iago@zulip.com', password: 'JhwLkBydEG1tAL5P'} {username: 'othello@zulip.com', password: 'GX5MTQ+qYSzcmDoH'} {username: 'cordelia@zulip.com', password: '+1pkoQiP0wEbEvv/'} {username: 'hamlet@zulip.com', password: 'Z/hx5nEcXRQBGzk3'} {username: 'prospero@zulip.com', password: 'j+XqHkQ2cycwCQJE'} ] user_start_step = 1000*1 if argv.users > users.length console.log "Only have #{users.length} accounts, so simulating multiple sessions" for i in [0..argv.users] then do -> user = users[i%users.length] h = new ZulipSession(i, host, user) setTimeout(h.run_test, i*user_start_step) stats = [ message_latency = new Stat("Message Latency") message_send_time = new Stat("Message Send Time") update_status_time = new Stat("/json/update_status_time Time") total_reload_time = new Stat("Total reload time") get_old_messages_time = new Stat("/json/get_old_messages Time") ] # Reset message latency stat after everyone logs in # setTimeout(message_latency.reset, (i+1)*user_start_step) showStats = -> for stat in stats when stat.count() > 0 console.log "#{stat.name}:", stat.stats() stat.reset() process.exit() setTimeout(showStats, argv['time']*1000)
98311
{Session, Stat} = require './support' assert = require 'assert' argv = require('optimist').default({ time: 60 users: 5 'min-wait': 5 'max-wait': 10 }).argv class ZulipSession extends Session constructor: (id, host, {@username, @password}) -> user = @username.split('@')[0] super(host, "#{id} #{user}") @last_csrf_token = undefined @page_params = undefined parse_csrf: -> match = @last_body.match /name='csrfmiddlewaretoken' value='([a-zA-Z0-9]+)/ assert match, "Expected CSRF token in form" @last_csrf_token = match[1] @headers['X-CSRFToken'] = @last_csrf_token parse_page_params: -> match = @last_body.match /^var page_params = (.*);$/m assert match, "Expected page_params" @page_params = JSON.parse match[1] {@max_message_id, @event_queue_id} = @page_params @pointer = @page_params.initial_pointer @last_event_id = -1 login: (cb) -> @get '/', => #@get_all(@static) @parse_csrf() @post '/accounts/login/?next=', {@username, @password}, => @on_app_load(cb) on_app_load: (cb) -> #@get_all(@app_static) @parse_csrf() @parse_page_params() @update_active_status() @get '/json/bots' @post '/json/get_old_messages', { anchor: @pointer num_before: 200 num_after: 200 }, get_old_messages_time.cbTimer cb reload: (cb) -> @get '/', => @on_app_load(cb) get_events: -> @post '/json/get_events', { @pointer last: @max_message_id dont_block: false queue_id: @event_queue_id @last_event_id }, (r, body) => response = JSON.parse(body) for event in response.events @last_event_id = Math.max(@last_event_id, event.id) if event.type == 'message' @on_message(event.message) @get_events() on_message: (message) -> if (m = message.content.match /Test message sent at (\d+)/) message_latency.update(+new Date() - parseInt(m[1], 10)) update_active_status: -> @post "/json/update_active_status", {status: "active"}, update_status_time.cbTimer() send_stream_message: (stream, subject, content) -> @post '/json/send_message', { client: 'website' type: 'stream' to: JSON.stringify([stream]) stream subject content }, message_send_time.cbTimer() send_private_message: (recipients, content) -> @post '/json/send_message', { client: 'website' type: 'private' to: JSON.stringify(recipients) reply_to: recipients.join(', ') private_message_recipient: recipients.join(', ') content }, message_send_time.cbTimer() random_sends: => s = Math.round(Math.random()*5) msg = "Test message sent at #{+new Date()}" @send_stream_message("test", "test#{s}", msg) setTimeout(@random_sends, @rand_time()) # TODO: update_message_flags # TODO: get_old_messages run_message_test: => @login => @get_events() setInterval((=> @update_active_status()), 60*1000) @random_sends() run_reload_test: => @login @random_reloads random_reloads: => @reload total_reload_time.cbTimer => setTimeout(@random_reloads, @rand_time()) run_test: => opts = argv @min_wait = opts['min-wait'] @max_wait = opts['max-wait'] switch opts._[0] when 'reload' then @run_reload_test() when 'message' then @run_message_test() else throw new Error("No test selected") rand_time: -> Math.round(1000 * (@min_wait + Math.random() * (@max_wait - @min_wait))) host = 'http://localhost:9991' users = [ {username: '<EMAIL>', password: '<PASSWORD>'} {username: '<EMAIL>', password: '<PASSWORD>'} {username: '<EMAIL>', password: <PASSWORD>/'} {username: '<EMAIL>', password: '<PASSWORD>'} {username: '<EMAIL>', password: '<PASSWORD>'} ] user_start_step = 1000*1 if argv.users > users.length console.log "Only have #{users.length} accounts, so simulating multiple sessions" for i in [0..argv.users] then do -> user = users[i%users.length] h = new ZulipSession(i, host, user) setTimeout(h.run_test, i*user_start_step) stats = [ message_latency = new Stat("Message Latency") message_send_time = new Stat("Message Send Time") update_status_time = new Stat("/json/update_status_time Time") total_reload_time = new Stat("Total reload time") get_old_messages_time = new Stat("/json/get_old_messages Time") ] # Reset message latency stat after everyone logs in # setTimeout(message_latency.reset, (i+1)*user_start_step) showStats = -> for stat in stats when stat.count() > 0 console.log "#{stat.name}:", stat.stats() stat.reset() process.exit() setTimeout(showStats, argv['time']*1000)
true
{Session, Stat} = require './support' assert = require 'assert' argv = require('optimist').default({ time: 60 users: 5 'min-wait': 5 'max-wait': 10 }).argv class ZulipSession extends Session constructor: (id, host, {@username, @password}) -> user = @username.split('@')[0] super(host, "#{id} #{user}") @last_csrf_token = undefined @page_params = undefined parse_csrf: -> match = @last_body.match /name='csrfmiddlewaretoken' value='([a-zA-Z0-9]+)/ assert match, "Expected CSRF token in form" @last_csrf_token = match[1] @headers['X-CSRFToken'] = @last_csrf_token parse_page_params: -> match = @last_body.match /^var page_params = (.*);$/m assert match, "Expected page_params" @page_params = JSON.parse match[1] {@max_message_id, @event_queue_id} = @page_params @pointer = @page_params.initial_pointer @last_event_id = -1 login: (cb) -> @get '/', => #@get_all(@static) @parse_csrf() @post '/accounts/login/?next=', {@username, @password}, => @on_app_load(cb) on_app_load: (cb) -> #@get_all(@app_static) @parse_csrf() @parse_page_params() @update_active_status() @get '/json/bots' @post '/json/get_old_messages', { anchor: @pointer num_before: 200 num_after: 200 }, get_old_messages_time.cbTimer cb reload: (cb) -> @get '/', => @on_app_load(cb) get_events: -> @post '/json/get_events', { @pointer last: @max_message_id dont_block: false queue_id: @event_queue_id @last_event_id }, (r, body) => response = JSON.parse(body) for event in response.events @last_event_id = Math.max(@last_event_id, event.id) if event.type == 'message' @on_message(event.message) @get_events() on_message: (message) -> if (m = message.content.match /Test message sent at (\d+)/) message_latency.update(+new Date() - parseInt(m[1], 10)) update_active_status: -> @post "/json/update_active_status", {status: "active"}, update_status_time.cbTimer() send_stream_message: (stream, subject, content) -> @post '/json/send_message', { client: 'website' type: 'stream' to: JSON.stringify([stream]) stream subject content }, message_send_time.cbTimer() send_private_message: (recipients, content) -> @post '/json/send_message', { client: 'website' type: 'private' to: JSON.stringify(recipients) reply_to: recipients.join(', ') private_message_recipient: recipients.join(', ') content }, message_send_time.cbTimer() random_sends: => s = Math.round(Math.random()*5) msg = "Test message sent at #{+new Date()}" @send_stream_message("test", "test#{s}", msg) setTimeout(@random_sends, @rand_time()) # TODO: update_message_flags # TODO: get_old_messages run_message_test: => @login => @get_events() setInterval((=> @update_active_status()), 60*1000) @random_sends() run_reload_test: => @login @random_reloads random_reloads: => @reload total_reload_time.cbTimer => setTimeout(@random_reloads, @rand_time()) run_test: => opts = argv @min_wait = opts['min-wait'] @max_wait = opts['max-wait'] switch opts._[0] when 'reload' then @run_reload_test() when 'message' then @run_message_test() else throw new Error("No test selected") rand_time: -> Math.round(1000 * (@min_wait + Math.random() * (@max_wait - @min_wait))) host = 'http://localhost:9991' users = [ {username: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'} {username: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'} {username: 'PI:EMAIL:<EMAIL>END_PI', password: PI:PASSWORD:<PASSWORD>END_PI/'} {username: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'} {username: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'} ] user_start_step = 1000*1 if argv.users > users.length console.log "Only have #{users.length} accounts, so simulating multiple sessions" for i in [0..argv.users] then do -> user = users[i%users.length] h = new ZulipSession(i, host, user) setTimeout(h.run_test, i*user_start_step) stats = [ message_latency = new Stat("Message Latency") message_send_time = new Stat("Message Send Time") update_status_time = new Stat("/json/update_status_time Time") total_reload_time = new Stat("Total reload time") get_old_messages_time = new Stat("/json/get_old_messages Time") ] # Reset message latency stat after everyone logs in # setTimeout(message_latency.reset, (i+1)*user_start_step) showStats = -> for stat in stats when stat.count() > 0 console.log "#{stat.name}:", stat.stats() stat.reset() process.exit() setTimeout(showStats, argv['time']*1000)
[ { "context": "(\"url_or_guid\").text()\n\n mail\n from: \"no-reply@test.com\"\n to: guid\n subject: @title\n ", "end": 4208, "score": 0.9998596906661987, "start": 4191, "tag": "EMAIL", "value": "no-reply@test.com" } ]
src/server/litmus-client.coffee
groupon/gleemail
89
### Copyright (c) 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### request = require "request" mail = require("nodemailer").mail cheerio = require "cheerio" _ = require "underscore" module.exports = class Litmus constructor: (options) -> @html = options.html @title = options.title @baseUrl = options.url @clients = options.clients @auth = user: options.username pass: options.password run: (cb) -> @litmusId (err, id) => return cb(err) if err if id @updateTest id, cb else @createTest cb litmusId: (cb) -> opts = auth: @auth url: "#{@baseUrl}/tests.xml" request.get opts, (err, res, body) -> return cb(err) if err try id = null $ = cheerio.load body, xmlMode: true title = @title $name = $("name").filter -> $nameTag = $(this) $nameTag.text() == title id = $matchedName.parent().children("id").text() if $name.length cb(null, id) catch e cb(e) parseStatus: (body) -> $ = cheerio.load body, xmlMode: true statuses = $("status") delayed = [] unavailable = [] seconds = 0 avgTimes = $("average_time_to_process") avgTimes.each (i, el) -> seconds += parseInt($(this).text(), 10) seconds = Math.round(seconds / avgTimes.length) statuses.each (i, el) -> $this = $(this) statusCode = parseInt($this.text(), 10) appName = $this.parent().children("application_long_name").text() switch statusCode when 1 delayed.push(appName) when 2 unavailable.push(appName) time: seconds delayed: delayed unavailable: unavailable createTest: (cb) -> opts = auth: @auth headers: "Content-type": "application/xml" "Accept": "application/xml" body: @xml() url: "#{@baseUrl}/emails.xml" request.post opts, (err, res, body) => return cb(err) if err try status = res.headers.status unless /^2/.test status return cb(status) status = @parseStatus body cb(null, status) catch e cb(e) updateTest: (id, cb) -> opts = auth: @auth headers: "Content-type": "application/xml" "Accept": "application/xml" body: @xml() url: "#{@baseUrl}/tests/#{id}/versions.xml" request.post opts, (err, res, body) => return cb(err) if err @mailNewVersion body, (err) => return cb(err) if err try status = @parseStatus body cb(null, status) catch e cb(e) mailNewVersion: (body, cb) -> try $ = cheerio.load(body) guid = $("url_or_guid").text() mail from: "no-reply@test.com" to: guid subject: @title text: "" html: @html cb() catch e cb(e) xml: -> xml = """ <?xml version="1.0"?> <test_set> <save_defaults>false</save_defaults> <use_defaults>false</use_defaults> <email_source> <body> <![CDATA[#{@html}]]> </body> <subject>#{@title}</subject> </email_source> <applications type="array"> """ for client in @clients xml += """ <application> <code>#{client}</code> </application> """ xml += """ </applications> </test_set> """ xml
171744
### Copyright (c) 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### request = require "request" mail = require("nodemailer").mail cheerio = require "cheerio" _ = require "underscore" module.exports = class Litmus constructor: (options) -> @html = options.html @title = options.title @baseUrl = options.url @clients = options.clients @auth = user: options.username pass: options.password run: (cb) -> @litmusId (err, id) => return cb(err) if err if id @updateTest id, cb else @createTest cb litmusId: (cb) -> opts = auth: @auth url: "#{@baseUrl}/tests.xml" request.get opts, (err, res, body) -> return cb(err) if err try id = null $ = cheerio.load body, xmlMode: true title = @title $name = $("name").filter -> $nameTag = $(this) $nameTag.text() == title id = $matchedName.parent().children("id").text() if $name.length cb(null, id) catch e cb(e) parseStatus: (body) -> $ = cheerio.load body, xmlMode: true statuses = $("status") delayed = [] unavailable = [] seconds = 0 avgTimes = $("average_time_to_process") avgTimes.each (i, el) -> seconds += parseInt($(this).text(), 10) seconds = Math.round(seconds / avgTimes.length) statuses.each (i, el) -> $this = $(this) statusCode = parseInt($this.text(), 10) appName = $this.parent().children("application_long_name").text() switch statusCode when 1 delayed.push(appName) when 2 unavailable.push(appName) time: seconds delayed: delayed unavailable: unavailable createTest: (cb) -> opts = auth: @auth headers: "Content-type": "application/xml" "Accept": "application/xml" body: @xml() url: "#{@baseUrl}/emails.xml" request.post opts, (err, res, body) => return cb(err) if err try status = res.headers.status unless /^2/.test status return cb(status) status = @parseStatus body cb(null, status) catch e cb(e) updateTest: (id, cb) -> opts = auth: @auth headers: "Content-type": "application/xml" "Accept": "application/xml" body: @xml() url: "#{@baseUrl}/tests/#{id}/versions.xml" request.post opts, (err, res, body) => return cb(err) if err @mailNewVersion body, (err) => return cb(err) if err try status = @parseStatus body cb(null, status) catch e cb(e) mailNewVersion: (body, cb) -> try $ = cheerio.load(body) guid = $("url_or_guid").text() mail from: "<EMAIL>" to: guid subject: @title text: "" html: @html cb() catch e cb(e) xml: -> xml = """ <?xml version="1.0"?> <test_set> <save_defaults>false</save_defaults> <use_defaults>false</use_defaults> <email_source> <body> <![CDATA[#{@html}]]> </body> <subject>#{@title}</subject> </email_source> <applications type="array"> """ for client in @clients xml += """ <application> <code>#{client}</code> </application> """ xml += """ </applications> </test_set> """ xml
true
### Copyright (c) 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### request = require "request" mail = require("nodemailer").mail cheerio = require "cheerio" _ = require "underscore" module.exports = class Litmus constructor: (options) -> @html = options.html @title = options.title @baseUrl = options.url @clients = options.clients @auth = user: options.username pass: options.password run: (cb) -> @litmusId (err, id) => return cb(err) if err if id @updateTest id, cb else @createTest cb litmusId: (cb) -> opts = auth: @auth url: "#{@baseUrl}/tests.xml" request.get opts, (err, res, body) -> return cb(err) if err try id = null $ = cheerio.load body, xmlMode: true title = @title $name = $("name").filter -> $nameTag = $(this) $nameTag.text() == title id = $matchedName.parent().children("id").text() if $name.length cb(null, id) catch e cb(e) parseStatus: (body) -> $ = cheerio.load body, xmlMode: true statuses = $("status") delayed = [] unavailable = [] seconds = 0 avgTimes = $("average_time_to_process") avgTimes.each (i, el) -> seconds += parseInt($(this).text(), 10) seconds = Math.round(seconds / avgTimes.length) statuses.each (i, el) -> $this = $(this) statusCode = parseInt($this.text(), 10) appName = $this.parent().children("application_long_name").text() switch statusCode when 1 delayed.push(appName) when 2 unavailable.push(appName) time: seconds delayed: delayed unavailable: unavailable createTest: (cb) -> opts = auth: @auth headers: "Content-type": "application/xml" "Accept": "application/xml" body: @xml() url: "#{@baseUrl}/emails.xml" request.post opts, (err, res, body) => return cb(err) if err try status = res.headers.status unless /^2/.test status return cb(status) status = @parseStatus body cb(null, status) catch e cb(e) updateTest: (id, cb) -> opts = auth: @auth headers: "Content-type": "application/xml" "Accept": "application/xml" body: @xml() url: "#{@baseUrl}/tests/#{id}/versions.xml" request.post opts, (err, res, body) => return cb(err) if err @mailNewVersion body, (err) => return cb(err) if err try status = @parseStatus body cb(null, status) catch e cb(e) mailNewVersion: (body, cb) -> try $ = cheerio.load(body) guid = $("url_or_guid").text() mail from: "PI:EMAIL:<EMAIL>END_PI" to: guid subject: @title text: "" html: @html cb() catch e cb(e) xml: -> xml = """ <?xml version="1.0"?> <test_set> <save_defaults>false</save_defaults> <use_defaults>false</use_defaults> <email_source> <body> <![CDATA[#{@html}]]> </body> <subject>#{@title}</subject> </email_source> <applications type="array"> """ for client in @clients xml += """ <application> <code>#{client}</code> </application> """ xml += """ </applications> </test_set> """ xml
[ { "context": "email: tmpl.$('#inputEmail').val()\n password: password\n }\n\n Meteor.call 'createUserByInvite', user", "end": 868, "score": 0.9991316199302673, "start": 860, "tag": "PASSWORD", "value": "password" } ]
client/templates/sign-up/sign-up.coffee
JSSolutions/Dataforce
2
Template.SignUp.onCreated -> @errorMessage = new ReactiveVar(false) @email = new ReactiveVar() Meteor.call 'getEmailByInviteId', @data.inviteId, (err, email) => if err @errorMessage.set err.toString() else @email.set email Template.SignUp.helpers errorMessage: -> Template.instance().errorMessage.get() email: -> Template.instance().email.get() Template.SignUp.events 'submit form': (event, tmpl) -> event.preventDefault() password = tmpl.$('#inputPassword').val() passwordRepeat = tmpl.$('#inputPasswordRepeat').val() if password isnt passwordRepeat tmpl.errorMessage.set 'Passwords should match' return if password.length < 8 tmpl.errorMessage.set 'Password\'s length should be 8 letters or more' return user = { email: tmpl.$('#inputEmail').val() password: password } Meteor.call 'createUserByInvite', user, (error) -> if error tmpl.errorMessage.set error.reason else Router.go 'dashboard'
144876
Template.SignUp.onCreated -> @errorMessage = new ReactiveVar(false) @email = new ReactiveVar() Meteor.call 'getEmailByInviteId', @data.inviteId, (err, email) => if err @errorMessage.set err.toString() else @email.set email Template.SignUp.helpers errorMessage: -> Template.instance().errorMessage.get() email: -> Template.instance().email.get() Template.SignUp.events 'submit form': (event, tmpl) -> event.preventDefault() password = tmpl.$('#inputPassword').val() passwordRepeat = tmpl.$('#inputPasswordRepeat').val() if password isnt passwordRepeat tmpl.errorMessage.set 'Passwords should match' return if password.length < 8 tmpl.errorMessage.set 'Password\'s length should be 8 letters or more' return user = { email: tmpl.$('#inputEmail').val() password: <PASSWORD> } Meteor.call 'createUserByInvite', user, (error) -> if error tmpl.errorMessage.set error.reason else Router.go 'dashboard'
true
Template.SignUp.onCreated -> @errorMessage = new ReactiveVar(false) @email = new ReactiveVar() Meteor.call 'getEmailByInviteId', @data.inviteId, (err, email) => if err @errorMessage.set err.toString() else @email.set email Template.SignUp.helpers errorMessage: -> Template.instance().errorMessage.get() email: -> Template.instance().email.get() Template.SignUp.events 'submit form': (event, tmpl) -> event.preventDefault() password = tmpl.$('#inputPassword').val() passwordRepeat = tmpl.$('#inputPasswordRepeat').val() if password isnt passwordRepeat tmpl.errorMessage.set 'Passwords should match' return if password.length < 8 tmpl.errorMessage.set 'Password\'s length should be 8 letters or more' return user = { email: tmpl.$('#inputEmail').val() password: PI:PASSWORD:<PASSWORD>END_PI } Meteor.call 'createUserByInvite', user, (error) -> if error tmpl.errorMessage.set error.reason else Router.go 'dashboard'
[ { "context": "#############\n#\n#\tMoocita collections\n# Created by Markus on 26/10/2015.\n#\n################################", "end": 99, "score": 0.9995012283325195, "start": 93, "tag": "NAME", "value": "Markus" } ]
server/publications/posts.coffee
agottschalk10/worklearn
0
####################################################### # # Moocita collections # Created by Markus on 26/10/2015. # ####################################################### ####################################################### Meteor.publish "posts", (group_name) -> check group_name, String user_id = this.userId restrict = group_name: group_name filter = filter_visible_documents user_id, restrict fields = visible_fields Posts, user_id, filter crs = Posts.find filter, fields log_publication "Posts", crs, filter, restrict, "posts", user_id return crs
215813
####################################################### # # Moocita collections # Created by <NAME> on 26/10/2015. # ####################################################### ####################################################### Meteor.publish "posts", (group_name) -> check group_name, String user_id = this.userId restrict = group_name: group_name filter = filter_visible_documents user_id, restrict fields = visible_fields Posts, user_id, filter crs = Posts.find filter, fields log_publication "Posts", crs, filter, restrict, "posts", user_id return crs
true
####################################################### # # Moocita collections # Created by PI:NAME:<NAME>END_PI on 26/10/2015. # ####################################################### ####################################################### Meteor.publish "posts", (group_name) -> check group_name, String user_id = this.userId restrict = group_name: group_name filter = filter_visible_documents user_id, restrict fields = visible_fields Posts, user_id, filter crs = Posts.find filter, fields log_publication "Posts", crs, filter, restrict, "posts", user_id return crs
[ { "context": "nk-you-for-considering'\n hashedToken: 'ZOGZOX7K4XywpyNFjVS+6SfbXFux8FNW7VT6NWmsz6E='\n metadata:\n tag: 'hello'\n", "end": 860, "score": 0.9941454529762268, "start": 815, "tag": "KEY", "value": "ZOGZOX7K4XywpyNFjVS+6SfbXFux8FNW7VT6NWmsz6E='" }, { "context": "nk-you-for-considering'\n hashedToken: 'bOT5i3r4bUXvG5owgEVUBOtnF30zyuShfocALDoi1HA='\n metadata:\n tag: 'hello'\n", "end": 1052, "score": 0.9919612407684326, "start": 1007, "tag": "KEY", "value": "bOT5i3r4bUXvG5owgEVUBOtnF30zyuShfocALDoi1HA='" }, { "context": "nk-you-for-considering'\n hashedToken: 'T/GMBdFNOc9l3uagnYZSwgFfjtp8Vlf6ryltQUEUY1U='\n metadata:\n tag: 'not-thi", "end": 1243, "score": 0.9950069785118103, "start": 1198, "tag": "KEY", "value": "T/GMBdFNOc9l3uagnYZSwgFfjtp8Vlf6ryltQUEUY1U='" }, { "context": "uid: 'some-other-token'\n hashedToken: 'T/GMBdFNOc9l3uagnYZSwgFfjtp8Vlf6ryltQUEUY1U='\n metadata:\n tag: 'not-thi", "end": 1432, "score": 0.9967442154884338, "start": 1387, "tag": "KEY", "value": "T/GMBdFNOc9l3uagnYZSwgFfjtp8Vlf6ryltQUEUY1U='" }, { "context": " 'should-not-use-this-uuid'\n token: 'the-environment'\n\n @sut.do request, (error, @response) => ", "end": 1808, "score": 0.9593384861946106, "start": 1793, "tag": "PASSWORD", "value": "the-environment" } ]
test/revoke-all-tokens.coffee
octoblu/meshblu-core-task-revoke-all-tokens
0
_ = require 'lodash' mongojs = require 'mongojs' Datastore = require 'meshblu-core-datastore' RevokeAllTokens = require '..' describe 'RevokeAllTokens', -> beforeEach (done) -> @uuidAliasResolver = resolve: (uuid, callback) => callback null, uuid database = mongojs 'meshblu-core-task-check-token', ['tokens'] @datastore = new Datastore database: database collection: 'tokens' database.tokens.remove done beforeEach -> @sut = new RevokeAllTokens datastore: @datastore pepper: 'totally-a-secret' uuidAliasResolver: @uuidAliasResolver describe '->do', -> context 'when given a valid token', -> beforeEach (done) -> record = [ { uuid: 'thank-you-for-considering' hashedToken: 'ZOGZOX7K4XywpyNFjVS+6SfbXFux8FNW7VT6NWmsz6E=' metadata: tag: 'hello' }, { uuid: 'thank-you-for-considering' hashedToken: 'bOT5i3r4bUXvG5owgEVUBOtnF30zyuShfocALDoi1HA=' metadata: tag: 'hello' } { uuid: 'thank-you-for-considering' hashedToken: 'T/GMBdFNOc9l3uagnYZSwgFfjtp8Vlf6ryltQUEUY1U=' metadata: tag: 'not-this-one' } { uuid: 'some-other-token' hashedToken: 'T/GMBdFNOc9l3uagnYZSwgFfjtp8Vlf6ryltQUEUY1U=' metadata: tag: 'not-this-one' } ] @datastore.insert record, done beforeEach (done) -> request = metadata: responseId: 'used-as-biofuel' toUuid: 'thank-you-for-considering' auth: uuid: 'should-not-use-this-uuid' token: 'the-environment' @sut.do request, (error, @response) => done error it 'should respond with a 204', -> expectedResponse = metadata: responseId: 'used-as-biofuel' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse it 'should remove all the tokens for that uuid', (done) -> @datastore.find { uuid: 'thank-you-for-considering' }, (error, records) => return done error if error? expect(records).to.be.empty done() it 'should not remove all the tokens in the system', (done) -> @datastore.find { uuid: 'some-other-token' }, (error, records) => return done error if error? expect(records).not.to.be.empty done()
156426
_ = require 'lodash' mongojs = require 'mongojs' Datastore = require 'meshblu-core-datastore' RevokeAllTokens = require '..' describe 'RevokeAllTokens', -> beforeEach (done) -> @uuidAliasResolver = resolve: (uuid, callback) => callback null, uuid database = mongojs 'meshblu-core-task-check-token', ['tokens'] @datastore = new Datastore database: database collection: 'tokens' database.tokens.remove done beforeEach -> @sut = new RevokeAllTokens datastore: @datastore pepper: 'totally-a-secret' uuidAliasResolver: @uuidAliasResolver describe '->do', -> context 'when given a valid token', -> beforeEach (done) -> record = [ { uuid: 'thank-you-for-considering' hashedToken: '<KEY> metadata: tag: 'hello' }, { uuid: 'thank-you-for-considering' hashedToken: '<KEY> metadata: tag: 'hello' } { uuid: 'thank-you-for-considering' hashedToken: '<KEY> metadata: tag: 'not-this-one' } { uuid: 'some-other-token' hashedToken: '<KEY> metadata: tag: 'not-this-one' } ] @datastore.insert record, done beforeEach (done) -> request = metadata: responseId: 'used-as-biofuel' toUuid: 'thank-you-for-considering' auth: uuid: 'should-not-use-this-uuid' token: '<PASSWORD>' @sut.do request, (error, @response) => done error it 'should respond with a 204', -> expectedResponse = metadata: responseId: 'used-as-biofuel' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse it 'should remove all the tokens for that uuid', (done) -> @datastore.find { uuid: 'thank-you-for-considering' }, (error, records) => return done error if error? expect(records).to.be.empty done() it 'should not remove all the tokens in the system', (done) -> @datastore.find { uuid: 'some-other-token' }, (error, records) => return done error if error? expect(records).not.to.be.empty done()
true
_ = require 'lodash' mongojs = require 'mongojs' Datastore = require 'meshblu-core-datastore' RevokeAllTokens = require '..' describe 'RevokeAllTokens', -> beforeEach (done) -> @uuidAliasResolver = resolve: (uuid, callback) => callback null, uuid database = mongojs 'meshblu-core-task-check-token', ['tokens'] @datastore = new Datastore database: database collection: 'tokens' database.tokens.remove done beforeEach -> @sut = new RevokeAllTokens datastore: @datastore pepper: 'totally-a-secret' uuidAliasResolver: @uuidAliasResolver describe '->do', -> context 'when given a valid token', -> beforeEach (done) -> record = [ { uuid: 'thank-you-for-considering' hashedToken: 'PI:KEY:<KEY>END_PI metadata: tag: 'hello' }, { uuid: 'thank-you-for-considering' hashedToken: 'PI:KEY:<KEY>END_PI metadata: tag: 'hello' } { uuid: 'thank-you-for-considering' hashedToken: 'PI:KEY:<KEY>END_PI metadata: tag: 'not-this-one' } { uuid: 'some-other-token' hashedToken: 'PI:KEY:<KEY>END_PI metadata: tag: 'not-this-one' } ] @datastore.insert record, done beforeEach (done) -> request = metadata: responseId: 'used-as-biofuel' toUuid: 'thank-you-for-considering' auth: uuid: 'should-not-use-this-uuid' token: 'PI:PASSWORD:<PASSWORD>END_PI' @sut.do request, (error, @response) => done error it 'should respond with a 204', -> expectedResponse = metadata: responseId: 'used-as-biofuel' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse it 'should remove all the tokens for that uuid', (done) -> @datastore.find { uuid: 'thank-you-for-considering' }, (error, records) => return done error if error? expect(records).to.be.empty done() it 'should not remove all the tokens in the system', (done) -> @datastore.find { uuid: 'some-other-token' }, (error, records) => return done error if error? expect(records).not.to.be.empty done()
[ { "context": "# a simple syntax highlighter for Asteroid\n# (c) Lutz Hamel, Jeffrey Drummond - University of Rhode Island\n\n'", "end": 59, "score": 0.9998592138290405, "start": 49, "tag": "NAME", "value": "Lutz Hamel" }, { "context": " syntax highlighter for Asteroid\n# (c) Lutz Hamel, Jeffrey Drummond - University of Rhode Island\n\n'scopeName': 'sourc", "end": 77, "score": 0.9998242855072021, "start": 61, "tag": "NAME", "value": "Jeffrey Drummond" } ]
grammars/asteroid.cson
lutzhamel/language-asteroid
1
# a simple syntax highlighter for Asteroid # (c) Lutz Hamel, Jeffrey Drummond - University of Rhode Island 'scopeName': 'source.asteroid' 'name': 'Asteroid' 'fileTypes': ['ast', 'asteroid'] 'limitLineLength': false 'patterns': [ ################## { # comments 'match': '(--.*(\\n|$))|(#.*(\\n|$))' 'name': 'comment.line.asteroid' } ################## { # numeric constants, which may include scientific notation 'match': '(^\\d+)|(\\b(([0-9]+(\\.|\\s*E\\s*)?[0-9]*)|(\\.[0-9]+))\\b)' 'captures': '1': 'name': 'markup.bold.asteroid' '2': 'name': 'constant.numeric.asteroid' 'name': 'meta.constant.asteroid' } { # constant of data type none 'match': '\\b(none)\\b' 'name': 'keyword.operator.asteroid' } { # constant of bool 'match': '\\b(true)\\b' 'name': 'keyword.operator.asteroid' } { # constant of bool 'match': '\\b(false)\\b' 'name': 'keyword.operator.asteroid' } ################## { # strings 'begin': '(")' 'end': '(")' 'name': 'meta.string.quoted.double.asteroid' } ################## { # operators 'match': '\'|\\.|\\||\\\\|@|\\+|-|\\*|/|<|>|=|\\b(and)\\b|\\b(or)\\b' 'name': 'keyword.operator.asteroid' } ################## # key words { 'match': '\\b(assert)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(break)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(case)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(catch)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(data)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(do)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(elif)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(else)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(end)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(escape)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(for)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(from)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(function)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(global)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(if)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(in)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(is)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(lambda)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(let)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(load)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(loop)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(nonlocal)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(noop)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(match)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(orwith)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(otherwise)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(pattern)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(repeat)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(return)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(step)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(structure)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(system)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(throw)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(to)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(try)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(until)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(while)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(with)\\b' 'name': 'keyword.control.asteroid' } ]
148597
# a simple syntax highlighter for Asteroid # (c) <NAME>, <NAME> - University of Rhode Island 'scopeName': 'source.asteroid' 'name': 'Asteroid' 'fileTypes': ['ast', 'asteroid'] 'limitLineLength': false 'patterns': [ ################## { # comments 'match': '(--.*(\\n|$))|(#.*(\\n|$))' 'name': 'comment.line.asteroid' } ################## { # numeric constants, which may include scientific notation 'match': '(^\\d+)|(\\b(([0-9]+(\\.|\\s*E\\s*)?[0-9]*)|(\\.[0-9]+))\\b)' 'captures': '1': 'name': 'markup.bold.asteroid' '2': 'name': 'constant.numeric.asteroid' 'name': 'meta.constant.asteroid' } { # constant of data type none 'match': '\\b(none)\\b' 'name': 'keyword.operator.asteroid' } { # constant of bool 'match': '\\b(true)\\b' 'name': 'keyword.operator.asteroid' } { # constant of bool 'match': '\\b(false)\\b' 'name': 'keyword.operator.asteroid' } ################## { # strings 'begin': '(")' 'end': '(")' 'name': 'meta.string.quoted.double.asteroid' } ################## { # operators 'match': '\'|\\.|\\||\\\\|@|\\+|-|\\*|/|<|>|=|\\b(and)\\b|\\b(or)\\b' 'name': 'keyword.operator.asteroid' } ################## # key words { 'match': '\\b(assert)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(break)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(case)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(catch)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(data)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(do)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(elif)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(else)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(end)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(escape)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(for)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(from)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(function)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(global)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(if)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(in)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(is)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(lambda)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(let)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(load)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(loop)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(nonlocal)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(noop)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(match)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(orwith)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(otherwise)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(pattern)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(repeat)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(return)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(step)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(structure)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(system)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(throw)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(to)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(try)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(until)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(while)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(with)\\b' 'name': 'keyword.control.asteroid' } ]
true
# a simple syntax highlighter for Asteroid # (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI - University of Rhode Island 'scopeName': 'source.asteroid' 'name': 'Asteroid' 'fileTypes': ['ast', 'asteroid'] 'limitLineLength': false 'patterns': [ ################## { # comments 'match': '(--.*(\\n|$))|(#.*(\\n|$))' 'name': 'comment.line.asteroid' } ################## { # numeric constants, which may include scientific notation 'match': '(^\\d+)|(\\b(([0-9]+(\\.|\\s*E\\s*)?[0-9]*)|(\\.[0-9]+))\\b)' 'captures': '1': 'name': 'markup.bold.asteroid' '2': 'name': 'constant.numeric.asteroid' 'name': 'meta.constant.asteroid' } { # constant of data type none 'match': '\\b(none)\\b' 'name': 'keyword.operator.asteroid' } { # constant of bool 'match': '\\b(true)\\b' 'name': 'keyword.operator.asteroid' } { # constant of bool 'match': '\\b(false)\\b' 'name': 'keyword.operator.asteroid' } ################## { # strings 'begin': '(")' 'end': '(")' 'name': 'meta.string.quoted.double.asteroid' } ################## { # operators 'match': '\'|\\.|\\||\\\\|@|\\+|-|\\*|/|<|>|=|\\b(and)\\b|\\b(or)\\b' 'name': 'keyword.operator.asteroid' } ################## # key words { 'match': '\\b(assert)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(break)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(case)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(catch)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(data)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(do)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(elif)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(else)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(end)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(escape)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(for)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(from)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(function)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(global)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(if)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(in)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(is)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(lambda)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(let)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(load)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(loop)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(nonlocal)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(noop)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(match)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(orwith)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(otherwise)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(pattern)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(repeat)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(return)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(step)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(structure)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(system)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(throw)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(to)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(try)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(until)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(while)\\b' 'name': 'keyword.control.asteroid' } { 'match': '\\b(with)\\b' 'name': 'keyword.control.asteroid' } ]
[ { "context": "ish attributes', ->\n data = {\n name: 'bla'\n price: 1\n description: 'blabla'\n ", "end": 1138, "score": 0.9946961402893066, "start": 1135, "tag": "NAME", "value": "bla" }, { "context": ":'blabla',picture:'images/1.png',user:{id:1,name:'jack',avatar:'avatars/jack.png'}},\n {id:2,com", "end": 1283, "score": 0.6525909304618835, "start": 1279, "tag": "NAME", "value": "jack" }, { "context": ":'blabla',picture:'images/2.png',user:{id:2,name:'rose',avatar:'avatars/rose.png'}},\n ]\n }\n ", "end": 1391, "score": 0.9922888875007629, "start": 1387, "tag": "USERNAME", "value": "rose" }, { "context": " ]\n }\n attributes = {\n name: 'bla'\n price: 1\n description: 'blabla'\n ", "end": 1479, "score": 0.9946272373199463, "start": 1476, "tag": "NAME", "value": "bla" } ]
Resources/specs/models/DishSpec.coffee
yuchenzhang/social_menu_tt
0
describe 'Dish model', -> dish = null beforeEach -> dish = new Ti.Model.Dish describe 'attributes', -> it 'should have its count defined as zero by default', -> expect(dish.attributes.count).toEqual 0 it 'should by default is orderable', -> expect(dish.attributes.orderable).toEqual true describe 'validations', -> it 'should not accept a invalid id', -> expect(dish.set {id:'abc'}).toBeFalsy() it 'should not accept a null id', -> expect(dish.set {id: null}).toBeFalsy() it 'should not accept a null name', -> expect(dish.set {name: null}).toBeFalsy() it 'should not accept a null price', -> expect(dish.set {price: null}).toBeFalsy() it 'should not accept a invalid price', -> expect(dish.set {price: 'abc'}).toBeFalsy() it 'should not accept a invalid count', -> expect(dish.set {count: 'abc'}).toBeFalsy() it 'should not accept a minus count', -> expect(dish.set {count:-1}).toBeFalsy() describe 'parse', -> it 'should (re)set the review collection and return the dish attributes', -> data = { name: 'bla' price: 1 description: 'blabla' reviews: [ {id:1,comment:'blabla',picture:'images/1.png',user:{id:1,name:'jack',avatar:'avatars/jack.png'}}, {id:2,comment:'blabla',picture:'images/2.png',user:{id:2,name:'rose',avatar:'avatars/rose.png'}}, ] } attributes = { name: 'bla' price: 1 description: 'blabla' } expect(dish.parse data).toEqual attributes expect(dish.reviews.length).toEqual 2 expect(dish.reviews.at(0) instanceof Ti.Model.Review).toBeTruthy() expect(dish.reviews.at(0).attributes.picture).toEqual 'images/1.png'
166667
describe 'Dish model', -> dish = null beforeEach -> dish = new Ti.Model.Dish describe 'attributes', -> it 'should have its count defined as zero by default', -> expect(dish.attributes.count).toEqual 0 it 'should by default is orderable', -> expect(dish.attributes.orderable).toEqual true describe 'validations', -> it 'should not accept a invalid id', -> expect(dish.set {id:'abc'}).toBeFalsy() it 'should not accept a null id', -> expect(dish.set {id: null}).toBeFalsy() it 'should not accept a null name', -> expect(dish.set {name: null}).toBeFalsy() it 'should not accept a null price', -> expect(dish.set {price: null}).toBeFalsy() it 'should not accept a invalid price', -> expect(dish.set {price: 'abc'}).toBeFalsy() it 'should not accept a invalid count', -> expect(dish.set {count: 'abc'}).toBeFalsy() it 'should not accept a minus count', -> expect(dish.set {count:-1}).toBeFalsy() describe 'parse', -> it 'should (re)set the review collection and return the dish attributes', -> data = { name: '<NAME>' price: 1 description: 'blabla' reviews: [ {id:1,comment:'blabla',picture:'images/1.png',user:{id:1,name:'<NAME>',avatar:'avatars/jack.png'}}, {id:2,comment:'blabla',picture:'images/2.png',user:{id:2,name:'rose',avatar:'avatars/rose.png'}}, ] } attributes = { name: '<NAME>' price: 1 description: 'blabla' } expect(dish.parse data).toEqual attributes expect(dish.reviews.length).toEqual 2 expect(dish.reviews.at(0) instanceof Ti.Model.Review).toBeTruthy() expect(dish.reviews.at(0).attributes.picture).toEqual 'images/1.png'
true
describe 'Dish model', -> dish = null beforeEach -> dish = new Ti.Model.Dish describe 'attributes', -> it 'should have its count defined as zero by default', -> expect(dish.attributes.count).toEqual 0 it 'should by default is orderable', -> expect(dish.attributes.orderable).toEqual true describe 'validations', -> it 'should not accept a invalid id', -> expect(dish.set {id:'abc'}).toBeFalsy() it 'should not accept a null id', -> expect(dish.set {id: null}).toBeFalsy() it 'should not accept a null name', -> expect(dish.set {name: null}).toBeFalsy() it 'should not accept a null price', -> expect(dish.set {price: null}).toBeFalsy() it 'should not accept a invalid price', -> expect(dish.set {price: 'abc'}).toBeFalsy() it 'should not accept a invalid count', -> expect(dish.set {count: 'abc'}).toBeFalsy() it 'should not accept a minus count', -> expect(dish.set {count:-1}).toBeFalsy() describe 'parse', -> it 'should (re)set the review collection and return the dish attributes', -> data = { name: 'PI:NAME:<NAME>END_PI' price: 1 description: 'blabla' reviews: [ {id:1,comment:'blabla',picture:'images/1.png',user:{id:1,name:'PI:NAME:<NAME>END_PI',avatar:'avatars/jack.png'}}, {id:2,comment:'blabla',picture:'images/2.png',user:{id:2,name:'rose',avatar:'avatars/rose.png'}}, ] } attributes = { name: 'PI:NAME:<NAME>END_PI' price: 1 description: 'blabla' } expect(dish.parse data).toEqual attributes expect(dish.reviews.length).toEqual 2 expect(dish.reviews.at(0) instanceof Ti.Model.Review).toBeTruthy() expect(dish.reviews.at(0).attributes.picture).toEqual 'images/1.png'
[ { "context": "- - - - - - - - - - - - - - - #\n# Copyright © 2015 Denis Luchkin-Zhou #\n# See L", "end": 277, "score": 0.9998679757118225, "start": 259, "tag": "NAME", "value": "Denis Luchkin-Zhou" } ]
gulp/aliases.coffee
jluchiji/tranzit
0
# --------------------------------------------------------------------------- # # wyvernzora.ninja build script. # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Copyright © 2015 Denis Luchkin-Zhou # # See LICENSE.md for terms of distribution. # # --------------------------------------------------------------------------- # sequence = require 'run-sequence' module.exports = (gulp, config) -> gulp.task 'default', -> sequence( 'all:clean', 'all:build' ) gulp.task 'all:clean', ['server:clean', 'client:clean'] gulp.task 'all:build', ['server:build', 'client'] gulp.task 'client', ['bower', 'client:assets', 'client:markup', 'client:scripts', 'client:styles'] gulp.task 'client:markup', ['client:html', 'client:jade'] gulp.task 'bower', ['bower:scripts', 'bower:styles', 'bower:fonts'] gulp.task 'server', ['server:build'] gulp.task 'server:build', ['server:scripts', 'server:config'] gulp.task 'live-dev', ['default', 'server:launch', 'client:watch']
160271
# --------------------------------------------------------------------------- # # wyvernzora.ninja build script. # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Copyright © 2015 <NAME> # # See LICENSE.md for terms of distribution. # # --------------------------------------------------------------------------- # sequence = require 'run-sequence' module.exports = (gulp, config) -> gulp.task 'default', -> sequence( 'all:clean', 'all:build' ) gulp.task 'all:clean', ['server:clean', 'client:clean'] gulp.task 'all:build', ['server:build', 'client'] gulp.task 'client', ['bower', 'client:assets', 'client:markup', 'client:scripts', 'client:styles'] gulp.task 'client:markup', ['client:html', 'client:jade'] gulp.task 'bower', ['bower:scripts', 'bower:styles', 'bower:fonts'] gulp.task 'server', ['server:build'] gulp.task 'server:build', ['server:scripts', 'server:config'] gulp.task 'live-dev', ['default', 'server:launch', 'client:watch']
true
# --------------------------------------------------------------------------- # # wyvernzora.ninja build script. # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Copyright © 2015 PI:NAME:<NAME>END_PI # # See LICENSE.md for terms of distribution. # # --------------------------------------------------------------------------- # sequence = require 'run-sequence' module.exports = (gulp, config) -> gulp.task 'default', -> sequence( 'all:clean', 'all:build' ) gulp.task 'all:clean', ['server:clean', 'client:clean'] gulp.task 'all:build', ['server:build', 'client'] gulp.task 'client', ['bower', 'client:assets', 'client:markup', 'client:scripts', 'client:styles'] gulp.task 'client:markup', ['client:html', 'client:jade'] gulp.task 'bower', ['bower:scripts', 'bower:styles', 'bower:fonts'] gulp.task 'server', ['server:build'] gulp.task 'server:build', ['server:scripts', 'server:config'] gulp.task 'live-dev', ['default', 'server:launch', 'client:watch']
[ { "context": "# Looks Good To Me\n# by Nikolai Warner, 2012\n\nclass LooksGoodToMe\n constructor: (option", "end": 38, "score": 0.9998862147331238, "start": 24, "tag": "NAME", "value": "Nikolai Warner" }, { "context": "comments, for example:\n # https://github.com/nikolaiwarner/Looks-Good-To-Me/pull/21\n $.get pull_url, (r", "end": 1471, "score": 0.9989539384841919, "start": 1458, "tag": "USERNAME", "value": "nikolaiwarner" } ]
lgtm.coffee
WalrusCow/Looks-Good-To-Me
0
# Looks Good To Me # by Nikolai Warner, 2012 class LooksGoodToMe constructor: (options={}) -> @refresh_rate = options.refresh_rate || 5 * 60000 @ci_status_selector = options.ci_status_selector || 'status_icon' @default_plus_one_message = options.default_plus_one_message || '+1' @good = options.good || 1 @better = options.better || 2 @best = options.best || 3 @regexes = options.regexes || [ /looks good to me/ig, /lgtm/ig, /(\s|\z|>)\+1(\s|\z|<)/g, /title=":\+1:"/ig ] @restore_options() # Initialize Chrome Events #document.addEventListener "DOMContentLoaded", => # if $("body.lgtm.options").length > 0 # Init for Options Page # $(".save_button").click => @save_options() # console.log "Options Page." # Init for Github pages if @refresh_rate > 0 setInterval(@refresh, @refresh_rate) @refresh() refresh: => # Remove previous badges $('.lgtm_badge, .lgtm_button, .lgtm_icon, .lgtm_container').remove() # We're on a pull request index page $('.pulls-list-group .list-group-item').each (index, listing) => title = $(listing).find('h4') pull_url = title.find('a').prop('href') authorInfo = $(listing).find('.list-group-item-meta li').first() authorName = authorInfo.find('a').not('.gravatar').text() # Who needs apis? :) # Get the pull comments, for example: # https://github.com/nikolaiwarner/Looks-Good-To-Me/pull/21 $.get pull_url, (response) => container = $('<div>') container.addClass('lgtm_container') title.before(container) ones_count = @count_ones(response, authorName) container.append(@make_a_badge(ones_count.ones)) container.find('.lgtm_badge').append(@list_participants(ones_count.participants)) #container.append(@get_ci_build_status_icon(response).addClass('lgtm_icon')) # We're on a pull request show page $('#discussion_bucket').each (index, discussion) => title = $(discussion).find('.discussion-topic-title') merge_button = $(discussion).find('.mergeable .minibutton').first() authorName = $(discussion).find('.discussion-topic-author a').text() ones_count = @count_ones(discussion, authorName) if badge = @make_a_badge(ones_count.ones, 'lgtm_large') badge.clone().prependTo(title) badge.clone().prependTo(merge_button) merge_button.find('.lgtm_large').append(@list_participants(ones_count.participants)) # Show Plus One, the button message = @default_plus_one_message refresh = @refresh button = $("<button type='submit'>#{message}</button>") button.addClass('button primary lgtm_button') button.click -> $(@).closest('form').find('.write-content textarea').html("#{message}") setTimeout(refresh, 5000) button.insertBefore('.discussion-bubble .button.primary') # Count plus ones in each comment count_ones: (string, authorName) => ones = 0 participants = {} # Scrape out and count what we want from the string $('.comment-body', string).each (index, comment) => # Clean up the comment body $(comment).find('.email-signature-reply').remove() $(comment).find('.email-quoted-reply').remove() # Capture information about particitpant comment_bubble = $(comment).closest('.discussion-bubble') participantName = $(comment_bubble).find('.comment-header-author').text() participantImage = $(comment_bubble).find('.discussion-bubble-avatar').clone() # You can't upvote your own pull request or vote twice if participants[participantName] or participantName == authorName return for regex in @regexes if count = $(comment).html().match(regex) ones += 1 # Save name and image of participant participants[participantName] = participantImage break return { ones: ones participants: participants } make_a_badge: (ones=0, extra_classes='') => badge = undefined if ones > 0 badge = $('<span>') badge.addClass("lgtm_badge #{extra_classes}") badge.html("+#{ones}") # Set the color based on momentum if ones >= @good and ones < @better badge.addClass('lgtm_good') else if ones >= @better and ones < @best badge.addClass('lgtm_better') else if ones >= @best badge.addClass('lgtm_best') else badge.addClass('lgtm_okay') return badge list_participants: (participants={}) => list = $('<span>') list.addClass('lgtm_participants') for name, image of participants image.prop('title', name) image.addClass('participant_thumb') list.append(image) return list restore_options: => chrome.storage.sync.get null, (items) => $("#regexes").attr("checked", (items["show_badge"] == "true")) $("#refresh_rate").attr("checked", (items["show_notification"] == "true")) $("#ci_status_selector").val(items["rss_url"]) $("#default_plus_one_message").val(items["rss_url"]) # Listen for storage changes chrome.storage.onChanged.addListener (changes, namespace) -> for key in changes storageChange = changes[key] @[key] = storageChange.newValue console.log('Storage key "%s" in namespace "%s" changed. Old value was "%s", new value is "%s".', key, namespace, storageChange.oldValue, storageChange.newValue) save_options: => chrome.storage.sync.set() 'regexes': $('#regexes').val() 'refresh_rate': $('#refresh_rate').val() 'ci_status_selector': $('#ci_status_selector').val() 'default_plus_one_message': $('#default_plus_one_message').val() , => message('Settings saved.') # Some projects use a CI system which output the build status into Github # pull request messages. If this is included, show on index pages. get_ci_build_status_icon: (page_content) => $(".starting-comment img[src*=#{@ci_status_selector}]", page_content) window.looks_good_to_me = new LooksGoodToMe()
166037
# Looks Good To Me # by <NAME>, 2012 class LooksGoodToMe constructor: (options={}) -> @refresh_rate = options.refresh_rate || 5 * 60000 @ci_status_selector = options.ci_status_selector || 'status_icon' @default_plus_one_message = options.default_plus_one_message || '+1' @good = options.good || 1 @better = options.better || 2 @best = options.best || 3 @regexes = options.regexes || [ /looks good to me/ig, /lgtm/ig, /(\s|\z|>)\+1(\s|\z|<)/g, /title=":\+1:"/ig ] @restore_options() # Initialize Chrome Events #document.addEventListener "DOMContentLoaded", => # if $("body.lgtm.options").length > 0 # Init for Options Page # $(".save_button").click => @save_options() # console.log "Options Page." # Init for Github pages if @refresh_rate > 0 setInterval(@refresh, @refresh_rate) @refresh() refresh: => # Remove previous badges $('.lgtm_badge, .lgtm_button, .lgtm_icon, .lgtm_container').remove() # We're on a pull request index page $('.pulls-list-group .list-group-item').each (index, listing) => title = $(listing).find('h4') pull_url = title.find('a').prop('href') authorInfo = $(listing).find('.list-group-item-meta li').first() authorName = authorInfo.find('a').not('.gravatar').text() # Who needs apis? :) # Get the pull comments, for example: # https://github.com/nikolaiwarner/Looks-Good-To-Me/pull/21 $.get pull_url, (response) => container = $('<div>') container.addClass('lgtm_container') title.before(container) ones_count = @count_ones(response, authorName) container.append(@make_a_badge(ones_count.ones)) container.find('.lgtm_badge').append(@list_participants(ones_count.participants)) #container.append(@get_ci_build_status_icon(response).addClass('lgtm_icon')) # We're on a pull request show page $('#discussion_bucket').each (index, discussion) => title = $(discussion).find('.discussion-topic-title') merge_button = $(discussion).find('.mergeable .minibutton').first() authorName = $(discussion).find('.discussion-topic-author a').text() ones_count = @count_ones(discussion, authorName) if badge = @make_a_badge(ones_count.ones, 'lgtm_large') badge.clone().prependTo(title) badge.clone().prependTo(merge_button) merge_button.find('.lgtm_large').append(@list_participants(ones_count.participants)) # Show Plus One, the button message = @default_plus_one_message refresh = @refresh button = $("<button type='submit'>#{message}</button>") button.addClass('button primary lgtm_button') button.click -> $(@).closest('form').find('.write-content textarea').html("#{message}") setTimeout(refresh, 5000) button.insertBefore('.discussion-bubble .button.primary') # Count plus ones in each comment count_ones: (string, authorName) => ones = 0 participants = {} # Scrape out and count what we want from the string $('.comment-body', string).each (index, comment) => # Clean up the comment body $(comment).find('.email-signature-reply').remove() $(comment).find('.email-quoted-reply').remove() # Capture information about particitpant comment_bubble = $(comment).closest('.discussion-bubble') participantName = $(comment_bubble).find('.comment-header-author').text() participantImage = $(comment_bubble).find('.discussion-bubble-avatar').clone() # You can't upvote your own pull request or vote twice if participants[participantName] or participantName == authorName return for regex in @regexes if count = $(comment).html().match(regex) ones += 1 # Save name and image of participant participants[participantName] = participantImage break return { ones: ones participants: participants } make_a_badge: (ones=0, extra_classes='') => badge = undefined if ones > 0 badge = $('<span>') badge.addClass("lgtm_badge #{extra_classes}") badge.html("+#{ones}") # Set the color based on momentum if ones >= @good and ones < @better badge.addClass('lgtm_good') else if ones >= @better and ones < @best badge.addClass('lgtm_better') else if ones >= @best badge.addClass('lgtm_best') else badge.addClass('lgtm_okay') return badge list_participants: (participants={}) => list = $('<span>') list.addClass('lgtm_participants') for name, image of participants image.prop('title', name) image.addClass('participant_thumb') list.append(image) return list restore_options: => chrome.storage.sync.get null, (items) => $("#regexes").attr("checked", (items["show_badge"] == "true")) $("#refresh_rate").attr("checked", (items["show_notification"] == "true")) $("#ci_status_selector").val(items["rss_url"]) $("#default_plus_one_message").val(items["rss_url"]) # Listen for storage changes chrome.storage.onChanged.addListener (changes, namespace) -> for key in changes storageChange = changes[key] @[key] = storageChange.newValue console.log('Storage key "%s" in namespace "%s" changed. Old value was "%s", new value is "%s".', key, namespace, storageChange.oldValue, storageChange.newValue) save_options: => chrome.storage.sync.set() 'regexes': $('#regexes').val() 'refresh_rate': $('#refresh_rate').val() 'ci_status_selector': $('#ci_status_selector').val() 'default_plus_one_message': $('#default_plus_one_message').val() , => message('Settings saved.') # Some projects use a CI system which output the build status into Github # pull request messages. If this is included, show on index pages. get_ci_build_status_icon: (page_content) => $(".starting-comment img[src*=#{@ci_status_selector}]", page_content) window.looks_good_to_me = new LooksGoodToMe()
true
# Looks Good To Me # by PI:NAME:<NAME>END_PI, 2012 class LooksGoodToMe constructor: (options={}) -> @refresh_rate = options.refresh_rate || 5 * 60000 @ci_status_selector = options.ci_status_selector || 'status_icon' @default_plus_one_message = options.default_plus_one_message || '+1' @good = options.good || 1 @better = options.better || 2 @best = options.best || 3 @regexes = options.regexes || [ /looks good to me/ig, /lgtm/ig, /(\s|\z|>)\+1(\s|\z|<)/g, /title=":\+1:"/ig ] @restore_options() # Initialize Chrome Events #document.addEventListener "DOMContentLoaded", => # if $("body.lgtm.options").length > 0 # Init for Options Page # $(".save_button").click => @save_options() # console.log "Options Page." # Init for Github pages if @refresh_rate > 0 setInterval(@refresh, @refresh_rate) @refresh() refresh: => # Remove previous badges $('.lgtm_badge, .lgtm_button, .lgtm_icon, .lgtm_container').remove() # We're on a pull request index page $('.pulls-list-group .list-group-item').each (index, listing) => title = $(listing).find('h4') pull_url = title.find('a').prop('href') authorInfo = $(listing).find('.list-group-item-meta li').first() authorName = authorInfo.find('a').not('.gravatar').text() # Who needs apis? :) # Get the pull comments, for example: # https://github.com/nikolaiwarner/Looks-Good-To-Me/pull/21 $.get pull_url, (response) => container = $('<div>') container.addClass('lgtm_container') title.before(container) ones_count = @count_ones(response, authorName) container.append(@make_a_badge(ones_count.ones)) container.find('.lgtm_badge').append(@list_participants(ones_count.participants)) #container.append(@get_ci_build_status_icon(response).addClass('lgtm_icon')) # We're on a pull request show page $('#discussion_bucket').each (index, discussion) => title = $(discussion).find('.discussion-topic-title') merge_button = $(discussion).find('.mergeable .minibutton').first() authorName = $(discussion).find('.discussion-topic-author a').text() ones_count = @count_ones(discussion, authorName) if badge = @make_a_badge(ones_count.ones, 'lgtm_large') badge.clone().prependTo(title) badge.clone().prependTo(merge_button) merge_button.find('.lgtm_large').append(@list_participants(ones_count.participants)) # Show Plus One, the button message = @default_plus_one_message refresh = @refresh button = $("<button type='submit'>#{message}</button>") button.addClass('button primary lgtm_button') button.click -> $(@).closest('form').find('.write-content textarea').html("#{message}") setTimeout(refresh, 5000) button.insertBefore('.discussion-bubble .button.primary') # Count plus ones in each comment count_ones: (string, authorName) => ones = 0 participants = {} # Scrape out and count what we want from the string $('.comment-body', string).each (index, comment) => # Clean up the comment body $(comment).find('.email-signature-reply').remove() $(comment).find('.email-quoted-reply').remove() # Capture information about particitpant comment_bubble = $(comment).closest('.discussion-bubble') participantName = $(comment_bubble).find('.comment-header-author').text() participantImage = $(comment_bubble).find('.discussion-bubble-avatar').clone() # You can't upvote your own pull request or vote twice if participants[participantName] or participantName == authorName return for regex in @regexes if count = $(comment).html().match(regex) ones += 1 # Save name and image of participant participants[participantName] = participantImage break return { ones: ones participants: participants } make_a_badge: (ones=0, extra_classes='') => badge = undefined if ones > 0 badge = $('<span>') badge.addClass("lgtm_badge #{extra_classes}") badge.html("+#{ones}") # Set the color based on momentum if ones >= @good and ones < @better badge.addClass('lgtm_good') else if ones >= @better and ones < @best badge.addClass('lgtm_better') else if ones >= @best badge.addClass('lgtm_best') else badge.addClass('lgtm_okay') return badge list_participants: (participants={}) => list = $('<span>') list.addClass('lgtm_participants') for name, image of participants image.prop('title', name) image.addClass('participant_thumb') list.append(image) return list restore_options: => chrome.storage.sync.get null, (items) => $("#regexes").attr("checked", (items["show_badge"] == "true")) $("#refresh_rate").attr("checked", (items["show_notification"] == "true")) $("#ci_status_selector").val(items["rss_url"]) $("#default_plus_one_message").val(items["rss_url"]) # Listen for storage changes chrome.storage.onChanged.addListener (changes, namespace) -> for key in changes storageChange = changes[key] @[key] = storageChange.newValue console.log('Storage key "%s" in namespace "%s" changed. Old value was "%s", new value is "%s".', key, namespace, storageChange.oldValue, storageChange.newValue) save_options: => chrome.storage.sync.set() 'regexes': $('#regexes').val() 'refresh_rate': $('#refresh_rate').val() 'ci_status_selector': $('#ci_status_selector').val() 'default_plus_one_message': $('#default_plus_one_message').val() , => message('Settings saved.') # Some projects use a CI system which output the build status into Github # pull request messages. If this is included, show on index pages. get_ci_build_status_icon: (page_content) => $(".starting-comment img[src*=#{@ci_status_selector}]", page_content) window.looks_good_to_me = new LooksGoodToMe()
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999133348464966, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/_components/user-avatar.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. import * as React from 'react' import { div } from 'react-dom-factories' bn = 'avatar' export UserAvatar = (props) -> if props.user.id? div className: osu.classWithModifiers(bn, props.modifiers) style: backgroundImage: osu.urlPresence(props.user.avatar_url) else div className: osu.classWithModifiers(bn, _.concat(props.modifiers, 'guest'))
21380
# 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. import * as React from 'react' import { div } from 'react-dom-factories' bn = 'avatar' export UserAvatar = (props) -> if props.user.id? div className: osu.classWithModifiers(bn, props.modifiers) style: backgroundImage: osu.urlPresence(props.user.avatar_url) else div className: osu.classWithModifiers(bn, _.concat(props.modifiers, 'guest'))
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. import * as React from 'react' import { div } from 'react-dom-factories' bn = 'avatar' export UserAvatar = (props) -> if props.user.id? div className: osu.classWithModifiers(bn, props.modifiers) style: backgroundImage: osu.urlPresence(props.user.avatar_url) else div className: osu.classWithModifiers(bn, _.concat(props.modifiers, 'guest'))
[ { "context": " @name grunt-chalkboard\n# @url https://github.com/adrianlee44/grunt-chalkboard\n#\n# @copyright Copyright (c) 201", "end": 82, "score": 0.999178409576416, "start": 71, "tag": "USERNAME", "value": "adrianlee44" }, { "context": "grunt-chalkboard\n#\n# @copyright Copyright (c) 2013 Adrian Lee\n# @license Licensed under the MIT license.\n#\n\nmod", "end": 144, "score": 0.9998438358306885, "start": 134, "tag": "NAME", "value": "Adrian Lee" } ]
src/chalkboard.coffee
gruntjs-updater/grunt-chalkboard
0
# # @chalk overview # @name grunt-chalkboard # @url https://github.com/adrianlee44/grunt-chalkboard # # @copyright Copyright (c) 2013 Adrian Lee # @license Licensed under the MIT license. # module.exports = (grunt) -> grunt.registerMultiTask "chalkboard", "A simple grunt task to make documentation easier.", -> path = require "path" chalkboard = require "chalkboard" options = @options separator: grunt.util.linefeed private: false header: false format: "markdown" # Iterate over all specified file groups. @files.forEach (f) -> destPath = path.normalize f.dest # Read file source. src = f.src.filter((filepath) -> unless (exist = grunt.file.exists(filepath)) grunt.log.warn "Source file \"" + filepath + "\" not found." return exist ).map((filepath) -> code = grunt.file.read filepath chalkboard.compile code, options, filepath ).join(grunt.util.normalizelf(options.separator)) # Write the destination file. if src grunt.file.write destPath, src # Print a success message. grunt.log.writeln "File \"" + destPath + "\" created."
28986
# # @chalk overview # @name grunt-chalkboard # @url https://github.com/adrianlee44/grunt-chalkboard # # @copyright Copyright (c) 2013 <NAME> # @license Licensed under the MIT license. # module.exports = (grunt) -> grunt.registerMultiTask "chalkboard", "A simple grunt task to make documentation easier.", -> path = require "path" chalkboard = require "chalkboard" options = @options separator: grunt.util.linefeed private: false header: false format: "markdown" # Iterate over all specified file groups. @files.forEach (f) -> destPath = path.normalize f.dest # Read file source. src = f.src.filter((filepath) -> unless (exist = grunt.file.exists(filepath)) grunt.log.warn "Source file \"" + filepath + "\" not found." return exist ).map((filepath) -> code = grunt.file.read filepath chalkboard.compile code, options, filepath ).join(grunt.util.normalizelf(options.separator)) # Write the destination file. if src grunt.file.write destPath, src # Print a success message. grunt.log.writeln "File \"" + destPath + "\" created."
true
# # @chalk overview # @name grunt-chalkboard # @url https://github.com/adrianlee44/grunt-chalkboard # # @copyright Copyright (c) 2013 PI:NAME:<NAME>END_PI # @license Licensed under the MIT license. # module.exports = (grunt) -> grunt.registerMultiTask "chalkboard", "A simple grunt task to make documentation easier.", -> path = require "path" chalkboard = require "chalkboard" options = @options separator: grunt.util.linefeed private: false header: false format: "markdown" # Iterate over all specified file groups. @files.forEach (f) -> destPath = path.normalize f.dest # Read file source. src = f.src.filter((filepath) -> unless (exist = grunt.file.exists(filepath)) grunt.log.warn "Source file \"" + filepath + "\" not found." return exist ).map((filepath) -> code = grunt.file.read filepath chalkboard.compile code, options, filepath ).join(grunt.util.normalizelf(options.separator)) # Write the destination file. if src grunt.file.write destPath, src # Print a success message. grunt.log.writeln "File \"" + destPath + "\" created."
[ { "context": "sions = (v) ->\n ret = {}\n for obj in v\n key = prng(16)\n hmac = hmac_obj({obj, key}).toString('hex')\n", "end": 722, "score": 0.8976977467536926, "start": 715, "tag": "KEY", "value": "prng(16" }, { "context": " arg =\n user :\n local :\n username : new_username()\n uid : new_uid()\n host : \"keybase.io\"", "end": 2935, "score": 0.9992591738700867, "start": 2923, "tag": "USERNAME", "value": "new_username" } ]
test/files/expand.iced
Dexvirxx/proofs
118
{prng} = require 'crypto' {expand_json,stub_json,hmac_obj} = require '../../lib/expand' triplesec = require('triplesec') pgp_utils = require('pgp-utils') {katch,json_stringify_sorted} = pgp_utils.util {KeyManager} = require('kbpgp').kb {prng} = require 'crypto' {constants,errors,alloc,Cryptocurrency} = require '../../' {createHash} = require 'crypto' {make_ids} = require '../../lib/base' {make_esc} = require 'iced-error' {errors} = require '../../lib/errors' new_uid = () -> prng(15).toString('hex') + "19" new_username = () -> "u_" + prng(5).toString('hex') twiddle_hex = (s) -> b = Buffer.from(s, 'hex') b[0] ^= 1 return b.toString('hex') make_expansions = (v) -> ret = {} for obj in v key = prng(16) hmac = hmac_obj({obj, key}).toString('hex') ret[hmac] = { obj, key : key.toString('hex') } return ret exports.happy = (T,cb) -> expansion_vals = [ ["a","b","c"], 300 ] expansions = make_expansions expansion_vals h = Object.keys(expansions) json = { a : 10 b : "hi" c : d : e : h[0] f : [1,2,3] g : [ { h : h[1] } ] i : h } res = expand_json { json, expansions } json.c.d.e = expansion_vals[0] json.g[0].h = expansion_vals[1] json.i[0] = expansion_vals[0] json.i[1] = expansion_vals[1] T.equal json, res, "worked" cb null exports.sad1 = (T,cb) -> expansion_vals = [ ["a","b","c"], 300 ] expansions = make_expansions expansion_vals h = Object.keys(expansions) tests = [ { expansions : { "a" : ["10"] }, json : 10, err : "bad hash" } { expansions : {}, json : 10, err : "hashcheck failure" } { expansions, json : 10, err : "Did not find expansion for" } { expansions : make_expansions(["💩"]), json : 10, err : "non-ASCII" } { expansions : {}, json : 10, err : "hashcheck failure" } { expansions : {}, json : 10, err : "bad hmac key" } ] expansion = expansions[h[0]] tests[1].expansions[h[0]] = { obj : ["a","b"], key : expansion.key } tests[4].expansions[h[0]] = { obj : expansion.obj, key : twiddle_hex(expansion.key) } tests[5].expansions[h[0]] = { obj : expansion.obj, key : expansion.key[0...12] } for t in tests err = null try expand_json t catch e err = e T.assert err?, "error for case #{JSON.stringify t}" T.assert err.toString().indexOf(t.err) >= 0, "found #{t.err}" cb null exports.check_unstub_expand = (T,cb) -> json = { a : b : c : { z : 1, y : 2, w : 3} d : e : f : true g : h : false } orig = JSON.parse JSON.stringify json expansions = {} stub_json { json, expansions, path : "a.b.c" } stub_json { json, expansions, path : "d.e"} expanded = expand_json { expansions, json } T.equal orig, expanded, "got the right value out" cb null exports.stubbed_chainlink = (T,cb) -> esc = make_esc cb, "@generate" await KeyManager.generate {}, esc defer km arg = user : local : username : new_username() uid : new_uid() host : "keybase.io" sig_eng : km.make_sig_eng() seq_type : constants.seq_types.PUBLIC cryptocurrency : address: "1BjgMvwVkpmmJ5HFGZ3L3H1G6fcKLNGT5h" type: "bitcoin" seqno : 1 prev : null stub_paths : [ "body.cryptocurrency" ] btc = new Cryptocurrency arg await btc.generate_v2 esc defer out verifier = alloc out.inner.obj.body.type, arg varg = { armored : out.armored, skip_ids : true, make_ids : true, inner : out.inner.str, expansions : out.expansions} await verifier.verify_v2 varg, esc defer() for k,v of out.expansions v.obj.foo = "bar" out.expansions[k] = v await verifier.verify_v2 varg, defer err T.assert err?, "failed to destub" T.assert (err instanceof errors.ExpansionError), "right kind of error" T.assert (err.toString().indexOf("hashcheck failure in stub import") >= 0), "right error message" cb null
88897
{prng} = require 'crypto' {expand_json,stub_json,hmac_obj} = require '../../lib/expand' triplesec = require('triplesec') pgp_utils = require('pgp-utils') {katch,json_stringify_sorted} = pgp_utils.util {KeyManager} = require('kbpgp').kb {prng} = require 'crypto' {constants,errors,alloc,Cryptocurrency} = require '../../' {createHash} = require 'crypto' {make_ids} = require '../../lib/base' {make_esc} = require 'iced-error' {errors} = require '../../lib/errors' new_uid = () -> prng(15).toString('hex') + "19" new_username = () -> "u_" + prng(5).toString('hex') twiddle_hex = (s) -> b = Buffer.from(s, 'hex') b[0] ^= 1 return b.toString('hex') make_expansions = (v) -> ret = {} for obj in v key = <KEY>) hmac = hmac_obj({obj, key}).toString('hex') ret[hmac] = { obj, key : key.toString('hex') } return ret exports.happy = (T,cb) -> expansion_vals = [ ["a","b","c"], 300 ] expansions = make_expansions expansion_vals h = Object.keys(expansions) json = { a : 10 b : "hi" c : d : e : h[0] f : [1,2,3] g : [ { h : h[1] } ] i : h } res = expand_json { json, expansions } json.c.d.e = expansion_vals[0] json.g[0].h = expansion_vals[1] json.i[0] = expansion_vals[0] json.i[1] = expansion_vals[1] T.equal json, res, "worked" cb null exports.sad1 = (T,cb) -> expansion_vals = [ ["a","b","c"], 300 ] expansions = make_expansions expansion_vals h = Object.keys(expansions) tests = [ { expansions : { "a" : ["10"] }, json : 10, err : "bad hash" } { expansions : {}, json : 10, err : "hashcheck failure" } { expansions, json : 10, err : "Did not find expansion for" } { expansions : make_expansions(["💩"]), json : 10, err : "non-ASCII" } { expansions : {}, json : 10, err : "hashcheck failure" } { expansions : {}, json : 10, err : "bad hmac key" } ] expansion = expansions[h[0]] tests[1].expansions[h[0]] = { obj : ["a","b"], key : expansion.key } tests[4].expansions[h[0]] = { obj : expansion.obj, key : twiddle_hex(expansion.key) } tests[5].expansions[h[0]] = { obj : expansion.obj, key : expansion.key[0...12] } for t in tests err = null try expand_json t catch e err = e T.assert err?, "error for case #{JSON.stringify t}" T.assert err.toString().indexOf(t.err) >= 0, "found #{t.err}" cb null exports.check_unstub_expand = (T,cb) -> json = { a : b : c : { z : 1, y : 2, w : 3} d : e : f : true g : h : false } orig = JSON.parse JSON.stringify json expansions = {} stub_json { json, expansions, path : "a.b.c" } stub_json { json, expansions, path : "d.e"} expanded = expand_json { expansions, json } T.equal orig, expanded, "got the right value out" cb null exports.stubbed_chainlink = (T,cb) -> esc = make_esc cb, "@generate" await KeyManager.generate {}, esc defer km arg = user : local : username : new_username() uid : new_uid() host : "keybase.io" sig_eng : km.make_sig_eng() seq_type : constants.seq_types.PUBLIC cryptocurrency : address: "1BjgMvwVkpmmJ5HFGZ3L3H1G6fcKLNGT5h" type: "bitcoin" seqno : 1 prev : null stub_paths : [ "body.cryptocurrency" ] btc = new Cryptocurrency arg await btc.generate_v2 esc defer out verifier = alloc out.inner.obj.body.type, arg varg = { armored : out.armored, skip_ids : true, make_ids : true, inner : out.inner.str, expansions : out.expansions} await verifier.verify_v2 varg, esc defer() for k,v of out.expansions v.obj.foo = "bar" out.expansions[k] = v await verifier.verify_v2 varg, defer err T.assert err?, "failed to destub" T.assert (err instanceof errors.ExpansionError), "right kind of error" T.assert (err.toString().indexOf("hashcheck failure in stub import") >= 0), "right error message" cb null
true
{prng} = require 'crypto' {expand_json,stub_json,hmac_obj} = require '../../lib/expand' triplesec = require('triplesec') pgp_utils = require('pgp-utils') {katch,json_stringify_sorted} = pgp_utils.util {KeyManager} = require('kbpgp').kb {prng} = require 'crypto' {constants,errors,alloc,Cryptocurrency} = require '../../' {createHash} = require 'crypto' {make_ids} = require '../../lib/base' {make_esc} = require 'iced-error' {errors} = require '../../lib/errors' new_uid = () -> prng(15).toString('hex') + "19" new_username = () -> "u_" + prng(5).toString('hex') twiddle_hex = (s) -> b = Buffer.from(s, 'hex') b[0] ^= 1 return b.toString('hex') make_expansions = (v) -> ret = {} for obj in v key = PI:KEY:<KEY>END_PI) hmac = hmac_obj({obj, key}).toString('hex') ret[hmac] = { obj, key : key.toString('hex') } return ret exports.happy = (T,cb) -> expansion_vals = [ ["a","b","c"], 300 ] expansions = make_expansions expansion_vals h = Object.keys(expansions) json = { a : 10 b : "hi" c : d : e : h[0] f : [1,2,3] g : [ { h : h[1] } ] i : h } res = expand_json { json, expansions } json.c.d.e = expansion_vals[0] json.g[0].h = expansion_vals[1] json.i[0] = expansion_vals[0] json.i[1] = expansion_vals[1] T.equal json, res, "worked" cb null exports.sad1 = (T,cb) -> expansion_vals = [ ["a","b","c"], 300 ] expansions = make_expansions expansion_vals h = Object.keys(expansions) tests = [ { expansions : { "a" : ["10"] }, json : 10, err : "bad hash" } { expansions : {}, json : 10, err : "hashcheck failure" } { expansions, json : 10, err : "Did not find expansion for" } { expansions : make_expansions(["💩"]), json : 10, err : "non-ASCII" } { expansions : {}, json : 10, err : "hashcheck failure" } { expansions : {}, json : 10, err : "bad hmac key" } ] expansion = expansions[h[0]] tests[1].expansions[h[0]] = { obj : ["a","b"], key : expansion.key } tests[4].expansions[h[0]] = { obj : expansion.obj, key : twiddle_hex(expansion.key) } tests[5].expansions[h[0]] = { obj : expansion.obj, key : expansion.key[0...12] } for t in tests err = null try expand_json t catch e err = e T.assert err?, "error for case #{JSON.stringify t}" T.assert err.toString().indexOf(t.err) >= 0, "found #{t.err}" cb null exports.check_unstub_expand = (T,cb) -> json = { a : b : c : { z : 1, y : 2, w : 3} d : e : f : true g : h : false } orig = JSON.parse JSON.stringify json expansions = {} stub_json { json, expansions, path : "a.b.c" } stub_json { json, expansions, path : "d.e"} expanded = expand_json { expansions, json } T.equal orig, expanded, "got the right value out" cb null exports.stubbed_chainlink = (T,cb) -> esc = make_esc cb, "@generate" await KeyManager.generate {}, esc defer km arg = user : local : username : new_username() uid : new_uid() host : "keybase.io" sig_eng : km.make_sig_eng() seq_type : constants.seq_types.PUBLIC cryptocurrency : address: "1BjgMvwVkpmmJ5HFGZ3L3H1G6fcKLNGT5h" type: "bitcoin" seqno : 1 prev : null stub_paths : [ "body.cryptocurrency" ] btc = new Cryptocurrency arg await btc.generate_v2 esc defer out verifier = alloc out.inner.obj.body.type, arg varg = { armored : out.armored, skip_ids : true, make_ids : true, inner : out.inner.str, expansions : out.expansions} await verifier.verify_v2 varg, esc defer() for k,v of out.expansions v.obj.foo = "bar" out.expansions[k] = v await verifier.verify_v2 varg, defer err T.assert err?, "failed to destub" T.assert (err instanceof errors.ExpansionError), "right kind of error" T.assert (err.toString().indexOf("hashcheck failure in stub import") >= 0), "right error message" cb null
[ { "context": "T /cache', ->\n beforeEach ->\n @publicKey = '''-----BEGIN PUBLIC KEY-----\nMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAILmZ+FAnHRH5uxDCjuZNf4/NO1+RlnB\nrgGbCwRSmrezo4kBnAcOEx54m18toGFLI40oHFazEgvOM3F1N3jxelkCAwEAAQ==\n-----END PUBLIC KEY-----'''\n @privateKey = '''-----BEGIN RSA PRIVATE KE", "end": 583, "score": 0.999091625213623, "start": 407, "tag": "KEY", "value": "BEGIN PUBLIC KEY-----\nMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAILmZ+FAnHRH5uxDCjuZNf4/NO1+RlnB\nrgGbCwRSmrezo4kBnAcOEx54m18toGFLI40oHFazEgvOM3F1N3jxelkCAwEAAQ==\n-----END PUBLIC KEY-----" }, { "context": "\n-----END PUBLIC KEY-----'''\n @privateKey = '''-----BEGIN RSA PRIVATE KEY-----\nMIIBOgIBAAJBAILmZ+FAnHRH5uxDCjuZNf4/NO1+RlnBrgGbCw", "end": 639, "score": 0.9486820101737976, "start": 613, "tag": "KEY", "value": "BEGIN RSA PRIVATE KEY-----" }, { "context": " @privateKey = '''-----BEGIN RSA PRIVATE KEY-----\nMIIBOgIBAAJBAILmZ+FAnHRH5uxDCjuZNf4/NO1+RlnBrgGbCwRSmrezo4kBnAcO\nEx54m18toGFLI40oHFazEgvOM3F1N3jxelkCAwEAAQJATs8rYbmFuJiFll8ybPls\nQXuKgSYScv2hpsPS2TJmhgxQHYNFGc3DDRTRkHpLLxLWOvHw2pJ8EnlLIB2Wv6Tv\n0QIhAP4MaMWkcCJNewGkrMUSiPLkMY0MDpja8rKoHTWsL9oNAiEAg+fSrLY6zB7u\nxw1jselN6/qJXeGtGtduDu5cL6ztin0CIQDO5lBV1ow0g6GQPwsuHOBH4KyyUIV6\n26YY9m2Djs4R6QIgRYAJVi0yL8kAoOriI6S9BOBeLpQxJFpsR/u5oPkps/UCICC+\nkeYaKc587IGMob72txxUbtNLXfQoU2o4+262ojUd\n-----END RSA PRIVATE KEY-----'''\n\n beforeEach ", "end": 1068, "score": 0.9982742667198181, "start": 640, "tag": "KEY", "value": "MIIBOgIBAAJBAILmZ+FAnHRH5uxDCjuZNf4/NO1+RlnBrgGbCwRSmrezo4kBnAcO\nEx54m18toGFLI40oHFazEgvOM3F1N3jxelkCAwEAAQJATs8rYbmFuJiFll8ybPls\nQXuKgSYScv2hpsPS2TJmhgxQHYNFGc3DDRTRkHpLLxLWOvHw2pJ8EnlLIB2Wv6Tv\n0QIhAP4MaMWkcCJNewGkrMUSiPLkMY0MDpja8rKoHTWsL9oNAiEAg+fSrLY6zB7u\nxw1jselN6/qJXeGtGtduDu5cL6ztin0CIQDO5lBV1ow0g6GQPwsuHOBH4KyyUIV6\n26YY9m2Djs4R6QIgRYAJVi0yL8kAoOriI6S9BOBeLpQxJFpsR/u5oPkps/UCICC+\nkeYaKc587IGMob72txxUbtNLXfQoU2o4+262oj" }, { "context": "h: 'foo'\n httpSignature:\n keyId: 'meshblu-webhook-key'\n key: @privateKey\n headers: [ ", "end": 2135, "score": 0.8320760726928711, "start": 2116, "tag": "KEY", "value": "meshblu-webhook-key" }, { "context": "h: 'foo'\n httpSignature:\n keyId: 'meshblu-webhook-key'\n key: @privateKey\n headers: [ ", "end": 3083, "score": 0.9978957176208496, "start": 3064, "tag": "KEY", "value": "meshblu-webhook-key" }, { "context": ", ->\n beforeEach (done) ->\n @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', done\n return\n\n b", "end": 3685, "score": 0.9786784052848816, "start": 3663, "tag": "KEY", "value": "7c32ca0-ae2b-4983-bcd4" }, { "context": "ne) ->\n @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', done\n return\n\n beforeE", "end": 3691, "score": 0.6941367983818054, "start": 3686, "tag": "KEY", "value": "9ce55" }, { "context": " @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', done\n return\n\n beforeEach (d", "end": 3697, "score": 0.7249608635902405, "start": 3693, "tag": "KEY", "value": "fe3c" }, { "context": "reEach (done) ->\n @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/another/path', done\n retur", "end": 3792, "score": 0.6709340214729309, "start": 3788, "tag": "KEY", "value": "4983" }, { "context": "h (done) ->\n @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/another/path', done\n return\n\n ", "end": 3797, "score": 0.5982601642608643, "start": 3793, "tag": "KEY", "value": "bcd4" }, { "context": "h: 'bar'\n httpSignature:\n keyId: 'meshblu-webhook-key'\n key: @privateKey\n headers: [ ", "end": 4231, "score": 0.979062557220459, "start": 4212, "tag": "KEY", "value": "meshblu-webhook-key" } ]
test/integration/post-cache-spec.coffee
octoblu/meshblu-ref-cache-service
0
{beforeEach, afterEach, describe, it} = global {expect} = require 'chai' sinon = require 'sinon' request = require 'request' enableDestroy = require 'server-destroy' Server = require '../../src/server' Redis = require 'ioredis' RedisNS = require '@octoblu/redis-ns' UUID = require 'uuid' describe 'POST /cache', -> beforeEach -> @publicKey = '''-----BEGIN PUBLIC KEY----- MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAILmZ+FAnHRH5uxDCjuZNf4/NO1+RlnB rgGbCwRSmrezo4kBnAcOEx54m18toGFLI40oHFazEgvOM3F1N3jxelkCAwEAAQ== -----END PUBLIC KEY-----''' @privateKey = '''-----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAILmZ+FAnHRH5uxDCjuZNf4/NO1+RlnBrgGbCwRSmrezo4kBnAcO Ex54m18toGFLI40oHFazEgvOM3F1N3jxelkCAwEAAQJATs8rYbmFuJiFll8ybPls QXuKgSYScv2hpsPS2TJmhgxQHYNFGc3DDRTRkHpLLxLWOvHw2pJ8EnlLIB2Wv6Tv 0QIhAP4MaMWkcCJNewGkrMUSiPLkMY0MDpja8rKoHTWsL9oNAiEAg+fSrLY6zB7u xw1jselN6/qJXeGtGtduDu5cL6ztin0CIQDO5lBV1ow0g6GQPwsuHOBH4KyyUIV6 26YY9m2Djs4R6QIgRYAJVi0yL8kAoOriI6S9BOBeLpQxJFpsR/u5oPkps/UCICC+ keYaKc587IGMob72txxUbtNLXfQoU2o4+262ojUd -----END RSA PRIVATE KEY-----''' beforeEach (done) -> @namespace = "test:ref-cache:#{UUID.v4()}" @redisUri = 'localhost' @logFn = sinon.spy() serverOptions = { port: undefined disableLogging: true @logFn @publicKey @redisUri @namespace } @server = new Server serverOptions @server.run => @serverPort = @server.address().port done() beforeEach (done) -> @client = new RedisNS @namespace, new Redis @redisUri, dropBufferSupport: true @client.on 'ready', done afterEach -> @server.destroy() describe 'posting a single key', -> beforeEach (done) -> @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', done return beforeEach (done) -> options = headers: 'X-MESHBLU-UUID': '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1' uri: '/cache?key=some.path' baseUrl: "http://localhost:#{@serverPort}" json: some: path: 'foo' httpSignature: keyId: 'meshblu-webhook-key' key: @privateKey headers: [ 'date', 'X-MESHBLU-UUID' ] request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 it 'should create a cache entry', (done) -> @client.get '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', (error, data) => return done error if error? expect(data).to.equal '"foo"' done() return # promises describe 'caching the whole device', -> beforeEach (done) -> @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/_', done return beforeEach (done) -> options = headers: 'X-MESHBLU-UUID': '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1' uri: '/cache?key=_' baseUrl: "http://localhost:#{@serverPort}" json: some: path: 'foo' httpSignature: keyId: 'meshblu-webhook-key' key: @privateKey headers: [ 'date', 'X-MESHBLU-UUID' ] request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 it 'should create a cache file', (done) -> @client.get '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/_', (error, data) => return done error if error? expect(JSON.parse data).to.deep.equal some: path: 'foo' done() return # promises describe 'posting two keys', -> beforeEach (done) -> @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', done return beforeEach (done) -> @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/another/path', done return beforeEach (done) -> options = headers: 'X-MESHBLU-UUID': '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1' uri: '/cache?key=some.path&key=another.path' baseUrl: "http://localhost:#{@serverPort}" json: some: path: 'foo' another: path: 'bar' httpSignature: keyId: 'meshblu-webhook-key' key: @privateKey headers: [ 'date', 'X-MESHBLU-UUID' ] request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 it 'should create a cache entry', (done) -> @client.get '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', (error, data) => return done error if error? expect(data).to.equal '"foo"' done() return # promises it 'should create another cache file', (done) -> @client.get '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/another/path', (error, data) => return done error if error? expect(data).to.equal '"bar"' done() return # promises
199880
{beforeEach, afterEach, describe, it} = global {expect} = require 'chai' sinon = require 'sinon' request = require 'request' enableDestroy = require 'server-destroy' Server = require '../../src/server' Redis = require 'ioredis' RedisNS = require '@octoblu/redis-ns' UUID = require 'uuid' describe 'POST /cache', -> beforeEach -> @publicKey = '''-----<KEY>''' @privateKey = '''-----<KEY> <KEY>Ud -----END RSA PRIVATE KEY-----''' beforeEach (done) -> @namespace = "test:ref-cache:#{UUID.v4()}" @redisUri = 'localhost' @logFn = sinon.spy() serverOptions = { port: undefined disableLogging: true @logFn @publicKey @redisUri @namespace } @server = new Server serverOptions @server.run => @serverPort = @server.address().port done() beforeEach (done) -> @client = new RedisNS @namespace, new Redis @redisUri, dropBufferSupport: true @client.on 'ready', done afterEach -> @server.destroy() describe 'posting a single key', -> beforeEach (done) -> @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', done return beforeEach (done) -> options = headers: 'X-MESHBLU-UUID': '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1' uri: '/cache?key=some.path' baseUrl: "http://localhost:#{@serverPort}" json: some: path: 'foo' httpSignature: keyId: '<KEY>' key: @privateKey headers: [ 'date', 'X-MESHBLU-UUID' ] request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 it 'should create a cache entry', (done) -> @client.get '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', (error, data) => return done error if error? expect(data).to.equal '"foo"' done() return # promises describe 'caching the whole device', -> beforeEach (done) -> @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/_', done return beforeEach (done) -> options = headers: 'X-MESHBLU-UUID': '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1' uri: '/cache?key=_' baseUrl: "http://localhost:#{@serverPort}" json: some: path: 'foo' httpSignature: keyId: '<KEY>' key: @privateKey headers: [ 'date', 'X-MESHBLU-UUID' ] request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 it 'should create a cache file', (done) -> @client.get '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/_', (error, data) => return done error if error? expect(JSON.parse data).to.deep.equal some: path: 'foo' done() return # promises describe 'posting two keys', -> beforeEach (done) -> @client.del '8<KEY>-<KEY>00<KEY>1/some/path', done return beforeEach (done) -> @client.del '87c32ca0-ae2b-<KEY>-<KEY>-9ce5500fe3c1/another/path', done return beforeEach (done) -> options = headers: 'X-MESHBLU-UUID': '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1' uri: '/cache?key=some.path&key=another.path' baseUrl: "http://localhost:#{@serverPort}" json: some: path: 'foo' another: path: 'bar' httpSignature: keyId: '<KEY>' key: @privateKey headers: [ 'date', 'X-MESHBLU-UUID' ] request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 it 'should create a cache entry', (done) -> @client.get '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', (error, data) => return done error if error? expect(data).to.equal '"foo"' done() return # promises it 'should create another cache file', (done) -> @client.get '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/another/path', (error, data) => return done error if error? expect(data).to.equal '"bar"' done() return # promises
true
{beforeEach, afterEach, describe, it} = global {expect} = require 'chai' sinon = require 'sinon' request = require 'request' enableDestroy = require 'server-destroy' Server = require '../../src/server' Redis = require 'ioredis' RedisNS = require '@octoblu/redis-ns' UUID = require 'uuid' describe 'POST /cache', -> beforeEach -> @publicKey = '''-----PI:KEY:<KEY>END_PI''' @privateKey = '''-----PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PIUd -----END RSA PRIVATE KEY-----''' beforeEach (done) -> @namespace = "test:ref-cache:#{UUID.v4()}" @redisUri = 'localhost' @logFn = sinon.spy() serverOptions = { port: undefined disableLogging: true @logFn @publicKey @redisUri @namespace } @server = new Server serverOptions @server.run => @serverPort = @server.address().port done() beforeEach (done) -> @client = new RedisNS @namespace, new Redis @redisUri, dropBufferSupport: true @client.on 'ready', done afterEach -> @server.destroy() describe 'posting a single key', -> beforeEach (done) -> @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', done return beforeEach (done) -> options = headers: 'X-MESHBLU-UUID': '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1' uri: '/cache?key=some.path' baseUrl: "http://localhost:#{@serverPort}" json: some: path: 'foo' httpSignature: keyId: 'PI:KEY:<KEY>END_PI' key: @privateKey headers: [ 'date', 'X-MESHBLU-UUID' ] request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 it 'should create a cache entry', (done) -> @client.get '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', (error, data) => return done error if error? expect(data).to.equal '"foo"' done() return # promises describe 'caching the whole device', -> beforeEach (done) -> @client.del '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/_', done return beforeEach (done) -> options = headers: 'X-MESHBLU-UUID': '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1' uri: '/cache?key=_' baseUrl: "http://localhost:#{@serverPort}" json: some: path: 'foo' httpSignature: keyId: 'PI:KEY:<KEY>END_PI' key: @privateKey headers: [ 'date', 'X-MESHBLU-UUID' ] request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 it 'should create a cache file', (done) -> @client.get '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/_', (error, data) => return done error if error? expect(JSON.parse data).to.deep.equal some: path: 'foo' done() return # promises describe 'posting two keys', -> beforeEach (done) -> @client.del '8PI:KEY:<KEY>END_PI-PI:KEY:<KEY>END_PI00PI:KEY:<KEY>END_PI1/some/path', done return beforeEach (done) -> @client.del '87c32ca0-ae2b-PI:KEY:<KEY>END_PI-PI:KEY:<KEY>END_PI-9ce5500fe3c1/another/path', done return beforeEach (done) -> options = headers: 'X-MESHBLU-UUID': '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1' uri: '/cache?key=some.path&key=another.path' baseUrl: "http://localhost:#{@serverPort}" json: some: path: 'foo' another: path: 'bar' httpSignature: keyId: 'PI:KEY:<KEY>END_PI' key: @privateKey headers: [ 'date', 'X-MESHBLU-UUID' ] request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 it 'should create a cache entry', (done) -> @client.get '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/some/path', (error, data) => return done error if error? expect(data).to.equal '"foo"' done() return # promises it 'should create another cache file', (done) -> @client.get '87c32ca0-ae2b-4983-bcd4-9ce5500fe3c1/another/path', (error, data) => return done error if error? expect(data).to.equal '"bar"' done() return # promises
[ { "context": "scope = $rootScope\n scope.model =\n name: \"username\"\n email: \"me@home.com\"\n number: 150\n\n ", "end": 1215, "score": 0.9960864782333374, "start": 1207, "tag": "USERNAME", "value": "username" }, { "context": "cope.model =\n name: \"username\"\n email: \"me@home.com\"\n number: 150\n\n $compile(element)(scope)\n", "end": 1242, "score": 0.9999178647994995, "start": 1231, "tag": "EMAIL", "value": "me@home.com" } ]
src/input-errors/input-errors_test.coffee
bsm/angular-ui-bootstrap-more
0
describe 'provider: bsInputErrorsConfig', -> subject = null beforeEach module('ui.bootstrap.more.input-errors') beforeEach inject((bsInputErrorsConfig) -> subject = bsInputErrorsConfig ) it 'should have config', -> expect(subject.messages).toBeDefined() expect(Object.keys(subject.messages).length).toEqual(9) describe 'directive: bsInputErrors', -> scope = element = null beforeEach module('ui.bootstrap.more.input-errors') beforeEach inject(($rootScope, $compile) -> element = angular.element """ <form name="form"> <input type="name" ng-model="model.name" name="name" required minlength="3" ng-maxlength="30" pattern="^[a-z]+$" /> <div bs-input-errors messages="{pattern: 'lowercase only'}" name="name"></div> <input type="email" ng-model="model.email" name="email" required /> <bs-input-errors messages="{required: 'not set'}" name="email"></bs-input-errors> <div class="form-group"> <input type="number" ng-model="model.number" name="number" min="100" max="200" /> <div bs-input-errors name="number"></div> </div> </form> """ scope = $rootScope scope.model = name: "username" email: "me@home.com" number: 150 $compile(element)(scope) scope.$digest() ) select = (q) -> el = element[0].querySelector(q) angular.element(el) errorsOn = (name) -> select("[name='#{name}'] p.help-block") it 'should render', -> expect(element.children().length).toEqual(5) it 'should validate required', -> scope.form.name.$setViewValue('') expect(errorsOn('name').length).toEqual(1) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('name').text()).toEqual('is required') it 'should validate minlength', -> scope.form.name.$setViewValue('ab') expect(errorsOn('name').length).toEqual(1) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('name').text()).toEqual('too short, minimum 3 characters') it 'should validate maxlength', -> scope.form.name.$setViewValue('abcdefghijabcdefghijabcdefghijabcdefghij') expect(errorsOn('name').length).toEqual(1) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('name').text()).toEqual('too long, maximum 30 characters') it 'should validate pattern', -> scope.form.name.$setViewValue('ABCD') expect(errorsOn('name').length).toEqual(1) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('name').text()).toEqual('lowercase only') it 'should validate emails', -> scope.form.email.$setViewValue('BADEMAIL') expect(errorsOn('name').length).toEqual(0) expect(errorsOn('email').length).toEqual(1) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('email').text()).toEqual('is not a valid email address') it 'should validate numbers', -> scope.form.number.$setViewValue('NOTNUM') expect(errorsOn('name').length).toEqual(0) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(1) expect(errorsOn('number').text()).toEqual('is not a number') scope.form.number.$setViewValue('90') expect(errorsOn('number').text()).toEqual('must be at least 100') scope.form.number.$setViewValue('210') expect(errorsOn('number').text()).toEqual('must not be over 200') scope.form.number.$setViewValue('150') expect(errorsOn('number').length).toEqual(0) it 'should allow custom error message injection', -> scope.form.number.errorMessages['number'] = 'bad number' scope.form.number.errorMessages['custom'] = 'not a good number' scope.$apply -> scope.form.number.$setViewValue('NOTNUM') expect(errorsOn('number').length).toEqual(1) expect(errorsOn('number').text()).toEqual('bad number') scope.$apply -> scope.form.number.$setViewValue('150') scope.form.number.$error.custom = true expect(errorsOn('number').length).toEqual(1) expect(errorsOn('number').text()).toEqual('not a good number') it 'should toggle has-success/error', -> classes = -> select('.form-group')[0].getAttribute('class') expect(classes()).toBe("form-group") scope.$apply -> scope.form.number.$setViewValue('50') scope.form.number.$setTouched() expect(classes()).toBe("form-group has-error") scope.$apply -> scope.form.number.$setViewValue('120') scope.form.number.$setTouched() expect(classes()).toBe("form-group has-success") scope.$apply -> scope.form.number.$setViewValue('150') scope.form.number.$setPristine() expect(classes()).toBe("form-group")
2402
describe 'provider: bsInputErrorsConfig', -> subject = null beforeEach module('ui.bootstrap.more.input-errors') beforeEach inject((bsInputErrorsConfig) -> subject = bsInputErrorsConfig ) it 'should have config', -> expect(subject.messages).toBeDefined() expect(Object.keys(subject.messages).length).toEqual(9) describe 'directive: bsInputErrors', -> scope = element = null beforeEach module('ui.bootstrap.more.input-errors') beforeEach inject(($rootScope, $compile) -> element = angular.element """ <form name="form"> <input type="name" ng-model="model.name" name="name" required minlength="3" ng-maxlength="30" pattern="^[a-z]+$" /> <div bs-input-errors messages="{pattern: 'lowercase only'}" name="name"></div> <input type="email" ng-model="model.email" name="email" required /> <bs-input-errors messages="{required: 'not set'}" name="email"></bs-input-errors> <div class="form-group"> <input type="number" ng-model="model.number" name="number" min="100" max="200" /> <div bs-input-errors name="number"></div> </div> </form> """ scope = $rootScope scope.model = name: "username" email: "<EMAIL>" number: 150 $compile(element)(scope) scope.$digest() ) select = (q) -> el = element[0].querySelector(q) angular.element(el) errorsOn = (name) -> select("[name='#{name}'] p.help-block") it 'should render', -> expect(element.children().length).toEqual(5) it 'should validate required', -> scope.form.name.$setViewValue('') expect(errorsOn('name').length).toEqual(1) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('name').text()).toEqual('is required') it 'should validate minlength', -> scope.form.name.$setViewValue('ab') expect(errorsOn('name').length).toEqual(1) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('name').text()).toEqual('too short, minimum 3 characters') it 'should validate maxlength', -> scope.form.name.$setViewValue('abcdefghijabcdefghijabcdefghijabcdefghij') expect(errorsOn('name').length).toEqual(1) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('name').text()).toEqual('too long, maximum 30 characters') it 'should validate pattern', -> scope.form.name.$setViewValue('ABCD') expect(errorsOn('name').length).toEqual(1) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('name').text()).toEqual('lowercase only') it 'should validate emails', -> scope.form.email.$setViewValue('BADEMAIL') expect(errorsOn('name').length).toEqual(0) expect(errorsOn('email').length).toEqual(1) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('email').text()).toEqual('is not a valid email address') it 'should validate numbers', -> scope.form.number.$setViewValue('NOTNUM') expect(errorsOn('name').length).toEqual(0) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(1) expect(errorsOn('number').text()).toEqual('is not a number') scope.form.number.$setViewValue('90') expect(errorsOn('number').text()).toEqual('must be at least 100') scope.form.number.$setViewValue('210') expect(errorsOn('number').text()).toEqual('must not be over 200') scope.form.number.$setViewValue('150') expect(errorsOn('number').length).toEqual(0) it 'should allow custom error message injection', -> scope.form.number.errorMessages['number'] = 'bad number' scope.form.number.errorMessages['custom'] = 'not a good number' scope.$apply -> scope.form.number.$setViewValue('NOTNUM') expect(errorsOn('number').length).toEqual(1) expect(errorsOn('number').text()).toEqual('bad number') scope.$apply -> scope.form.number.$setViewValue('150') scope.form.number.$error.custom = true expect(errorsOn('number').length).toEqual(1) expect(errorsOn('number').text()).toEqual('not a good number') it 'should toggle has-success/error', -> classes = -> select('.form-group')[0].getAttribute('class') expect(classes()).toBe("form-group") scope.$apply -> scope.form.number.$setViewValue('50') scope.form.number.$setTouched() expect(classes()).toBe("form-group has-error") scope.$apply -> scope.form.number.$setViewValue('120') scope.form.number.$setTouched() expect(classes()).toBe("form-group has-success") scope.$apply -> scope.form.number.$setViewValue('150') scope.form.number.$setPristine() expect(classes()).toBe("form-group")
true
describe 'provider: bsInputErrorsConfig', -> subject = null beforeEach module('ui.bootstrap.more.input-errors') beforeEach inject((bsInputErrorsConfig) -> subject = bsInputErrorsConfig ) it 'should have config', -> expect(subject.messages).toBeDefined() expect(Object.keys(subject.messages).length).toEqual(9) describe 'directive: bsInputErrors', -> scope = element = null beforeEach module('ui.bootstrap.more.input-errors') beforeEach inject(($rootScope, $compile) -> element = angular.element """ <form name="form"> <input type="name" ng-model="model.name" name="name" required minlength="3" ng-maxlength="30" pattern="^[a-z]+$" /> <div bs-input-errors messages="{pattern: 'lowercase only'}" name="name"></div> <input type="email" ng-model="model.email" name="email" required /> <bs-input-errors messages="{required: 'not set'}" name="email"></bs-input-errors> <div class="form-group"> <input type="number" ng-model="model.number" name="number" min="100" max="200" /> <div bs-input-errors name="number"></div> </div> </form> """ scope = $rootScope scope.model = name: "username" email: "PI:EMAIL:<EMAIL>END_PI" number: 150 $compile(element)(scope) scope.$digest() ) select = (q) -> el = element[0].querySelector(q) angular.element(el) errorsOn = (name) -> select("[name='#{name}'] p.help-block") it 'should render', -> expect(element.children().length).toEqual(5) it 'should validate required', -> scope.form.name.$setViewValue('') expect(errorsOn('name').length).toEqual(1) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('name').text()).toEqual('is required') it 'should validate minlength', -> scope.form.name.$setViewValue('ab') expect(errorsOn('name').length).toEqual(1) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('name').text()).toEqual('too short, minimum 3 characters') it 'should validate maxlength', -> scope.form.name.$setViewValue('abcdefghijabcdefghijabcdefghijabcdefghij') expect(errorsOn('name').length).toEqual(1) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('name').text()).toEqual('too long, maximum 30 characters') it 'should validate pattern', -> scope.form.name.$setViewValue('ABCD') expect(errorsOn('name').length).toEqual(1) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('name').text()).toEqual('lowercase only') it 'should validate emails', -> scope.form.email.$setViewValue('BADEMAIL') expect(errorsOn('name').length).toEqual(0) expect(errorsOn('email').length).toEqual(1) expect(errorsOn('number').length).toEqual(0) expect(errorsOn('email').text()).toEqual('is not a valid email address') it 'should validate numbers', -> scope.form.number.$setViewValue('NOTNUM') expect(errorsOn('name').length).toEqual(0) expect(errorsOn('email').length).toEqual(0) expect(errorsOn('number').length).toEqual(1) expect(errorsOn('number').text()).toEqual('is not a number') scope.form.number.$setViewValue('90') expect(errorsOn('number').text()).toEqual('must be at least 100') scope.form.number.$setViewValue('210') expect(errorsOn('number').text()).toEqual('must not be over 200') scope.form.number.$setViewValue('150') expect(errorsOn('number').length).toEqual(0) it 'should allow custom error message injection', -> scope.form.number.errorMessages['number'] = 'bad number' scope.form.number.errorMessages['custom'] = 'not a good number' scope.$apply -> scope.form.number.$setViewValue('NOTNUM') expect(errorsOn('number').length).toEqual(1) expect(errorsOn('number').text()).toEqual('bad number') scope.$apply -> scope.form.number.$setViewValue('150') scope.form.number.$error.custom = true expect(errorsOn('number').length).toEqual(1) expect(errorsOn('number').text()).toEqual('not a good number') it 'should toggle has-success/error', -> classes = -> select('.form-group')[0].getAttribute('class') expect(classes()).toBe("form-group") scope.$apply -> scope.form.number.$setViewValue('50') scope.form.number.$setTouched() expect(classes()).toBe("form-group has-error") scope.$apply -> scope.form.number.$setViewValue('120') scope.form.number.$setTouched() expect(classes()).toBe("form-group has-success") scope.$apply -> scope.form.number.$setViewValue('150') scope.form.number.$setPristine() expect(classes()).toBe("form-group")
[ { "context": "RL, currently just for debugging\n#\n#\n# Author:\n# Chris Coveney <xkickflip@gmail.com>\n\nmodule.exports = (robot) -", "end": 600, "score": 0.9998012781143188, "start": 587, "tag": "NAME", "value": "Chris Coveney" }, { "context": "st for debugging\n#\n#\n# Author:\n# Chris Coveney <xkickflip@gmail.com>\n\nmodule.exports = (robot) ->\n\n # ENV variable f", "end": 621, "score": 0.9999313354492188, "start": 602, "tag": "EMAIL", "value": "xkickflip@gmail.com" } ]
node_modules/hubot-jira-linkifier/src/jira-linkifier.coffee
grokify/glipbot-demos-enterprise
0
# Description # Hubot listens for a list of your Jira project codes and responds with full clickable links to the tickets # that are generated from the configured Jira base url. # # Configuration: # HUBOT_JIRA_LINKIFIER_JIRA_URL # HUBOT_JIRA_LINKIFIER_PROJECT_PREFIXES # # Commands: # hubot jl url - Responds with the configured Jira base URL # hubot jl prefixes - Responds with the configured Jira project prefixes to build URLs for e.g. "DEV" for DEV-111 # hubot jl regex - Responds with the configured Jira base URL, currently just for debugging # # # Author: # Chris Coveney <xkickflip@gmail.com> module.exports = (robot) -> # ENV variable for list of project prefixes prefixes = process.env.HUBOT_JIRA_LINKIFIER_PROJECT_PREFIXES?.split(',') || [] # Base URL for your JIRA install. Strip trailing slash if it's included jiraUrl = process.env.HUBOT_JIRA_LINKIFIER_JIRA_URL || "" # Strip leading & trailing whitespace & trailing / jiraUrl = jiraUrl.replace /^\s+|\s+$|\/\s*$/g, "" ticketRegExp = new RegExp "(^|\\s+)(#{prefixes.join('|')})-[0-9]+($|\\s+)", "gi" robot.hear ticketRegExp, (res) -> for ticketMatch in res.match res.send "#{jiraUrl}/browse/#{ticketMatch.trim().toUpperCase()}" # TODO: debug print the generated regex, remove me robot.respond /jl regexp/i, (res) -> res.send ticketRegExp # "jl url": respond with the configured Jira base url robot.respond /jl url/i, (res) -> res.send jiraUrl # "jl prefixes": respond with all current Jira prefixes that will be matched robot.respond /jl prefixes/i, (res) -> if prefixes.length == 0 res.send "Jira Prefix list is empty." else res.send "Currently matching Jira project prefixes: #{prefixes.join(', ')}"
10197
# Description # Hubot listens for a list of your Jira project codes and responds with full clickable links to the tickets # that are generated from the configured Jira base url. # # Configuration: # HUBOT_JIRA_LINKIFIER_JIRA_URL # HUBOT_JIRA_LINKIFIER_PROJECT_PREFIXES # # Commands: # hubot jl url - Responds with the configured Jira base URL # hubot jl prefixes - Responds with the configured Jira project prefixes to build URLs for e.g. "DEV" for DEV-111 # hubot jl regex - Responds with the configured Jira base URL, currently just for debugging # # # Author: # <NAME> <<EMAIL>> module.exports = (robot) -> # ENV variable for list of project prefixes prefixes = process.env.HUBOT_JIRA_LINKIFIER_PROJECT_PREFIXES?.split(',') || [] # Base URL for your JIRA install. Strip trailing slash if it's included jiraUrl = process.env.HUBOT_JIRA_LINKIFIER_JIRA_URL || "" # Strip leading & trailing whitespace & trailing / jiraUrl = jiraUrl.replace /^\s+|\s+$|\/\s*$/g, "" ticketRegExp = new RegExp "(^|\\s+)(#{prefixes.join('|')})-[0-9]+($|\\s+)", "gi" robot.hear ticketRegExp, (res) -> for ticketMatch in res.match res.send "#{jiraUrl}/browse/#{ticketMatch.trim().toUpperCase()}" # TODO: debug print the generated regex, remove me robot.respond /jl regexp/i, (res) -> res.send ticketRegExp # "jl url": respond with the configured Jira base url robot.respond /jl url/i, (res) -> res.send jiraUrl # "jl prefixes": respond with all current Jira prefixes that will be matched robot.respond /jl prefixes/i, (res) -> if prefixes.length == 0 res.send "Jira Prefix list is empty." else res.send "Currently matching Jira project prefixes: #{prefixes.join(', ')}"
true
# Description # Hubot listens for a list of your Jira project codes and responds with full clickable links to the tickets # that are generated from the configured Jira base url. # # Configuration: # HUBOT_JIRA_LINKIFIER_JIRA_URL # HUBOT_JIRA_LINKIFIER_PROJECT_PREFIXES # # Commands: # hubot jl url - Responds with the configured Jira base URL # hubot jl prefixes - Responds with the configured Jira project prefixes to build URLs for e.g. "DEV" for DEV-111 # hubot jl regex - Responds with the configured Jira base URL, currently just for debugging # # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> module.exports = (robot) -> # ENV variable for list of project prefixes prefixes = process.env.HUBOT_JIRA_LINKIFIER_PROJECT_PREFIXES?.split(',') || [] # Base URL for your JIRA install. Strip trailing slash if it's included jiraUrl = process.env.HUBOT_JIRA_LINKIFIER_JIRA_URL || "" # Strip leading & trailing whitespace & trailing / jiraUrl = jiraUrl.replace /^\s+|\s+$|\/\s*$/g, "" ticketRegExp = new RegExp "(^|\\s+)(#{prefixes.join('|')})-[0-9]+($|\\s+)", "gi" robot.hear ticketRegExp, (res) -> for ticketMatch in res.match res.send "#{jiraUrl}/browse/#{ticketMatch.trim().toUpperCase()}" # TODO: debug print the generated regex, remove me robot.respond /jl regexp/i, (res) -> res.send ticketRegExp # "jl url": respond with the configured Jira base url robot.respond /jl url/i, (res) -> res.send jiraUrl # "jl prefixes": respond with all current Jira prefixes that will be matched robot.respond /jl prefixes/i, (res) -> if prefixes.length == 0 res.send "Jira Prefix list is empty." else res.send "Currently matching Jira project prefixes: #{prefixes.join(', ')}"
[ { "context": " blogName: \"yahoo.tumblr.com\"\n appKey: \"NOTHING\"\n debug: false\n\n # Merge default settings", "end": 155, "score": 0.9499258995056152, "start": 148, "tag": "KEY", "value": "NOTHING" } ]
jQuery.tumblr-random-posts.coffee
razagill/tumblr-random-posts
5
$ = jQuery $.fn.extend tumblrRandomPosts: (options) -> # Default settings settings = blogName: "yahoo.tumblr.com" appKey: "NOTHING" debug: false # Merge default settings with options. settings = $.extend settings, options # Simple logger. log = (msg) -> console?.log msg if settings.debug return @each ()-> self = this $.ajax "http://api.tumblr.com/v2/blog/#{settings.blogName}/posts?api_key=#{settings.appKey}", type: 'GET' dataType: 'jsonp' data: { get_param: 'value', type: 'text' } success: (data, textStatus, jqXHR) -> console.log data random_number = Math.floor(Math.random() * data.response.total_posts) $.ajax "http://api.tumblr.com/v2/blog/#{settings.blogName}/posts?api_key=#{settings.appKey}", type: 'GET' dataType: 'jsonp' data: {get_param: 'value', offset: random_number,limit: '1',type: 'text'} success: (data2, textStatus, jqXHR) -> content = data2.response.posts[0].body $(self).append("<div>" + content + "</div>") console.log data2 log "BlogName is: #{settings.blogName}"
42570
$ = jQuery $.fn.extend tumblrRandomPosts: (options) -> # Default settings settings = blogName: "yahoo.tumblr.com" appKey: "<KEY>" debug: false # Merge default settings with options. settings = $.extend settings, options # Simple logger. log = (msg) -> console?.log msg if settings.debug return @each ()-> self = this $.ajax "http://api.tumblr.com/v2/blog/#{settings.blogName}/posts?api_key=#{settings.appKey}", type: 'GET' dataType: 'jsonp' data: { get_param: 'value', type: 'text' } success: (data, textStatus, jqXHR) -> console.log data random_number = Math.floor(Math.random() * data.response.total_posts) $.ajax "http://api.tumblr.com/v2/blog/#{settings.blogName}/posts?api_key=#{settings.appKey}", type: 'GET' dataType: 'jsonp' data: {get_param: 'value', offset: random_number,limit: '1',type: 'text'} success: (data2, textStatus, jqXHR) -> content = data2.response.posts[0].body $(self).append("<div>" + content + "</div>") console.log data2 log "BlogName is: #{settings.blogName}"
true
$ = jQuery $.fn.extend tumblrRandomPosts: (options) -> # Default settings settings = blogName: "yahoo.tumblr.com" appKey: "PI:KEY:<KEY>END_PI" debug: false # Merge default settings with options. settings = $.extend settings, options # Simple logger. log = (msg) -> console?.log msg if settings.debug return @each ()-> self = this $.ajax "http://api.tumblr.com/v2/blog/#{settings.blogName}/posts?api_key=#{settings.appKey}", type: 'GET' dataType: 'jsonp' data: { get_param: 'value', type: 'text' } success: (data, textStatus, jqXHR) -> console.log data random_number = Math.floor(Math.random() * data.response.total_posts) $.ajax "http://api.tumblr.com/v2/blog/#{settings.blogName}/posts?api_key=#{settings.appKey}", type: 'GET' dataType: 'jsonp' data: {get_param: 'value', offset: random_number,limit: '1',type: 'text'} success: (data2, textStatus, jqXHR) -> content = data2.response.posts[0].body $(self).append("<div>" + content + "</div>") console.log data2 log "BlogName is: #{settings.blogName}"
[ { "context": "###\n * 测试\n * @author jackieLin <dashi_lin@163.com>\n###\n\n'use strict'\n\nrequire 's", "end": 30, "score": 0.9284088611602783, "start": 21, "tag": "NAME", "value": "jackieLin" }, { "context": "###\n * 测试\n * @author jackieLin <dashi_lin@163.com>\n###\n\n'use strict'\n\nrequire 'should'\nstore = requ", "end": 49, "score": 0.9999276995658875, "start": 32, "tag": "EMAIL", "value": "dashi_lin@163.com" } ]
test/test.coffee
JackieLin/store
0
### * 测试 * @author jackieLin <dashi_lin@163.com> ### 'use strict' require 'should' store = require '../dist/store' describe '测试 store', -> ### * 更新数据 ### it '#updateall()', -> store.updateAll() ### * 测试删除方法 ### it '#destory()', -> Object.keys(store.destroy()).length.should.equal 0
213248
### * 测试 * @author <NAME> <<EMAIL>> ### 'use strict' require 'should' store = require '../dist/store' describe '测试 store', -> ### * 更新数据 ### it '#updateall()', -> store.updateAll() ### * 测试删除方法 ### it '#destory()', -> Object.keys(store.destroy()).length.should.equal 0
true
### * 测试 * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### 'use strict' require 'should' store = require '../dist/store' describe '测试 store', -> ### * 更新数据 ### it '#updateall()', -> store.updateAll() ### * 测试删除方法 ### it '#destory()', -> Object.keys(store.destroy()).length.should.equal 0
[ { "context": "can be an array or string, see https://github.com/docpad/docpad-plugin-sass/pull/26\n\n\t\t\t\t# Sourcemaps or s", "end": 2696, "score": 0.9895913600921631, "start": 2690, "tag": "USERNAME", "value": "docpad" }, { "context": "\t\t\t\t\tcommand.push('--require')\n\t\t\t\t\t\tcommand.push(name)\n\n\t\t\t\t# Spawn the appropriate process to render t", "end": 3714, "score": 0.8600777387619019, "start": 3710, "tag": "NAME", "value": "name" } ]
source/index.coffee
docpad/docpad-plugin-sass
0
# Export Plugin module.exports = (BasePlugin) -> # Requires safeps = require('safeps') fs = require('fs') {TaskGroup} = require('taskgroup') # Define Plugin class SassPlugin extends BasePlugin # Plugin name name: 'sass' # Plugin config # Only on the development environment use expanded, otherwise use compressed config: sassPath: null scssPath: null compass: null debugInfo: false sourcemap: false outputStyle: 'compressed' requireLibraries: null renderUnderscoreStylesheets: false environments: development: outputStyle: 'expanded' # Locale locale: sassNotInstalled: 'SASS does not appear to be available on your system' scssNotInstalled: 'SCSS does not appear to be available on your system' # Generate Before generateBefore: (opts,next) -> # Prepare config = @config # Group tasks = new TaskGroup(concurrency:0).done(next) # Determine if compass is installed unless config.compass? tasks.addTask (complete) -> safeps.getExecPath 'compass', (err,path) -> config.compass = path? return complete() # Determine sass executable path ['sass','scss'].forEach (thing) -> unless config[thing+'Path']? tasks.addTask (complete) -> safeps.getExecPath thing, (err,path) -> config[thing+'Path'] = path ? false return complete() # Fire tasks tasks.run() # Prevent underscore extendCollections: (opts) -> # Prepare config = @config docpad = @docpad # Prevent underscore files from being written if desired if config.renderUnderscoreStylesheets is false @underscoreStylesheets = docpad.getDatabase().findAllLive(filename: /^_(.*?)\.(?:scss|sass)/) @underscoreStylesheets.on 'add', (model) -> model.set({ render: false write: false }) # Render some content render: (opts,next) -> # Prepare config = @config locale = @locale {inExtension,outExtension,file} = opts # If SASS/SCSS then render if inExtension in ['sass','scss'] and outExtension in ['css',null] # Fetch useful paths fullDirPath = file.get('fullDirPath') # Prepare the command and options commandOpts = {} execPath = config[inExtension+'Path'] # Check if we have the executable for that extension return next(new Error(locale[inExtension+'NotInstalled'])) unless execPath # Set referencesOthers if this document imports, as sass concatenates files together file.setMetaDefaults('referencesOthers': true) if opts.content.indexOf('@import') isnt -1 # Build our command command = [].concat(execPath) # ^ execPath can be an array or string, see https://github.com/docpad/docpad-plugin-sass/pull/26 # Sourcemaps or stdin? if config.sourcemap command.push("#{file.attributes.fullPath}:#{file.attributes.outPath}", '--no-cache', '--update', '--sourcemap') else command.push('--no-cache', '--stdin') commandOpts.stdin = opts.content if fullDirPath command.push('--load-path') command.push(fullDirPath) unless config.requireLibraries config.requireLibraries = [] if config.loadPaths config.loadPaths.forEach (loadPath) -> command.push('--load-path') command.push(loadPath) if config.compass command.push('--compass') if config.requireLibraries.indexOf('compass') is -1 config.requireLibraries.push('compass') if config.debugInfo command.push('--debug-info') if config.outputStyle command.push('--style') command.push(config.outputStyle) if config.requireLibraries.length for name in config.requireLibraries command.push('--require') command.push(name) # Spawn the appropriate process to render the content safeps.spawn command, commandOpts, (err,stdout,stderr) -> if err err.message += '\n\n' + ((stderr || '').toString() or (stdout || '').toString()).trim() err.message += '\n\nCommand:\n' + command.join(' ') err.message += '\n\nConfiguration:\n' + (JSON.stringify(config, null, ' ')) return next(err) if config.sourcemap fs.readFile file.attributes.outPath, (err, result) -> return next(err) if ( err ) opts.content = result.toString() return next() else opts.content = stdout.toString() return next() else # Done, return back to DocPad return next()
130984
# Export Plugin module.exports = (BasePlugin) -> # Requires safeps = require('safeps') fs = require('fs') {TaskGroup} = require('taskgroup') # Define Plugin class SassPlugin extends BasePlugin # Plugin name name: 'sass' # Plugin config # Only on the development environment use expanded, otherwise use compressed config: sassPath: null scssPath: null compass: null debugInfo: false sourcemap: false outputStyle: 'compressed' requireLibraries: null renderUnderscoreStylesheets: false environments: development: outputStyle: 'expanded' # Locale locale: sassNotInstalled: 'SASS does not appear to be available on your system' scssNotInstalled: 'SCSS does not appear to be available on your system' # Generate Before generateBefore: (opts,next) -> # Prepare config = @config # Group tasks = new TaskGroup(concurrency:0).done(next) # Determine if compass is installed unless config.compass? tasks.addTask (complete) -> safeps.getExecPath 'compass', (err,path) -> config.compass = path? return complete() # Determine sass executable path ['sass','scss'].forEach (thing) -> unless config[thing+'Path']? tasks.addTask (complete) -> safeps.getExecPath thing, (err,path) -> config[thing+'Path'] = path ? false return complete() # Fire tasks tasks.run() # Prevent underscore extendCollections: (opts) -> # Prepare config = @config docpad = @docpad # Prevent underscore files from being written if desired if config.renderUnderscoreStylesheets is false @underscoreStylesheets = docpad.getDatabase().findAllLive(filename: /^_(.*?)\.(?:scss|sass)/) @underscoreStylesheets.on 'add', (model) -> model.set({ render: false write: false }) # Render some content render: (opts,next) -> # Prepare config = @config locale = @locale {inExtension,outExtension,file} = opts # If SASS/SCSS then render if inExtension in ['sass','scss'] and outExtension in ['css',null] # Fetch useful paths fullDirPath = file.get('fullDirPath') # Prepare the command and options commandOpts = {} execPath = config[inExtension+'Path'] # Check if we have the executable for that extension return next(new Error(locale[inExtension+'NotInstalled'])) unless execPath # Set referencesOthers if this document imports, as sass concatenates files together file.setMetaDefaults('referencesOthers': true) if opts.content.indexOf('@import') isnt -1 # Build our command command = [].concat(execPath) # ^ execPath can be an array or string, see https://github.com/docpad/docpad-plugin-sass/pull/26 # Sourcemaps or stdin? if config.sourcemap command.push("#{file.attributes.fullPath}:#{file.attributes.outPath}", '--no-cache', '--update', '--sourcemap') else command.push('--no-cache', '--stdin') commandOpts.stdin = opts.content if fullDirPath command.push('--load-path') command.push(fullDirPath) unless config.requireLibraries config.requireLibraries = [] if config.loadPaths config.loadPaths.forEach (loadPath) -> command.push('--load-path') command.push(loadPath) if config.compass command.push('--compass') if config.requireLibraries.indexOf('compass') is -1 config.requireLibraries.push('compass') if config.debugInfo command.push('--debug-info') if config.outputStyle command.push('--style') command.push(config.outputStyle) if config.requireLibraries.length for name in config.requireLibraries command.push('--require') command.push(<NAME>) # Spawn the appropriate process to render the content safeps.spawn command, commandOpts, (err,stdout,stderr) -> if err err.message += '\n\n' + ((stderr || '').toString() or (stdout || '').toString()).trim() err.message += '\n\nCommand:\n' + command.join(' ') err.message += '\n\nConfiguration:\n' + (JSON.stringify(config, null, ' ')) return next(err) if config.sourcemap fs.readFile file.attributes.outPath, (err, result) -> return next(err) if ( err ) opts.content = result.toString() return next() else opts.content = stdout.toString() return next() else # Done, return back to DocPad return next()
true
# Export Plugin module.exports = (BasePlugin) -> # Requires safeps = require('safeps') fs = require('fs') {TaskGroup} = require('taskgroup') # Define Plugin class SassPlugin extends BasePlugin # Plugin name name: 'sass' # Plugin config # Only on the development environment use expanded, otherwise use compressed config: sassPath: null scssPath: null compass: null debugInfo: false sourcemap: false outputStyle: 'compressed' requireLibraries: null renderUnderscoreStylesheets: false environments: development: outputStyle: 'expanded' # Locale locale: sassNotInstalled: 'SASS does not appear to be available on your system' scssNotInstalled: 'SCSS does not appear to be available on your system' # Generate Before generateBefore: (opts,next) -> # Prepare config = @config # Group tasks = new TaskGroup(concurrency:0).done(next) # Determine if compass is installed unless config.compass? tasks.addTask (complete) -> safeps.getExecPath 'compass', (err,path) -> config.compass = path? return complete() # Determine sass executable path ['sass','scss'].forEach (thing) -> unless config[thing+'Path']? tasks.addTask (complete) -> safeps.getExecPath thing, (err,path) -> config[thing+'Path'] = path ? false return complete() # Fire tasks tasks.run() # Prevent underscore extendCollections: (opts) -> # Prepare config = @config docpad = @docpad # Prevent underscore files from being written if desired if config.renderUnderscoreStylesheets is false @underscoreStylesheets = docpad.getDatabase().findAllLive(filename: /^_(.*?)\.(?:scss|sass)/) @underscoreStylesheets.on 'add', (model) -> model.set({ render: false write: false }) # Render some content render: (opts,next) -> # Prepare config = @config locale = @locale {inExtension,outExtension,file} = opts # If SASS/SCSS then render if inExtension in ['sass','scss'] and outExtension in ['css',null] # Fetch useful paths fullDirPath = file.get('fullDirPath') # Prepare the command and options commandOpts = {} execPath = config[inExtension+'Path'] # Check if we have the executable for that extension return next(new Error(locale[inExtension+'NotInstalled'])) unless execPath # Set referencesOthers if this document imports, as sass concatenates files together file.setMetaDefaults('referencesOthers': true) if opts.content.indexOf('@import') isnt -1 # Build our command command = [].concat(execPath) # ^ execPath can be an array or string, see https://github.com/docpad/docpad-plugin-sass/pull/26 # Sourcemaps or stdin? if config.sourcemap command.push("#{file.attributes.fullPath}:#{file.attributes.outPath}", '--no-cache', '--update', '--sourcemap') else command.push('--no-cache', '--stdin') commandOpts.stdin = opts.content if fullDirPath command.push('--load-path') command.push(fullDirPath) unless config.requireLibraries config.requireLibraries = [] if config.loadPaths config.loadPaths.forEach (loadPath) -> command.push('--load-path') command.push(loadPath) if config.compass command.push('--compass') if config.requireLibraries.indexOf('compass') is -1 config.requireLibraries.push('compass') if config.debugInfo command.push('--debug-info') if config.outputStyle command.push('--style') command.push(config.outputStyle) if config.requireLibraries.length for name in config.requireLibraries command.push('--require') command.push(PI:NAME:<NAME>END_PI) # Spawn the appropriate process to render the content safeps.spawn command, commandOpts, (err,stdout,stderr) -> if err err.message += '\n\n' + ((stderr || '').toString() or (stdout || '').toString()).trim() err.message += '\n\nCommand:\n' + command.join(' ') err.message += '\n\nConfiguration:\n' + (JSON.stringify(config, null, ' ')) return next(err) if config.sourcemap fs.readFile file.attributes.outPath, (err, result) -> return next(err) if ( err ) opts.content = result.toString() return next() else opts.content = stdout.toString() return next() else # Done, return back to DocPad return next()
[ { "context": "t shout down every idea I have? How about you call Bruce Springsteen and tell him to get another nickname since you're", "end": 364, "score": 0.9053998589515686, "start": 347, "tag": "NAME", "value": "Bruce Springsteen" }, { "context": "You want the mustache on, or off?\"\n#\n# Author:\n# lancepantz\n\nmodule.exports = (robot) ->\n\n robot.hear /^(did", "end": 530, "score": 0.9993998408317566, "start": 520, "tag": "USERNAME", "value": "lancepantz" }, { "context": "t shout down every idea I have? How about you call Bruce Springsteen and tell him to get another nickname since you're", "end": 916, "score": 0.9608128666877747, "start": 899, "tag": "NAME", "value": "Bruce Springsteen" } ]
src/scripts/sealab.coffee
Reelhouse/hubot-scripts
1,450
# Description: # Respond to specific phrases with quotes from Sealab 2021 # # Configuration: # None # # Commands: # /(did|can) hubot/ - "Not me! I'm gonna be an Adrienne Barbeau-bot" # energy - "I have the energy of a bear that has the energy of two bears!" # bad idea - "Oh why don't you just shout down every idea I have? How about you call Bruce Springsteen and tell him to get another nickname since you're already the Boss! Huh? Yeah? Yeah!" # change hubot - "You want the mustache on, or off?" # # Author: # lancepantz module.exports = (robot) -> robot.hear /^(did|can) hubot/i, (msg) -> msg.reply "Not me! I'm gonna be an Adrienne Barbeau-bot" robot.hear /energy/i, (msg) -> msg.reply "I have the energy of a bear that has the energy of two bears!" robot.hear /bad idea/i, (msg) -> msg.reply "Oh why don't you just shout down every idea I have? How about you call Bruce Springsteen and tell him to get another nickname since you're already the Boss! Huh? Yeah? Yeah!" robot.hear /change hubot/i, (msg) -> msg.reply "You want the mustache on, or off?"
30443
# Description: # Respond to specific phrases with quotes from Sealab 2021 # # Configuration: # None # # Commands: # /(did|can) hubot/ - "Not me! I'm gonna be an Adrienne Barbeau-bot" # energy - "I have the energy of a bear that has the energy of two bears!" # bad idea - "Oh why don't you just shout down every idea I have? How about you call <NAME> and tell him to get another nickname since you're already the Boss! Huh? Yeah? Yeah!" # change hubot - "You want the mustache on, or off?" # # Author: # lancepantz module.exports = (robot) -> robot.hear /^(did|can) hubot/i, (msg) -> msg.reply "Not me! I'm gonna be an Adrienne Barbeau-bot" robot.hear /energy/i, (msg) -> msg.reply "I have the energy of a bear that has the energy of two bears!" robot.hear /bad idea/i, (msg) -> msg.reply "Oh why don't you just shout down every idea I have? How about you call <NAME> and tell him to get another nickname since you're already the Boss! Huh? Yeah? Yeah!" robot.hear /change hubot/i, (msg) -> msg.reply "You want the mustache on, or off?"
true
# Description: # Respond to specific phrases with quotes from Sealab 2021 # # Configuration: # None # # Commands: # /(did|can) hubot/ - "Not me! I'm gonna be an Adrienne Barbeau-bot" # energy - "I have the energy of a bear that has the energy of two bears!" # bad idea - "Oh why don't you just shout down every idea I have? How about you call PI:NAME:<NAME>END_PI and tell him to get another nickname since you're already the Boss! Huh? Yeah? Yeah!" # change hubot - "You want the mustache on, or off?" # # Author: # lancepantz module.exports = (robot) -> robot.hear /^(did|can) hubot/i, (msg) -> msg.reply "Not me! I'm gonna be an Adrienne Barbeau-bot" robot.hear /energy/i, (msg) -> msg.reply "I have the energy of a bear that has the energy of two bears!" robot.hear /bad idea/i, (msg) -> msg.reply "Oh why don't you just shout down every idea I have? How about you call PI:NAME:<NAME>END_PI and tell him to get another nickname since you're already the Boss! Huh? Yeah? Yeah!" robot.hear /change hubot/i, (msg) -> msg.reply "You want the mustache on, or off?"
[ { "context": "-- monmigrate ---\n\nReleased under MIT license.\n\nby Gustavo Vargas - @xgvargas - 2018\n\nOriginal coffee code and issu", "end": 71, "score": 0.9998815655708313, "start": 57, "tag": "NAME", "value": "Gustavo Vargas" }, { "context": "\n\nReleased under MIT license.\n\nby Gustavo Vargas - @xgvargas - 2018\n\nOriginal coffee code and issues at: https", "end": 83, "score": 0.9990717172622681, "start": 74, "tag": "USERNAME", "value": "@xgvargas" }, { "context": "nal coffee code and issues at: https://github.com/xgvargas/monmigrate\n###\n\nyargs = require 'yargs'\n\nargv = y", "end": 155, "score": 0.9926522970199585, "start": 147, "tag": "USERNAME", "value": "xgvargas" } ]
src/cli.coffee
xgvargas/monmigrate
0
###! --- monmigrate --- Released under MIT license. by Gustavo Vargas - @xgvargas - 2018 Original coffee code and issues at: https://github.com/xgvargas/monmigrate ### yargs = require 'yargs' argv = yargs .wrap yargs.terminalWidth() .strict yes .alias 'h', 'help' # .config 'cfg' .usage 'Usage: $0 [options] [command]' .epilogue 'copyright 2018' .demandCommand 1 .command require './create' .command require './up' .command require './down' .options cfg: {describe:'Configuration file', default:'.monmigrate.json'} .argv # console.dir argv # if argv._.length != 1 # yargs.showHelp() # process.exit 1 # ....
129309
###! --- monmigrate --- Released under MIT license. by <NAME> - @xgvargas - 2018 Original coffee code and issues at: https://github.com/xgvargas/monmigrate ### yargs = require 'yargs' argv = yargs .wrap yargs.terminalWidth() .strict yes .alias 'h', 'help' # .config 'cfg' .usage 'Usage: $0 [options] [command]' .epilogue 'copyright 2018' .demandCommand 1 .command require './create' .command require './up' .command require './down' .options cfg: {describe:'Configuration file', default:'.monmigrate.json'} .argv # console.dir argv # if argv._.length != 1 # yargs.showHelp() # process.exit 1 # ....
true
###! --- monmigrate --- Released under MIT license. by PI:NAME:<NAME>END_PI - @xgvargas - 2018 Original coffee code and issues at: https://github.com/xgvargas/monmigrate ### yargs = require 'yargs' argv = yargs .wrap yargs.terminalWidth() .strict yes .alias 'h', 'help' # .config 'cfg' .usage 'Usage: $0 [options] [command]' .epilogue 'copyright 2018' .demandCommand 1 .command require './create' .command require './up' .command require './down' .options cfg: {describe:'Configuration file', default:'.monmigrate.json'} .argv # console.dir argv # if argv._.length != 1 # yargs.showHelp() # process.exit 1 # ....
[ { "context": "}}', ->\n valid_item =\n active: yes\n name: 'George'\n\n valid_update =\n name: 'John'\n\n invalid_it", "end": 74, "score": 0.9977479577064514, "start": 68, "tag": "NAME", "value": "George" }, { "context": "s\n name: 'George'\n\n valid_update =\n name: 'John'\n\n invalid_item = _.clone valid_item\n delete in", "end": 109, "score": 0.9998492002487183, "start": 105, "tag": "NAME", "value": "John" } ]
bin/templates/test.iced
tosadvisor/link-shortener
7
describe '/{{lower}}', -> valid_item = active: yes name: 'George' valid_update = name: 'John' invalid_item = _.clone valid_item delete invalid_item.name it 'should allow a new document to be created', (done) -> await client.post '/{{lower}}', {}, valid_item, defer e,r if e then return done e done() if r._id it 'should validate the document properly', (done) -> await client.post '/{{lower}}', {}, invalid_item, defer e,r done() if e it 'should get a list of items', (done) -> await client.get '/{{lower}}', {}, defer e,r if e then return done e done() if r.items it 'should allow one document to be viewed', (done) -> await client.get '/{{lower}}', {}, defer e,r await client.get '/{{lower}}/' + _.first(r.items)._id, {}, defer e,r if e then return done e done() if r._id it 'should allow one document to be updated', (done) -> await client.get '/{{lower}}', {}, defer e,r await client.post '/{{lower}}/' + _.first(r.items)._id, {}, valid_update, defer e,r if e then return done e done() if r._id it 'should allow a document to be deleted', (done) -> await client.get '/{{lower}}', {}, defer e,list await client.delete '/{{lower}}/' + _.first(list.items)._id, {}, defer e,r if e then return done e await client.get '/{{lower}}/' + _.first(list.items)._id, {}, defer e,r done() if r is null
51625
describe '/{{lower}}', -> valid_item = active: yes name: '<NAME>' valid_update = name: '<NAME>' invalid_item = _.clone valid_item delete invalid_item.name it 'should allow a new document to be created', (done) -> await client.post '/{{lower}}', {}, valid_item, defer e,r if e then return done e done() if r._id it 'should validate the document properly', (done) -> await client.post '/{{lower}}', {}, invalid_item, defer e,r done() if e it 'should get a list of items', (done) -> await client.get '/{{lower}}', {}, defer e,r if e then return done e done() if r.items it 'should allow one document to be viewed', (done) -> await client.get '/{{lower}}', {}, defer e,r await client.get '/{{lower}}/' + _.first(r.items)._id, {}, defer e,r if e then return done e done() if r._id it 'should allow one document to be updated', (done) -> await client.get '/{{lower}}', {}, defer e,r await client.post '/{{lower}}/' + _.first(r.items)._id, {}, valid_update, defer e,r if e then return done e done() if r._id it 'should allow a document to be deleted', (done) -> await client.get '/{{lower}}', {}, defer e,list await client.delete '/{{lower}}/' + _.first(list.items)._id, {}, defer e,r if e then return done e await client.get '/{{lower}}/' + _.first(list.items)._id, {}, defer e,r done() if r is null
true
describe '/{{lower}}', -> valid_item = active: yes name: 'PI:NAME:<NAME>END_PI' valid_update = name: 'PI:NAME:<NAME>END_PI' invalid_item = _.clone valid_item delete invalid_item.name it 'should allow a new document to be created', (done) -> await client.post '/{{lower}}', {}, valid_item, defer e,r if e then return done e done() if r._id it 'should validate the document properly', (done) -> await client.post '/{{lower}}', {}, invalid_item, defer e,r done() if e it 'should get a list of items', (done) -> await client.get '/{{lower}}', {}, defer e,r if e then return done e done() if r.items it 'should allow one document to be viewed', (done) -> await client.get '/{{lower}}', {}, defer e,r await client.get '/{{lower}}/' + _.first(r.items)._id, {}, defer e,r if e then return done e done() if r._id it 'should allow one document to be updated', (done) -> await client.get '/{{lower}}', {}, defer e,r await client.post '/{{lower}}/' + _.first(r.items)._id, {}, valid_update, defer e,r if e then return done e done() if r._id it 'should allow a document to be deleted', (done) -> await client.get '/{{lower}}', {}, defer e,list await client.delete '/{{lower}}/' + _.first(list.items)._id, {}, defer e,r if e then return done e await client.get '/{{lower}}/' + _.first(list.items)._id, {}, defer e,r done() if r is null
[ { "context": "mage*-1)\n if (damage > 0)\n @announce cb, \"Evan chilled out. His case was increased by \" + damage", "end": 375, "score": 0.9953721165657043, "start": 371, "tag": "NAME", "value": "Evan" }, { "context": "by \" + damage + \".\"\n else\n @announce cb, \"Evan tried to chill out, but he's freaking out! His ca", "end": 466, "score": 0.9958393573760986, "start": 462, "tag": "NAME", "value": "Evan" } ]
src/js/moves/cool.coffee
Huntrr/Battle-Resolution
0
$ = require './../lib/jquery.js' Move = require './../move.coffee' # PROOF BY ASSERTION IS A VALID TACTIC OF ARGUMENT module.exports = class Cool extends Move constructor: () -> super 'COOL EGO' getDamage: () -> return @user.civility use: (cb) -> super() damage = @getDamage() @user.damage(damage*-1) if (damage > 0) @announce cb, "Evan chilled out. His case was increased by " + damage + "." else @announce cb, "Evan tried to chill out, but he's freaking out! His case was decreased by " + (damage *-1) + "."
61940
$ = require './../lib/jquery.js' Move = require './../move.coffee' # PROOF BY ASSERTION IS A VALID TACTIC OF ARGUMENT module.exports = class Cool extends Move constructor: () -> super 'COOL EGO' getDamage: () -> return @user.civility use: (cb) -> super() damage = @getDamage() @user.damage(damage*-1) if (damage > 0) @announce cb, "<NAME> chilled out. His case was increased by " + damage + "." else @announce cb, "<NAME> tried to chill out, but he's freaking out! His case was decreased by " + (damage *-1) + "."
true
$ = require './../lib/jquery.js' Move = require './../move.coffee' # PROOF BY ASSERTION IS A VALID TACTIC OF ARGUMENT module.exports = class Cool extends Move constructor: () -> super 'COOL EGO' getDamage: () -> return @user.civility use: (cb) -> super() damage = @getDamage() @user.damage(damage*-1) if (damage > 0) @announce cb, "PI:NAME:<NAME>END_PI chilled out. His case was increased by " + damage + "." else @announce cb, "PI:NAME:<NAME>END_PI tried to chill out, but he's freaking out! His case was decreased by " + (damage *-1) + "."
[ { "context": "Size : (512*3)/32\n\ninputs = [\n {\n password : \"cats11\"\n salt : \"aabbccddeeff\"\n },{\n password : \"", "end": 157, "score": 0.9991316795349121, "start": 151, "tag": "PASSWORD", "value": "cats11" }, { "context": "\"\n salt : \"aabbccddeeff\"\n },{\n password : \"yo ho ho and a bottle of rum\"\n salt : \"1234abcd9876\"\n },{\n password : \"", "end": 235, "score": 0.9994857311248779, "start": 207, "tag": "PASSWORD", "value": "yo ho ho and a bottle of rum" }, { "context": "word : \"yo ho ho and a bottle of rum\"\n salt : \"1234abcd9876\"\n },{\n password : \"let me in!\"\n salt : \"01", "end": 261, "score": 0.8656918406486511, "start": 249, "tag": "PASSWORD", "value": "1234abcd9876" }, { "context": "\"\n salt : \"1234abcd9876\"\n },{\n password : \"let me in!\"\n salt : \"0123456789\"\n },{\n password : \"p", "end": 294, "score": 0.9994937777519226, "start": 285, "tag": "PASSWORD", "value": "let me in" }, { "context": "n!\"\n salt : \"0123456789\"\n },{\n password : \"password PASSWORD password PASSWORD\"\n salt : \"73616c7453414c5473616c7453414c547361", "end": 378, "score": 0.9983747005462646, "start": 343, "tag": "PASSWORD", "value": "password PASSWORD password PASSWORD" } ]
test/gen/gen_pbkdf2.iced
CyberFlameGO/triplesec
274
{CryptoJS} = require 'cryptojs-1sp' opts = hasher : CryptoJS.algo.SHA512 iterations : 64 keySize : (512*3)/32 inputs = [ { password : "cats11" salt : "aabbccddeeff" },{ password : "yo ho ho and a bottle of rum" salt : "1234abcd9876" },{ password : "let me in!" salt : "0123456789" },{ password : "password PASSWORD password PASSWORD" salt : "73616c7453414c5473616c7453414c5473616c7453414c54" } ] data = [] for {password,salt} in inputs password = CryptoJS.enc.Utf8.parse password salt = CryptoJS.enc.Hex.parse salt output = CryptoJS.PBKDF2 password, salt, opts d = { password, salt, output } for k,v of d d[k] = v.toString CryptoJS.enc.Hex data.push d export_opts = c : opts.iterations dkLen : opts.keySize * 4 console.log "exports.data = #{JSON.stringify data, null, 4};" console.log "exports.opts = #{JSON.stringify export_opts, null, 4};"
155619
{CryptoJS} = require 'cryptojs-1sp' opts = hasher : CryptoJS.algo.SHA512 iterations : 64 keySize : (512*3)/32 inputs = [ { password : "<PASSWORD>" salt : "aabbccddeeff" },{ password : "<PASSWORD>" salt : "<PASSWORD>" },{ password : "<PASSWORD>!" salt : "0123456789" },{ password : "<PASSWORD>" salt : "73616c7453414c5473616c7453414c5473616c7453414c54" } ] data = [] for {password,salt} in inputs password = CryptoJS.enc.Utf8.parse password salt = CryptoJS.enc.Hex.parse salt output = CryptoJS.PBKDF2 password, salt, opts d = { password, salt, output } for k,v of d d[k] = v.toString CryptoJS.enc.Hex data.push d export_opts = c : opts.iterations dkLen : opts.keySize * 4 console.log "exports.data = #{JSON.stringify data, null, 4};" console.log "exports.opts = #{JSON.stringify export_opts, null, 4};"
true
{CryptoJS} = require 'cryptojs-1sp' opts = hasher : CryptoJS.algo.SHA512 iterations : 64 keySize : (512*3)/32 inputs = [ { password : "PI:PASSWORD:<PASSWORD>END_PI" salt : "aabbccddeeff" },{ password : "PI:PASSWORD:<PASSWORD>END_PI" salt : "PI:PASSWORD:<PASSWORD>END_PI" },{ password : "PI:PASSWORD:<PASSWORD>END_PI!" salt : "0123456789" },{ password : "PI:PASSWORD:<PASSWORD>END_PI" salt : "73616c7453414c5473616c7453414c5473616c7453414c54" } ] data = [] for {password,salt} in inputs password = CryptoJS.enc.Utf8.parse password salt = CryptoJS.enc.Hex.parse salt output = CryptoJS.PBKDF2 password, salt, opts d = { password, salt, output } for k,v of d d[k] = v.toString CryptoJS.enc.Hex data.push d export_opts = c : opts.iterations dkLen : opts.keySize * 4 console.log "exports.data = #{JSON.stringify data, null, 4};" console.log "exports.opts = #{JSON.stringify export_opts, null, 4};"
[ { "context": "in package.json to \"awe-test-package\")\n repo: 'git@github.com:alberon/awe.git'\n\n # Delete files\n clean:\n ", "end": 322, "score": 0.9992977380752563, "start": 308, "tag": "EMAIL", "value": "git@github.com" }, { "context": " to \"awe-test-package\")\n repo: 'git@github.com:alberon/awe.git'\n\n # Delete files\n clean:\n doc", "end": 330, "score": 0.9996711611747742, "start": 323, "tag": "USERNAME", "value": "alberon" }, { "context": "pdating Awe on Jericho...\";\n ssh -p 52222 root@jericho.alberon.co.uk \"npm --color=always update -g awe\"\n '\n\n ", "end": 4637, "score": 0.9998615980148315, "start": 4611, "tag": "EMAIL", "value": "root@jericho.alberon.co.uk" } ]
Gruntfile.coffee
davejamesmiller/awe
0
chalk = require('chalk') fs = require('fs') semver = require('semver') module.exports = (grunt) -> pkg = grunt.file.readJSON('package.json') grunt.initConfig pkg: pkg # Change this for testing the publish task # (Also change "name" in package.json to "awe-test-package") repo: 'git@github.com:alberon/awe.git' # Delete files clean: docs: 'docs-html/' docsCache: 'docs-html/.buildinfo' lib: 'lib-build/' man: 'man-build/' pdfdocs: 'docs-pdf/' # Compile CoffeeScript files coffee: options: bare: true header: true runtime: 'node' sourceMap: true lib: expand: true nonull: true cwd: 'lib/' src: '**/*.iced' dest: 'lib-build/' ext: '.js' # Generate man pages markedman: options: manual: 'Awe Manual' version: 'Awe <%= pkg.version %>' man: expand: true nonull: true cwd: 'man/' src: '*.[1-8].md' dest: 'man-build/' ext: '' extDot: 'last' # Run unit tests mochaTest: options: bail: true reporter: 'spec' require: 'lib-build/common' all: src: ['test/**/*.coffee', '!test/**/_*.coffee'] # quick: # options: # reporter: 'dot' # src: ['test/**/*.coffee', '!test/**/_*.coffee'] # Interactive prompts prompt: # Confirm documentation has been updated 'publish-confirm': options: questions: [ { config: 'confirmed' type: 'confirm' message: 'Did you remember to update the documentation (if appropriate)?' } ] then: (answers) -> if ! answers.confirmed grunt.log.writeln() grunt.fail.fatal('Hmm... Better go do that then.', 0) # Ask which version number to use 'publish-version': options: questions: [ { config: 'version' type: 'list' message: 'Bump version from <%= pkg.version %> to:', choices: [ { value: (v = semver.inc(pkg.version, 'patch')), name: chalk.yellow(v) + ' Backwards-compatible bug fixes' }, { value: (v = semver.inc(pkg.version, 'minor')), name: chalk.yellow(v) + ' Add functionality in a backwards-compatible manner' }, { value: (v = semver.inc(pkg.version, 'major')), name: chalk.yellow(v) + ' Incompatible API changes' }, { value: 'custom', name: chalk.yellow('Custom') + ' Specify version...' } ] } { config: 'version', type: 'input', message: 'What specific version would you like?', when: (answers) -> answers.version == 'custom' validate: (value) -> if semver.valid(value) true else 'Must be a valid semver, such as 1.2.3-rc1. See http://semver.org/ for more details.' } ] # Shell commands shell: # Update Ruby gems 'update-gems': command: 'bundle install --path=ruby_bundle --binstubs=ruby_bundle/bin --no-deployment --without=production && bundle update' # Build documentation docs: command: 'sphinx-build -b html docs docs-html' pdfdocs: command: 'sphinx-build -b latex docs docs-pdf && make -C docs-pdf all-pdf' # Publish (from local to GitHub and npm) 'publish-check': command: 'scripts/publish-check.sh "<%= repo %>"' 'publish-show-log': command: ' echo "Commits since the last version:"; echo; git log --reverse --pretty=format:"%C(red)%h %C(yellow)%s %C(green)(%cr) %C(bold blue)<%= "<%" %>an>%C(reset)" refs/tags/v<%= pkg.version%>..; echo ' 'publish-version': command: 'npm version <%= version %>' 'publish-push': command: 'git push "<%= repo %>" refs/heads/master refs/tags/v<%= version %>' 'publish-npm': command: 'npm publish' # Deploy (from npm to Jericho) deploy: command: ' echo "Updating Awe on Jericho..."; ssh -p 52222 root@jericho.alberon.co.uk "npm --color=always update -g awe" ' # Test modified source files testMap: lib: expand: true src: 'lib/**/*.iced' # options: # additional: # 'lib/AssetGroup.iced': 'test/assets.coffee' # 'lib/cacheDir.iced': 'test/assets.coffee' # 'lib/cmd-build.iced': 'test/assets.coffee' # Watch for changes watch: # Build everything at start & when this file is modified buildAll: options: atBegin: true files: 'Gruntfile.coffee' tasks: ['clear', 'build'] # Build docs/ docs: files: 'docs/*.*' # Skip clean:docs because I have issues with Chrome not refreshing # properly if I happen to refresh too fast and get a Not Found page - # for some reason after that I can't see the new version tasks: ['clear', 'shell:docs'] docsAssets: files: 'docs/_static/*.*' tasks: ['clear', 'clean:docsCache', 'shell:docs'] # Build lib-build/ lib: files: 'lib/**/*.iced' tasks: ['clear', 'build-lib', 'newer:testMap:lib'] # Build man-build/ man: files: 'man/*.[1-8].md' tasks: ['clear', 'build-man'] # Run modified test suite test: files: ['test/**/*.coffee', '!test/**/_*.coffee'] tasks: ['clear', 'newer:mochaTest:all'] # Register tasks grunt.registerTask 'build', ['build-lib', 'build-man', 'build-docs-html'] grunt.registerTask 'build-docs-html', ['clean:docs', 'shell:docs'] grunt.registerTask 'build-docs-pdf', ['clean:pdfdocs', 'shell:pdfdocs'] grunt.registerTask 'build-lib', ['clean:lib', 'coffee:lib'] grunt.registerTask 'build-man', ['clean:man', 'markedman:man'] grunt.registerTask 'deploy', ['publish', 'shell:deploy'] grunt.registerTask 'update-gems', ['shell:update-gems'] grunt.registerTask 'publish', [ 'shell:publish-check' # Check everything is checked in and merged 'prompt:publish-confirm' # Check the documentation is up-to-date 'shell:publish-show-log' # Display list of changes 'prompt:publish-version' # Ask the user for the version number to use 'build-lib' # Build the files 'build-man' # Build the manual pages 'test' # Run the unit tests 'shell:publish-version' # Update package.json, commit and tag the version 'shell:publish-push' # Upload the tag to GitHub 'shell:publish-npm' # Upload the release to npm ] # The test command is a bit more complex as it takes an optional filename grunt.registerTask 'test', (suite) -> if suite grunt.config('mochaTest.suite.src', "test/#{suite}.coffee") grunt.task.run('mochaTest:suite') else grunt.task.run('mochaTest:all') # Default to displaying help grunt.registerTask 'default', ['help'] grunt.registerTask 'help', -> grunt.log.writeln """ #{chalk.bold.underline('AVAILABLE COMMANDS')} #{chalk.bold('grunt build')} Build (almost) everything (lib/, man/ and docs/ - excludes PDF docs) #{chalk.bold('grunt build-docs-html')} Build HTML documentation (docs/ → docs-html/) #{chalk.bold('grunt build-docs-pdf')} Build PDF documentation (docs/ → docs-pdf/) #{chalk.bold('grunt build-lib')} Build JavaScript files (lib/ → lib-build/) #{chalk.bold('grunt build-man')} Build manual pages (man/ → man-build/) #{chalk.bold('grunt deploy')} Upgrade Awe on Alberon servers (currently only Jericho) #{chalk.bold('grunt publish')} Release a new version of Awe (upload to GitHub & npm), then deploy it #{chalk.bold('grunt test')} Run all unit/integration tests #{chalk.bold('grunt test:<suite>')} Run the specified test suite (e.g. 'grunt test:config') #{chalk.bold('grunt update-gems')} Update Ruby gems to the latest allowed version (according to Gemfile) #{chalk.bold('grunt watch')} Run 'build' then watch for further changes and build / run tests automatically """ # Run tests corresponding to modified source files grunt.registerMultiTask 'testMap', '(For internal use only)', -> additional = this.options().additional files = [] # Loop through all the modified files this.files.forEach (file) => file.src.forEach (src) => # Does it have a matching unit test suite? if matches = src.match /lib\/(.+)\.iced$/ files.push("test/#{matches[1]}.coffee") # Any additional tests that should be run for this file? if additional && src of additional if additional[src] instanceof Array files = files.concat(additional[src]) else files.push(additional[src]) # Run the test suite for those files only grunt.config('mochaTest.modified.src', files) grunt.task.run('mochaTest:modified') # Lazy-load plugins & custom tasks require('jit-grunt')(grunt, coffee: 'grunt-iced-coffee' )
75017
chalk = require('chalk') fs = require('fs') semver = require('semver') module.exports = (grunt) -> pkg = grunt.file.readJSON('package.json') grunt.initConfig pkg: pkg # Change this for testing the publish task # (Also change "name" in package.json to "awe-test-package") repo: '<EMAIL>:alberon/awe.git' # Delete files clean: docs: 'docs-html/' docsCache: 'docs-html/.buildinfo' lib: 'lib-build/' man: 'man-build/' pdfdocs: 'docs-pdf/' # Compile CoffeeScript files coffee: options: bare: true header: true runtime: 'node' sourceMap: true lib: expand: true nonull: true cwd: 'lib/' src: '**/*.iced' dest: 'lib-build/' ext: '.js' # Generate man pages markedman: options: manual: 'Awe Manual' version: 'Awe <%= pkg.version %>' man: expand: true nonull: true cwd: 'man/' src: '*.[1-8].md' dest: 'man-build/' ext: '' extDot: 'last' # Run unit tests mochaTest: options: bail: true reporter: 'spec' require: 'lib-build/common' all: src: ['test/**/*.coffee', '!test/**/_*.coffee'] # quick: # options: # reporter: 'dot' # src: ['test/**/*.coffee', '!test/**/_*.coffee'] # Interactive prompts prompt: # Confirm documentation has been updated 'publish-confirm': options: questions: [ { config: 'confirmed' type: 'confirm' message: 'Did you remember to update the documentation (if appropriate)?' } ] then: (answers) -> if ! answers.confirmed grunt.log.writeln() grunt.fail.fatal('Hmm... Better go do that then.', 0) # Ask which version number to use 'publish-version': options: questions: [ { config: 'version' type: 'list' message: 'Bump version from <%= pkg.version %> to:', choices: [ { value: (v = semver.inc(pkg.version, 'patch')), name: chalk.yellow(v) + ' Backwards-compatible bug fixes' }, { value: (v = semver.inc(pkg.version, 'minor')), name: chalk.yellow(v) + ' Add functionality in a backwards-compatible manner' }, { value: (v = semver.inc(pkg.version, 'major')), name: chalk.yellow(v) + ' Incompatible API changes' }, { value: 'custom', name: chalk.yellow('Custom') + ' Specify version...' } ] } { config: 'version', type: 'input', message: 'What specific version would you like?', when: (answers) -> answers.version == 'custom' validate: (value) -> if semver.valid(value) true else 'Must be a valid semver, such as 1.2.3-rc1. See http://semver.org/ for more details.' } ] # Shell commands shell: # Update Ruby gems 'update-gems': command: 'bundle install --path=ruby_bundle --binstubs=ruby_bundle/bin --no-deployment --without=production && bundle update' # Build documentation docs: command: 'sphinx-build -b html docs docs-html' pdfdocs: command: 'sphinx-build -b latex docs docs-pdf && make -C docs-pdf all-pdf' # Publish (from local to GitHub and npm) 'publish-check': command: 'scripts/publish-check.sh "<%= repo %>"' 'publish-show-log': command: ' echo "Commits since the last version:"; echo; git log --reverse --pretty=format:"%C(red)%h %C(yellow)%s %C(green)(%cr) %C(bold blue)<%= "<%" %>an>%C(reset)" refs/tags/v<%= pkg.version%>..; echo ' 'publish-version': command: 'npm version <%= version %>' 'publish-push': command: 'git push "<%= repo %>" refs/heads/master refs/tags/v<%= version %>' 'publish-npm': command: 'npm publish' # Deploy (from npm to Jericho) deploy: command: ' echo "Updating Awe on Jericho..."; ssh -p 52222 <EMAIL> "npm --color=always update -g awe" ' # Test modified source files testMap: lib: expand: true src: 'lib/**/*.iced' # options: # additional: # 'lib/AssetGroup.iced': 'test/assets.coffee' # 'lib/cacheDir.iced': 'test/assets.coffee' # 'lib/cmd-build.iced': 'test/assets.coffee' # Watch for changes watch: # Build everything at start & when this file is modified buildAll: options: atBegin: true files: 'Gruntfile.coffee' tasks: ['clear', 'build'] # Build docs/ docs: files: 'docs/*.*' # Skip clean:docs because I have issues with Chrome not refreshing # properly if I happen to refresh too fast and get a Not Found page - # for some reason after that I can't see the new version tasks: ['clear', 'shell:docs'] docsAssets: files: 'docs/_static/*.*' tasks: ['clear', 'clean:docsCache', 'shell:docs'] # Build lib-build/ lib: files: 'lib/**/*.iced' tasks: ['clear', 'build-lib', 'newer:testMap:lib'] # Build man-build/ man: files: 'man/*.[1-8].md' tasks: ['clear', 'build-man'] # Run modified test suite test: files: ['test/**/*.coffee', '!test/**/_*.coffee'] tasks: ['clear', 'newer:mochaTest:all'] # Register tasks grunt.registerTask 'build', ['build-lib', 'build-man', 'build-docs-html'] grunt.registerTask 'build-docs-html', ['clean:docs', 'shell:docs'] grunt.registerTask 'build-docs-pdf', ['clean:pdfdocs', 'shell:pdfdocs'] grunt.registerTask 'build-lib', ['clean:lib', 'coffee:lib'] grunt.registerTask 'build-man', ['clean:man', 'markedman:man'] grunt.registerTask 'deploy', ['publish', 'shell:deploy'] grunt.registerTask 'update-gems', ['shell:update-gems'] grunt.registerTask 'publish', [ 'shell:publish-check' # Check everything is checked in and merged 'prompt:publish-confirm' # Check the documentation is up-to-date 'shell:publish-show-log' # Display list of changes 'prompt:publish-version' # Ask the user for the version number to use 'build-lib' # Build the files 'build-man' # Build the manual pages 'test' # Run the unit tests 'shell:publish-version' # Update package.json, commit and tag the version 'shell:publish-push' # Upload the tag to GitHub 'shell:publish-npm' # Upload the release to npm ] # The test command is a bit more complex as it takes an optional filename grunt.registerTask 'test', (suite) -> if suite grunt.config('mochaTest.suite.src', "test/#{suite}.coffee") grunt.task.run('mochaTest:suite') else grunt.task.run('mochaTest:all') # Default to displaying help grunt.registerTask 'default', ['help'] grunt.registerTask 'help', -> grunt.log.writeln """ #{chalk.bold.underline('AVAILABLE COMMANDS')} #{chalk.bold('grunt build')} Build (almost) everything (lib/, man/ and docs/ - excludes PDF docs) #{chalk.bold('grunt build-docs-html')} Build HTML documentation (docs/ → docs-html/) #{chalk.bold('grunt build-docs-pdf')} Build PDF documentation (docs/ → docs-pdf/) #{chalk.bold('grunt build-lib')} Build JavaScript files (lib/ → lib-build/) #{chalk.bold('grunt build-man')} Build manual pages (man/ → man-build/) #{chalk.bold('grunt deploy')} Upgrade Awe on Alberon servers (currently only Jericho) #{chalk.bold('grunt publish')} Release a new version of Awe (upload to GitHub & npm), then deploy it #{chalk.bold('grunt test')} Run all unit/integration tests #{chalk.bold('grunt test:<suite>')} Run the specified test suite (e.g. 'grunt test:config') #{chalk.bold('grunt update-gems')} Update Ruby gems to the latest allowed version (according to Gemfile) #{chalk.bold('grunt watch')} Run 'build' then watch for further changes and build / run tests automatically """ # Run tests corresponding to modified source files grunt.registerMultiTask 'testMap', '(For internal use only)', -> additional = this.options().additional files = [] # Loop through all the modified files this.files.forEach (file) => file.src.forEach (src) => # Does it have a matching unit test suite? if matches = src.match /lib\/(.+)\.iced$/ files.push("test/#{matches[1]}.coffee") # Any additional tests that should be run for this file? if additional && src of additional if additional[src] instanceof Array files = files.concat(additional[src]) else files.push(additional[src]) # Run the test suite for those files only grunt.config('mochaTest.modified.src', files) grunt.task.run('mochaTest:modified') # Lazy-load plugins & custom tasks require('jit-grunt')(grunt, coffee: 'grunt-iced-coffee' )
true
chalk = require('chalk') fs = require('fs') semver = require('semver') module.exports = (grunt) -> pkg = grunt.file.readJSON('package.json') grunt.initConfig pkg: pkg # Change this for testing the publish task # (Also change "name" in package.json to "awe-test-package") repo: 'PI:EMAIL:<EMAIL>END_PI:alberon/awe.git' # Delete files clean: docs: 'docs-html/' docsCache: 'docs-html/.buildinfo' lib: 'lib-build/' man: 'man-build/' pdfdocs: 'docs-pdf/' # Compile CoffeeScript files coffee: options: bare: true header: true runtime: 'node' sourceMap: true lib: expand: true nonull: true cwd: 'lib/' src: '**/*.iced' dest: 'lib-build/' ext: '.js' # Generate man pages markedman: options: manual: 'Awe Manual' version: 'Awe <%= pkg.version %>' man: expand: true nonull: true cwd: 'man/' src: '*.[1-8].md' dest: 'man-build/' ext: '' extDot: 'last' # Run unit tests mochaTest: options: bail: true reporter: 'spec' require: 'lib-build/common' all: src: ['test/**/*.coffee', '!test/**/_*.coffee'] # quick: # options: # reporter: 'dot' # src: ['test/**/*.coffee', '!test/**/_*.coffee'] # Interactive prompts prompt: # Confirm documentation has been updated 'publish-confirm': options: questions: [ { config: 'confirmed' type: 'confirm' message: 'Did you remember to update the documentation (if appropriate)?' } ] then: (answers) -> if ! answers.confirmed grunt.log.writeln() grunt.fail.fatal('Hmm... Better go do that then.', 0) # Ask which version number to use 'publish-version': options: questions: [ { config: 'version' type: 'list' message: 'Bump version from <%= pkg.version %> to:', choices: [ { value: (v = semver.inc(pkg.version, 'patch')), name: chalk.yellow(v) + ' Backwards-compatible bug fixes' }, { value: (v = semver.inc(pkg.version, 'minor')), name: chalk.yellow(v) + ' Add functionality in a backwards-compatible manner' }, { value: (v = semver.inc(pkg.version, 'major')), name: chalk.yellow(v) + ' Incompatible API changes' }, { value: 'custom', name: chalk.yellow('Custom') + ' Specify version...' } ] } { config: 'version', type: 'input', message: 'What specific version would you like?', when: (answers) -> answers.version == 'custom' validate: (value) -> if semver.valid(value) true else 'Must be a valid semver, such as 1.2.3-rc1. See http://semver.org/ for more details.' } ] # Shell commands shell: # Update Ruby gems 'update-gems': command: 'bundle install --path=ruby_bundle --binstubs=ruby_bundle/bin --no-deployment --without=production && bundle update' # Build documentation docs: command: 'sphinx-build -b html docs docs-html' pdfdocs: command: 'sphinx-build -b latex docs docs-pdf && make -C docs-pdf all-pdf' # Publish (from local to GitHub and npm) 'publish-check': command: 'scripts/publish-check.sh "<%= repo %>"' 'publish-show-log': command: ' echo "Commits since the last version:"; echo; git log --reverse --pretty=format:"%C(red)%h %C(yellow)%s %C(green)(%cr) %C(bold blue)<%= "<%" %>an>%C(reset)" refs/tags/v<%= pkg.version%>..; echo ' 'publish-version': command: 'npm version <%= version %>' 'publish-push': command: 'git push "<%= repo %>" refs/heads/master refs/tags/v<%= version %>' 'publish-npm': command: 'npm publish' # Deploy (from npm to Jericho) deploy: command: ' echo "Updating Awe on Jericho..."; ssh -p 52222 PI:EMAIL:<EMAIL>END_PI "npm --color=always update -g awe" ' # Test modified source files testMap: lib: expand: true src: 'lib/**/*.iced' # options: # additional: # 'lib/AssetGroup.iced': 'test/assets.coffee' # 'lib/cacheDir.iced': 'test/assets.coffee' # 'lib/cmd-build.iced': 'test/assets.coffee' # Watch for changes watch: # Build everything at start & when this file is modified buildAll: options: atBegin: true files: 'Gruntfile.coffee' tasks: ['clear', 'build'] # Build docs/ docs: files: 'docs/*.*' # Skip clean:docs because I have issues with Chrome not refreshing # properly if I happen to refresh too fast and get a Not Found page - # for some reason after that I can't see the new version tasks: ['clear', 'shell:docs'] docsAssets: files: 'docs/_static/*.*' tasks: ['clear', 'clean:docsCache', 'shell:docs'] # Build lib-build/ lib: files: 'lib/**/*.iced' tasks: ['clear', 'build-lib', 'newer:testMap:lib'] # Build man-build/ man: files: 'man/*.[1-8].md' tasks: ['clear', 'build-man'] # Run modified test suite test: files: ['test/**/*.coffee', '!test/**/_*.coffee'] tasks: ['clear', 'newer:mochaTest:all'] # Register tasks grunt.registerTask 'build', ['build-lib', 'build-man', 'build-docs-html'] grunt.registerTask 'build-docs-html', ['clean:docs', 'shell:docs'] grunt.registerTask 'build-docs-pdf', ['clean:pdfdocs', 'shell:pdfdocs'] grunt.registerTask 'build-lib', ['clean:lib', 'coffee:lib'] grunt.registerTask 'build-man', ['clean:man', 'markedman:man'] grunt.registerTask 'deploy', ['publish', 'shell:deploy'] grunt.registerTask 'update-gems', ['shell:update-gems'] grunt.registerTask 'publish', [ 'shell:publish-check' # Check everything is checked in and merged 'prompt:publish-confirm' # Check the documentation is up-to-date 'shell:publish-show-log' # Display list of changes 'prompt:publish-version' # Ask the user for the version number to use 'build-lib' # Build the files 'build-man' # Build the manual pages 'test' # Run the unit tests 'shell:publish-version' # Update package.json, commit and tag the version 'shell:publish-push' # Upload the tag to GitHub 'shell:publish-npm' # Upload the release to npm ] # The test command is a bit more complex as it takes an optional filename grunt.registerTask 'test', (suite) -> if suite grunt.config('mochaTest.suite.src', "test/#{suite}.coffee") grunt.task.run('mochaTest:suite') else grunt.task.run('mochaTest:all') # Default to displaying help grunt.registerTask 'default', ['help'] grunt.registerTask 'help', -> grunt.log.writeln """ #{chalk.bold.underline('AVAILABLE COMMANDS')} #{chalk.bold('grunt build')} Build (almost) everything (lib/, man/ and docs/ - excludes PDF docs) #{chalk.bold('grunt build-docs-html')} Build HTML documentation (docs/ → docs-html/) #{chalk.bold('grunt build-docs-pdf')} Build PDF documentation (docs/ → docs-pdf/) #{chalk.bold('grunt build-lib')} Build JavaScript files (lib/ → lib-build/) #{chalk.bold('grunt build-man')} Build manual pages (man/ → man-build/) #{chalk.bold('grunt deploy')} Upgrade Awe on Alberon servers (currently only Jericho) #{chalk.bold('grunt publish')} Release a new version of Awe (upload to GitHub & npm), then deploy it #{chalk.bold('grunt test')} Run all unit/integration tests #{chalk.bold('grunt test:<suite>')} Run the specified test suite (e.g. 'grunt test:config') #{chalk.bold('grunt update-gems')} Update Ruby gems to the latest allowed version (according to Gemfile) #{chalk.bold('grunt watch')} Run 'build' then watch for further changes and build / run tests automatically """ # Run tests corresponding to modified source files grunt.registerMultiTask 'testMap', '(For internal use only)', -> additional = this.options().additional files = [] # Loop through all the modified files this.files.forEach (file) => file.src.forEach (src) => # Does it have a matching unit test suite? if matches = src.match /lib\/(.+)\.iced$/ files.push("test/#{matches[1]}.coffee") # Any additional tests that should be run for this file? if additional && src of additional if additional[src] instanceof Array files = files.concat(additional[src]) else files.push(additional[src]) # Run the test suite for those files only grunt.config('mochaTest.modified.src', files) grunt.task.run('mochaTest:modified') # Lazy-load plugins & custom tasks require('jit-grunt')(grunt, coffee: 'grunt-iced-coffee' )
[ { "context": "#\n#/*!\n# * node-uglifier\n# * Copyright (c) 2014 Zsolt Szabo Istvan\n# * MIT Licensed\n# *\n# */\n#\n\n_ = require('undersc", "end": 66, "score": 0.9998455047607422, "start": 48, "tag": "NAME", "value": "Zsolt Szabo Istvan" } ]
src/libs/cryptoUtils.coffee
BenHall/node-uglifier
185
# #/*! # * node-uglifier # * Copyright (c) 2014 Zsolt Szabo Istvan # * MIT Licensed # * # */ # _ = require('underscore') sugar = require('sugar') crypto=require("crypto") seedrandom=require("seedrandom") cryptoUtils=module.exports cryptoUtils.generateSalt=(saltLength)->crypto.randomBytes(Math.ceil(saltLength / 2)).toString('hex').substring(0, saltLength); cryptoUtils.getSaltedHash=(message,hashAlgorithm,salt)->crypto.createHmac(hashAlgorithm,salt).update(message).digest('hex') cryptoUtils.shuffleArray=(array,seed=null)-> randFnc=Math.random if seed then randFnc=seedrandom(seed); for i in [array.length - 1..0] j = Math.floor(randFnc() * (i + 1)); temp = array[i]; array[i] = array[j]; array[j] = temp; return array;
27789
# #/*! # * node-uglifier # * Copyright (c) 2014 <NAME> # * MIT Licensed # * # */ # _ = require('underscore') sugar = require('sugar') crypto=require("crypto") seedrandom=require("seedrandom") cryptoUtils=module.exports cryptoUtils.generateSalt=(saltLength)->crypto.randomBytes(Math.ceil(saltLength / 2)).toString('hex').substring(0, saltLength); cryptoUtils.getSaltedHash=(message,hashAlgorithm,salt)->crypto.createHmac(hashAlgorithm,salt).update(message).digest('hex') cryptoUtils.shuffleArray=(array,seed=null)-> randFnc=Math.random if seed then randFnc=seedrandom(seed); for i in [array.length - 1..0] j = Math.floor(randFnc() * (i + 1)); temp = array[i]; array[i] = array[j]; array[j] = temp; return array;
true
# #/*! # * node-uglifier # * Copyright (c) 2014 PI:NAME:<NAME>END_PI # * MIT Licensed # * # */ # _ = require('underscore') sugar = require('sugar') crypto=require("crypto") seedrandom=require("seedrandom") cryptoUtils=module.exports cryptoUtils.generateSalt=(saltLength)->crypto.randomBytes(Math.ceil(saltLength / 2)).toString('hex').substring(0, saltLength); cryptoUtils.getSaltedHash=(message,hashAlgorithm,salt)->crypto.createHmac(hashAlgorithm,salt).update(message).digest('hex') cryptoUtils.shuffleArray=(array,seed=null)-> randFnc=Math.random if seed then randFnc=seedrandom(seed); for i in [array.length - 1..0] j = Math.floor(randFnc() * (i + 1)); temp = array[i]; array[i] = array[j]; array[j] = temp; return array;
[ { "context": " user = RocketChat.models.Users.findOne({username: username})\n if user? and user.avatarUrl?\n ", "end": 113, "score": 0.9657111167907715, "start": 105, "tag": "USERNAME", "value": "username" }, { "context": " return user.avatarUrl\n key = \"avatar_random_#{username}\"\n random = Session?.keys[key] or 0\n ", "end": 252, "score": 0.994732677936554, "start": 226, "tag": "KEY", "value": "avatar_random_#{username}\"" } ]
rocketchat/packages/rocketchat-ui/lib/getAvatarUrlFromUsername.coffee
Ritesh1991/mobile_app_server
0
@getAvatarUrlFromUsername = (username) -> user = RocketChat.models.Users.findOne({username: username}) if user? and user.avatarUrl? return user.avatarUrl key = "avatar_random_#{username}" random = Session?.keys[key] or 0 if not username? return if Meteor.isCordova path = Meteor.absoluteUrl().replace /\/$/, '' else path = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; "#{path}/avatar/#{encodeURIComponent(username)}.jpg?_dc=#{random}"
121652
@getAvatarUrlFromUsername = (username) -> user = RocketChat.models.Users.findOne({username: username}) if user? and user.avatarUrl? return user.avatarUrl key = "<KEY> random = Session?.keys[key] or 0 if not username? return if Meteor.isCordova path = Meteor.absoluteUrl().replace /\/$/, '' else path = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; "#{path}/avatar/#{encodeURIComponent(username)}.jpg?_dc=#{random}"
true
@getAvatarUrlFromUsername = (username) -> user = RocketChat.models.Users.findOne({username: username}) if user? and user.avatarUrl? return user.avatarUrl key = "PI:KEY:<KEY>END_PI random = Session?.keys[key] or 0 if not username? return if Meteor.isCordova path = Meteor.absoluteUrl().replace /\/$/, '' else path = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; "#{path}/avatar/#{encodeURIComponent(username)}.jpg?_dc=#{random}"
[ { "context": ">\n clean = (key) ->\n key = key.replace /:/g, 'IDBI'\n key.replace /\\//g, 'IIDI'\n unclean = (key) ", "end": 150, "score": 0.9320762753486633, "start": 146, "tag": "KEY", "value": "IDBI" }, { "context": " key.replace /:/g, 'IDBI'\n key.replace /\\//g, 'IIDI'\n unclean = (key) ->\n key = key.replace /IDBI", "end": 180, "score": 0.9339966773986816, "start": 176, "tag": "KEY", "value": "IIDI" } ]
src/local-fs.coffee
ndxbxrme/rsdb
0
fs = require 'fs-extra' glob = require 'glob' path = require 'path' module.exports = (config) -> clean = (key) -> key = key.replace /:/g, 'IDBI' key.replace /\//g, 'IIDI' unclean = (key) -> key = key.replace /IDBI/g, ':' key = key.replace /IIDI/g, '/' regex = new RegExp '^' + path.join(config.localStorage) + '\\\/' key.replace regex, '' checkDataDir: -> if config.localStorage if not fs.existsSync path.join(config.localStorage) fs.mkdirSync path.join(config.localStorage) keys: (from, prefix) -> ls = path.join(config.localStorage).replace(/\\/g, '/') + '/' new Promise (resolve, reject) -> glob path.join(config.localStorage, clean(prefix) + '*.json'), (e, r) -> return reject e if e i = -1 count = 0 gotFrom = not from output = Contents: [] IsTruncated: false while ++i < r.length and count < 1000 r[i] = r[i].replace ls, '' if gotFrom output.Contents.push Key: unclean r[i].replace('.json', '') count++ else if unclean(r[i]) is from + '.json' gotFrom = true if i < r.length output.IsTruncated = true resolve output del: (key) -> uri = path.join(config.localStorage, "#{clean(key)}.json") fs.unlink uri put: (key, o) -> uri = path.join(config.localStorage, "#{clean(key)}.json") fs.writeFile uri, JSON.stringify(o) get: (key) -> uri = path.join(config.localStorage, "#{clean(key)}.json") new Promise (resolve, reject) -> try text = await fs.readFile uri, 'utf8' catch e return reject e try data = JSON.parse r catch e return reject e resolve data getReadStream: (key) -> uri = path.join(config.localStorage, "#{clean(key)}.json") fs.createReadStream uri getWriteStream: (key) -> uri = path.join(config.localStorage, "#{clean(key)}.json") fs.createWriteStream uri
165712
fs = require 'fs-extra' glob = require 'glob' path = require 'path' module.exports = (config) -> clean = (key) -> key = key.replace /:/g, '<KEY>' key.replace /\//g, '<KEY>' unclean = (key) -> key = key.replace /IDBI/g, ':' key = key.replace /IIDI/g, '/' regex = new RegExp '^' + path.join(config.localStorage) + '\\\/' key.replace regex, '' checkDataDir: -> if config.localStorage if not fs.existsSync path.join(config.localStorage) fs.mkdirSync path.join(config.localStorage) keys: (from, prefix) -> ls = path.join(config.localStorage).replace(/\\/g, '/') + '/' new Promise (resolve, reject) -> glob path.join(config.localStorage, clean(prefix) + '*.json'), (e, r) -> return reject e if e i = -1 count = 0 gotFrom = not from output = Contents: [] IsTruncated: false while ++i < r.length and count < 1000 r[i] = r[i].replace ls, '' if gotFrom output.Contents.push Key: unclean r[i].replace('.json', '') count++ else if unclean(r[i]) is from + '.json' gotFrom = true if i < r.length output.IsTruncated = true resolve output del: (key) -> uri = path.join(config.localStorage, "#{clean(key)}.json") fs.unlink uri put: (key, o) -> uri = path.join(config.localStorage, "#{clean(key)}.json") fs.writeFile uri, JSON.stringify(o) get: (key) -> uri = path.join(config.localStorage, "#{clean(key)}.json") new Promise (resolve, reject) -> try text = await fs.readFile uri, 'utf8' catch e return reject e try data = JSON.parse r catch e return reject e resolve data getReadStream: (key) -> uri = path.join(config.localStorage, "#{clean(key)}.json") fs.createReadStream uri getWriteStream: (key) -> uri = path.join(config.localStorage, "#{clean(key)}.json") fs.createWriteStream uri
true
fs = require 'fs-extra' glob = require 'glob' path = require 'path' module.exports = (config) -> clean = (key) -> key = key.replace /:/g, 'PI:KEY:<KEY>END_PI' key.replace /\//g, 'PI:KEY:<KEY>END_PI' unclean = (key) -> key = key.replace /IDBI/g, ':' key = key.replace /IIDI/g, '/' regex = new RegExp '^' + path.join(config.localStorage) + '\\\/' key.replace regex, '' checkDataDir: -> if config.localStorage if not fs.existsSync path.join(config.localStorage) fs.mkdirSync path.join(config.localStorage) keys: (from, prefix) -> ls = path.join(config.localStorage).replace(/\\/g, '/') + '/' new Promise (resolve, reject) -> glob path.join(config.localStorage, clean(prefix) + '*.json'), (e, r) -> return reject e if e i = -1 count = 0 gotFrom = not from output = Contents: [] IsTruncated: false while ++i < r.length and count < 1000 r[i] = r[i].replace ls, '' if gotFrom output.Contents.push Key: unclean r[i].replace('.json', '') count++ else if unclean(r[i]) is from + '.json' gotFrom = true if i < r.length output.IsTruncated = true resolve output del: (key) -> uri = path.join(config.localStorage, "#{clean(key)}.json") fs.unlink uri put: (key, o) -> uri = path.join(config.localStorage, "#{clean(key)}.json") fs.writeFile uri, JSON.stringify(o) get: (key) -> uri = path.join(config.localStorage, "#{clean(key)}.json") new Promise (resolve, reject) -> try text = await fs.readFile uri, 'utf8' catch e return reject e try data = JSON.parse r catch e return reject e resolve data getReadStream: (key) -> uri = path.join(config.localStorage, "#{clean(key)}.json") fs.createReadStream uri getWriteStream: (key) -> uri = path.join(config.localStorage, "#{clean(key)}.json") fs.createWriteStream uri
[ { "context": "dow\n# BBNS.error 'Whoops, we are out of stock on Simon Talek', window.location\n#\n# It basically works li", "end": 1369, "score": 0.5451070666313171, "start": 1364, "tag": "NAME", "value": "Simon" } ]
src/coffeescript/log.js.coffee
mihar/backbone-skeleton
6
# Protection against exceptions when window.console is not defined. window.console = {} if not window.console unless console.log console.log = -> unless console.warn console.warn = -> unless console.error console.error = -> unless console.info console.info = -> # Main log output function. BBNS.console_output = -> args = Array.prototype.slice.call(arguments) # Filter out output function. output_routine = args[0] args.shift() return unless output_routine if args.length > 1 level = parseInt args[0] if [0, 1, 2, 3, 4, 5, 6].indexOf(level) > -1 args.shift() return false if BBNS.app.debug < level level = 0 if isNaN level level = 0 unless level? # Timestamp. date = new Date timestamp = "#{date.getUTCFullYear()}-#{date.getUTCMonth()+1}-#{date.getUTCDate()}@#{date.getUTCHours()}:#{date.getUTCMinutes()}:#{date.getUTCSeconds()}.#{date.getUTCMilliseconds()}" # Message is separate. msg = args[0] if args.length > 1 args.shift() else args = [] console[output_routine] "[#{level}:#{timestamp}] #{msg}", args... true # Actual log functions you use in your app. # # The usual is to use them like this: # BBNS.log <Some message string here>, [<obj1>, <obj2>, <obj3>] # Example: # BBNS.log 'This is the current browser window object', window # BBNS.error 'Whoops, we are out of stock on Simon Talek', window.location # # It basically works like console.log, just that the first argument should # always be some kind of a message, what's happening, followed by an arbitrary # number of objects, that will be output verbatim. # BBNS.log = -> BBNS.console_output 'log', arguments... BBNS.info = -> BBNS.console_output 'info', arguments... BBNS.warn = -> BBNS.console_output 'warn', arguments... BBNS.error = -> BBNS.console_output 'error', arguments...
194607
# Protection against exceptions when window.console is not defined. window.console = {} if not window.console unless console.log console.log = -> unless console.warn console.warn = -> unless console.error console.error = -> unless console.info console.info = -> # Main log output function. BBNS.console_output = -> args = Array.prototype.slice.call(arguments) # Filter out output function. output_routine = args[0] args.shift() return unless output_routine if args.length > 1 level = parseInt args[0] if [0, 1, 2, 3, 4, 5, 6].indexOf(level) > -1 args.shift() return false if BBNS.app.debug < level level = 0 if isNaN level level = 0 unless level? # Timestamp. date = new Date timestamp = "#{date.getUTCFullYear()}-#{date.getUTCMonth()+1}-#{date.getUTCDate()}@#{date.getUTCHours()}:#{date.getUTCMinutes()}:#{date.getUTCSeconds()}.#{date.getUTCMilliseconds()}" # Message is separate. msg = args[0] if args.length > 1 args.shift() else args = [] console[output_routine] "[#{level}:#{timestamp}] #{msg}", args... true # Actual log functions you use in your app. # # The usual is to use them like this: # BBNS.log <Some message string here>, [<obj1>, <obj2>, <obj3>] # Example: # BBNS.log 'This is the current browser window object', window # BBNS.error 'Whoops, we are out of stock on <NAME> Talek', window.location # # It basically works like console.log, just that the first argument should # always be some kind of a message, what's happening, followed by an arbitrary # number of objects, that will be output verbatim. # BBNS.log = -> BBNS.console_output 'log', arguments... BBNS.info = -> BBNS.console_output 'info', arguments... BBNS.warn = -> BBNS.console_output 'warn', arguments... BBNS.error = -> BBNS.console_output 'error', arguments...
true
# Protection against exceptions when window.console is not defined. window.console = {} if not window.console unless console.log console.log = -> unless console.warn console.warn = -> unless console.error console.error = -> unless console.info console.info = -> # Main log output function. BBNS.console_output = -> args = Array.prototype.slice.call(arguments) # Filter out output function. output_routine = args[0] args.shift() return unless output_routine if args.length > 1 level = parseInt args[0] if [0, 1, 2, 3, 4, 5, 6].indexOf(level) > -1 args.shift() return false if BBNS.app.debug < level level = 0 if isNaN level level = 0 unless level? # Timestamp. date = new Date timestamp = "#{date.getUTCFullYear()}-#{date.getUTCMonth()+1}-#{date.getUTCDate()}@#{date.getUTCHours()}:#{date.getUTCMinutes()}:#{date.getUTCSeconds()}.#{date.getUTCMilliseconds()}" # Message is separate. msg = args[0] if args.length > 1 args.shift() else args = [] console[output_routine] "[#{level}:#{timestamp}] #{msg}", args... true # Actual log functions you use in your app. # # The usual is to use them like this: # BBNS.log <Some message string here>, [<obj1>, <obj2>, <obj3>] # Example: # BBNS.log 'This is the current browser window object', window # BBNS.error 'Whoops, we are out of stock on PI:NAME:<NAME>END_PI Talek', window.location # # It basically works like console.log, just that the first argument should # always be some kind of a message, what's happening, followed by an arbitrary # number of objects, that will be output verbatim. # BBNS.log = -> BBNS.console_output 'log', arguments... BBNS.info = -> BBNS.console_output 'info', arguments... BBNS.warn = -> BBNS.console_output 'warn', arguments... BBNS.error = -> BBNS.console_output 'error', arguments...
[ { "context": "tasks.length}}'\n 'input type=\"text\"':\n '@val': '@new_task_name'\n '.d1':\n 'a':\n '@on click': 'addNewTask", "end": 1500, "score": 0.9983041286468506, "start": 1485, "tag": "USERNAME", "value": "'@new_task_name" }, { "context": "lick': 'addNewTask()'\n '@text': 'Add Task {{@new_task_name}}'\n '.d2':\n 'a':\n '@on click': 'removeSe", "end": 1595, "score": 0.9344154596328735, "start": 1582, "tag": "USERNAME", "value": "new_task_name" }, { "context": "asks'\n\nnew TasksCtrl(\n 'tasks': [\n { 'name': 'one' }\n { 'name': 'two' }\n { 'name': 'three' }\n", "end": 1746, "score": 0.994067907333374, "start": 1743, "tag": "NAME", "value": "one" }, { "context": " 'tasks': [\n { 'name': 'one' }\n { 'name': 'two' }\n { 'name': 'three' }\n ]\n).renderAt app_nod", "end": 1768, "score": 0.9869693517684937, "start": 1765, "tag": "NAME", "value": "two" }, { "context": "me': 'one' }\n { 'name': 'two' }\n { 'name': 'three' }\n ]\n).renderAt app_node, template", "end": 1792, "score": 0.9926572442054749, "start": 1787, "tag": "NAME", "value": "three" } ]
examples/todo/todo.coffee
aligo/casua
2
TasksCtrl = casua.defineController (scope) -> scope.set 'new_task_name', 'new' addNewTask: -> scope.get('tasks').push 'name': scope.get('new_task_name') scope.set 'new_task_name', '' removeSelectedTasks: -> scope.get('tasks').filter (task) -> not task.get 'done' TaskCtrl = casua.defineController (scope) -> tasks_scope = scope.get('$parent') taskClass: -> if scope.get 'done' 'is-done' else '' checkTask: -> scope.set 'done', !scope.get('done') removeTask: -> tasks_scope.remove tasks_scope.indexOf(scope) startEdit: -> scope.set 'editing', true @$node('$name').trigger 'focus' saveChange: (e) -> keyCode = e.keyCode || e.which scope.set 'editing', false if keyCode == 13 app_node = new casua.Node document.getElementById('todo-app') template = 'ul.tasks-list': '@child tasks': '@controller': TaskCtrl 'li': '@attr class': 'taskClass()' 'span': '@unless': '@editing' 'input type="checkbox"': '@on click': 'checkTask()' '@attr checked': '@done' 'span': '@on dblclick': 'startEdit()' '@html': 'Task {{@name}}' 'a': '@text': 'x' '@on click': 'removeTask()' 'input type="text" $name': '@if': '@editing' '@val': '@name' '@on keyup': 'saveChange()' '.d0': 'Count: {{@tasks.length}}' 'input type="text"': '@val': '@new_task_name' '.d1': 'a': '@on click': 'addNewTask()' '@text': 'Add Task {{@new_task_name}}' '.d2': 'a': '@on click': 'removeSelectedTasks()' '@text': 'Remove Selected Tasks' new TasksCtrl( 'tasks': [ { 'name': 'one' } { 'name': 'two' } { 'name': 'three' } ] ).renderAt app_node, template
28707
TasksCtrl = casua.defineController (scope) -> scope.set 'new_task_name', 'new' addNewTask: -> scope.get('tasks').push 'name': scope.get('new_task_name') scope.set 'new_task_name', '' removeSelectedTasks: -> scope.get('tasks').filter (task) -> not task.get 'done' TaskCtrl = casua.defineController (scope) -> tasks_scope = scope.get('$parent') taskClass: -> if scope.get 'done' 'is-done' else '' checkTask: -> scope.set 'done', !scope.get('done') removeTask: -> tasks_scope.remove tasks_scope.indexOf(scope) startEdit: -> scope.set 'editing', true @$node('$name').trigger 'focus' saveChange: (e) -> keyCode = e.keyCode || e.which scope.set 'editing', false if keyCode == 13 app_node = new casua.Node document.getElementById('todo-app') template = 'ul.tasks-list': '@child tasks': '@controller': TaskCtrl 'li': '@attr class': 'taskClass()' 'span': '@unless': '@editing' 'input type="checkbox"': '@on click': 'checkTask()' '@attr checked': '@done' 'span': '@on dblclick': 'startEdit()' '@html': 'Task {{@name}}' 'a': '@text': 'x' '@on click': 'removeTask()' 'input type="text" $name': '@if': '@editing' '@val': '@name' '@on keyup': 'saveChange()' '.d0': 'Count: {{@tasks.length}}' 'input type="text"': '@val': '@new_task_name' '.d1': 'a': '@on click': 'addNewTask()' '@text': 'Add Task {{@new_task_name}}' '.d2': 'a': '@on click': 'removeSelectedTasks()' '@text': 'Remove Selected Tasks' new TasksCtrl( 'tasks': [ { 'name': '<NAME>' } { 'name': '<NAME>' } { 'name': '<NAME>' } ] ).renderAt app_node, template
true
TasksCtrl = casua.defineController (scope) -> scope.set 'new_task_name', 'new' addNewTask: -> scope.get('tasks').push 'name': scope.get('new_task_name') scope.set 'new_task_name', '' removeSelectedTasks: -> scope.get('tasks').filter (task) -> not task.get 'done' TaskCtrl = casua.defineController (scope) -> tasks_scope = scope.get('$parent') taskClass: -> if scope.get 'done' 'is-done' else '' checkTask: -> scope.set 'done', !scope.get('done') removeTask: -> tasks_scope.remove tasks_scope.indexOf(scope) startEdit: -> scope.set 'editing', true @$node('$name').trigger 'focus' saveChange: (e) -> keyCode = e.keyCode || e.which scope.set 'editing', false if keyCode == 13 app_node = new casua.Node document.getElementById('todo-app') template = 'ul.tasks-list': '@child tasks': '@controller': TaskCtrl 'li': '@attr class': 'taskClass()' 'span': '@unless': '@editing' 'input type="checkbox"': '@on click': 'checkTask()' '@attr checked': '@done' 'span': '@on dblclick': 'startEdit()' '@html': 'Task {{@name}}' 'a': '@text': 'x' '@on click': 'removeTask()' 'input type="text" $name': '@if': '@editing' '@val': '@name' '@on keyup': 'saveChange()' '.d0': 'Count: {{@tasks.length}}' 'input type="text"': '@val': '@new_task_name' '.d1': 'a': '@on click': 'addNewTask()' '@text': 'Add Task {{@new_task_name}}' '.d2': 'a': '@on click': 'removeSelectedTasks()' '@text': 'Remove Selected Tasks' new TasksCtrl( 'tasks': [ { 'name': 'PI:NAME:<NAME>END_PI' } { 'name': 'PI:NAME:<NAME>END_PI' } { 'name': 'PI:NAME:<NAME>END_PI' } ] ).renderAt app_node, template
[ { "context": "'''\nwatchOS : Notification\n\n@auther Jungho song (threeword.com)\n@since 2016.11.23\n'''\nclass expor", "end": 47, "score": 0.9998644590377808, "start": 36, "tag": "NAME", "value": "Jungho song" } ]
modules/watchos-kit-notification.coffee
framer-modules/watchos
2
''' watchOS : Notification @auther Jungho song (threeword.com) @since 2016.11.23 ''' class exports.Notification extends Layer # Button Button = {} # Button : Style Button.Style = {} Button.Style.Default = "buttonStyle.default" Button.Style.Destructive = "buttonStyle.destructive" # Static this.Button = Button ''' appName: 앱이름 [require] icon: 아이콘 이미지 경로 [require] accentColor: 대표 색상 (Shrot looks의 앱이름 색상이 됨) title: 제목 message: 내용 attach: 첨부 내용 (Layer) sashColor: 샤시 색상 (Long looks의 상단 색상) sashLabelColor: 샤시의 앱이름 색상 (Long looks의 상단레이블 색상) bgColoc: 배경 색상 (Long looks의 배경 색상) buttons: label: "상세보기" [require] style: Button.Style.Default bgColor: "rgba(242,244,255,.14)" labelColor: "white" isHaptic: false ''' # Constructor constructor: (options = {}) -> options.name = "Notification" options.width ?= Device.width options.height ?= Device.height options.backgroundColor ?= "" super options options.buttons ?= [] options.appName ?= "App" options.icon ?= "" options.accentColor ?= "white" options.title ?= "Title" options.message ?= "Message" options.sashColor ?= "rgba(255,255,255,.1)" options.bgColor ?= "rgba(255,255,255,.14)" options.sashLabelColor ?= "white" title = options.title message = options.message buttons = options.buttons appName = options.appName icon = options.icon accentColor = options.accentColor sashColor = options.sashColor bgColor = options.bgColor # bg @bg = new Layer name: ".bg" width: @width, height: @height backgroundColor: "rgba(0,0,0,.6)" opacity: 0 parent: @ Util.blur @bg # Short looks @short = new Layer name: ".short" width: @width, height: @height backgroundColor: "" parent: @ # Short looks : Icon @short.icon = new Layer name: ".short.icon" x: Align.center, y: Align.top(41) size: 196 image: icon borderRadius: 98 shadowY: 2, shadowBlur: 8, shadowColor: "rgba(0,0,0,.3)" backgroundColor: "white" parent: @short # Short looks : Title @short.title = new Layer name: ".short.title" x: Align.center, y: @short.icon.maxY + 18 html: title style: fontSize: "38px", fontWeight: 400, lineHeight: 1 letterSpacing: "-0.42px" textAlign: "center" backgroundColor: "" parent: @short Util.text.autoSize @short.title @short.title.centerX() # Short looks : App name @short.appName = new Layer name: ".short.appName" x: Align.center, y: @short.title.maxY + 9 html: appName style: fontSize: "28px", fontWeight: 400, lineHeight: 1 letterSpacing: "0.22px" textAlign: "center" textTransform: "uppercase" color: accentColor backgroundColor: "" parent: @short Util.text.autoSize @short.appName @short.appName.centerX() # Lonf looks @long = new Scroll name: ".long" width: @width, height: @height backgroundColor: "" contentInset: top: 42, bottom: 14 parent: @ @long.confirm = new Layer html: "확인" style: fontWeight: "400" fontSize: "24px" paddingBottom: "25px" textAlign: "center" backgroundColor: "" color: "#8d8d8d" parent: @long Util.text.autoSize @long.confirm @long.confirm.props = x: Align.center, y: -(@long.contentInset.top + 32) @long.confirm.bar = new Layer x: Align.center, y: Align.bottom width: 80, height: 5 backgroundColor: "" parent: @long.confirm @long.confirm.bar.left = new Layer x: Align.left, y: Align.bottom width: 43, height: 5 originX: 0, originY: 0 borderRadius: 5 backgroundColor: "#8d8d8d" parent: @long.confirm.bar @long.confirm.bar.right = new Layer x: Align.right, y: Align.bottom width: 43, height: 5 originX: 1, originY: 0 borderRadius: 5 backgroundColor: "#8d8d8d" parent: @long.confirm.bar @long.confirm.changeMode = (mode=false) -> @isChangeMode = mode color = if mode then "white" else "#8d8d8d" rotation = if mode then 10 else 0 options = time: .15, curve: "spring(500,50,0)" @animate color: color, options: options @bar.left.animate rotation: rotation, backgroundColor: color, options: options @bar.right.animate rotation: -rotation,backgroundColor: color, options: options # Lonf looks : Time @long.time = new Layer name: ".long.time" x: Align.right(-4), y: Align.top(1) width: 150, height: 38 html: Util.date.timeFormatter Util.date.getTime() style: fontSize: "32px", fontWeight: 400, lineHeight: "38px" textAlign: "right" color: "#ABABAB" backgroundColor: "" parent: @long # Lonf looks : Message @long.message = createMessage options @long.message.parent = @long.content # Action buttons @long.buttons = [] # Create buttons if buttons for button, i in buttons actionBtn = createActionButton button actionBtn.y += @long.content.contentFrame().height + 8 @long.content.addChild actionBtn @long.buttons.push actionBtn # Button : Close @long.dismissBtn = createActionButton label: "닫기", bgColor: "rgba(242,244,255,.2)" @long.dismissBtn.y += @long.content.contentFrame().height + 24 @long.content.addChild @long.dismissBtn @long.buttons.push @long.dismissBtn # @short.visible = true @long.visible = false # Show background @bg.show = => @bg.animate opacity: 1 options: time: .3 curve: "linear" # Dismiss background @bg.dismiss = => @bg.animate opacity: 0 options: time: 1 curve: "linear" delay: .2 # Show Short looks @short.show = => @short.y = @maxY @short.animate y: 0 options: time: 4 curve: "spring(200,20,0)" # Dismiss Short looks @short.dismiss = => @short.removeChild @short.icon @short.icon.parent = @long @short.animate y: @short.y - 250 opacity: 0 options: time: .07 curve: "spring(500,50,0)" @short.once Events.AnimationEnd, => @short.destroy() @short.icon.animate x: -32, y: -49 # x: 22, y: 5 options: time: .4 curve: "spring(200,20,0)" @short.icon.animate scale: 88/@short.icon.width # width: 88, height: 88 options: time: .46 curve: "ease-in-out" # Show Long looks @long.show = => @long.visible = true @long.content.y = @maxY @long.content.animate y: @long.contentInset.top options: time: 1 curve: "spring(200,20,0)" @long.time.opacity = 0 @long.time.animate opacity: 1 options: time: 1 # Event : Animation end @long.content.once Events.AnimationEnd, => # Event : Scroll @short.icon.startY = @short.icon.y @long.time.startY = @long.time.y @long.confirm.startY = @long.confirm.y @long.onMove => posY = @long.scrollY @short.icon.y = @short.icon.startY - posY # print posY @long.time.y = @long.time.startY - posY if posY < 0 then @long.time.y = @long.time.startY @long.time.opacity = 1 + (posY / 40) @long.confirm.y = @long.confirm.startY - posY if @long.confirm.startY - posY < 0 @long.confirm.changeMode false else @long.confirm.changeMode true @long.onScrollEnd => @close() if @long.confirm.isChangeMode # Event : Action buttons for button in @long.buttons button.onClick => @dismiss() # Dismiss Long looks @long.dismiss = => @long.animate opacity: 0 options: time: .3 curve: "ease" @long.close = => @long.content.draggable.animateStop() @long.content.animateStop() @long.content.animate y: @maxY * 1.3, options: { time: .15, curve: "spring(500,50,0)" } # 알림 @show() # Show show: -> @bringToFront() @bg.show() @short.show() Utils.delay 1.3, => @short.dismiss() @long.show() # Dismiss dismiss: -> @bg.dismiss() @long.dismiss() Utils.delay 1.3, => @destroy() # Close close: -> @bg.dismiss() @long.close() Utils.delay .3, => @destroy() # 버튼 생성 createActionButton = (options = {}) -> options.label ?= "Action" options.style ?= Button.Style.Default options.bgColor ?= "rgba(242,244,255,.14)" options.labelColor ?= "white" options.isHaptic ?= false label = options.label style = options.style bgColor = options.bgColor labelColor = options.labelColor isHaptic = options.isHaptic # 버튼 button = new Layer name: ".notification.button-#{label}" x: Align.left(2) width: 308, height: 80 html: label style: fontSize: "32px", fontWeight: 400, lineHeight: "80px" textAlign: "center" letterSpacing: "-0.1px" color: if style is Button.Style.Destructive then "#FF3B30" else labelColor borderRadius: 15 backgroundColor: bgColor # 버튼 : 상태 button.states = pressed: scale: .95 opacity: .8 animationOptions: time: .15 curve: "spring(500,50,0)" normal: scale: 1 opacity: 1 animationOptions: time: .20 curve: "spring(500,50,0)" # 버튼 효과 button.onMouseDown -> @animate "pressed" button.onMouseUp -> @animate "normal" button.onMouseOut -> @animate "normal" button.onTap -> Device.playHaptic() if isHaptic return button # 메시지 생성 createMessage = (options = {}) -> # 컨텐츠 content = new Layer name: ".notification.content" x: Align.left(2) width: 308, height: 232 backgroundColor: options.bgColor borderRadius: 15 # 헤더 content.header = new Layer name: ".header" width: content.width, height: 60 html: options.appName style: fontSize: "28px", fontWeight: 400, lineHeight: "34px" letterSpacing: "0.5px" textAlign: "right" padding: "12px 21px 14px 0px" textTransform: "uppercase" borderRadius: "15px 15px 0px 0px" color: options.sashLabelColor backgroundColor: options.sashColor parent: content # 타이틀 content.title = new Layer name: ".title" x: Align.left(15), y: content.header.maxY + 25 width: 278 html: options.title style: fontSize: "32px", fontWeight: 600, lineHeight: 1 backgroundColor: "" parent: content Util.text.autoSize content.title, {}, { width: content.title.width } # 메시지 content.message = new Layer name: ".message" x: content.title.minX, y: content.title.maxY + 2 width: content.title.width html: options.message style: fontSize: "32px", fontWeight: 400, lineHeight: "37px" letterSpacing: "-0.2px" backgroundColor: "" parent: content Util.text.autoSize content.message, {}, { width: content.message.width } # 추가내용 if options.attach content.attach = new Layer name: ".attach" x: content.message.x, y: content.message.maxY + 2 width: content.message.width backgroundColor: "" parent: content content.attach.addChild options.attach options.attach.point = Align.center content.attach.height = content.attach.contentFrame().y + content.attach.contentFrame().height # 컨텐츠 높이 조정 : 하단 여백 추가 content.height = content.contentFrame().height + 33 return content
181144
''' watchOS : Notification @auther <NAME> (threeword.com) @since 2016.11.23 ''' class exports.Notification extends Layer # Button Button = {} # Button : Style Button.Style = {} Button.Style.Default = "buttonStyle.default" Button.Style.Destructive = "buttonStyle.destructive" # Static this.Button = Button ''' appName: 앱이름 [require] icon: 아이콘 이미지 경로 [require] accentColor: 대표 색상 (Shrot looks의 앱이름 색상이 됨) title: 제목 message: 내용 attach: 첨부 내용 (Layer) sashColor: 샤시 색상 (Long looks의 상단 색상) sashLabelColor: 샤시의 앱이름 색상 (Long looks의 상단레이블 색상) bgColoc: 배경 색상 (Long looks의 배경 색상) buttons: label: "상세보기" [require] style: Button.Style.Default bgColor: "rgba(242,244,255,.14)" labelColor: "white" isHaptic: false ''' # Constructor constructor: (options = {}) -> options.name = "Notification" options.width ?= Device.width options.height ?= Device.height options.backgroundColor ?= "" super options options.buttons ?= [] options.appName ?= "App" options.icon ?= "" options.accentColor ?= "white" options.title ?= "Title" options.message ?= "Message" options.sashColor ?= "rgba(255,255,255,.1)" options.bgColor ?= "rgba(255,255,255,.14)" options.sashLabelColor ?= "white" title = options.title message = options.message buttons = options.buttons appName = options.appName icon = options.icon accentColor = options.accentColor sashColor = options.sashColor bgColor = options.bgColor # bg @bg = new Layer name: ".bg" width: @width, height: @height backgroundColor: "rgba(0,0,0,.6)" opacity: 0 parent: @ Util.blur @bg # Short looks @short = new Layer name: ".short" width: @width, height: @height backgroundColor: "" parent: @ # Short looks : Icon @short.icon = new Layer name: ".short.icon" x: Align.center, y: Align.top(41) size: 196 image: icon borderRadius: 98 shadowY: 2, shadowBlur: 8, shadowColor: "rgba(0,0,0,.3)" backgroundColor: "white" parent: @short # Short looks : Title @short.title = new Layer name: ".short.title" x: Align.center, y: @short.icon.maxY + 18 html: title style: fontSize: "38px", fontWeight: 400, lineHeight: 1 letterSpacing: "-0.42px" textAlign: "center" backgroundColor: "" parent: @short Util.text.autoSize @short.title @short.title.centerX() # Short looks : App name @short.appName = new Layer name: ".short.appName" x: Align.center, y: @short.title.maxY + 9 html: appName style: fontSize: "28px", fontWeight: 400, lineHeight: 1 letterSpacing: "0.22px" textAlign: "center" textTransform: "uppercase" color: accentColor backgroundColor: "" parent: @short Util.text.autoSize @short.appName @short.appName.centerX() # Lonf looks @long = new Scroll name: ".long" width: @width, height: @height backgroundColor: "" contentInset: top: 42, bottom: 14 parent: @ @long.confirm = new Layer html: "확인" style: fontWeight: "400" fontSize: "24px" paddingBottom: "25px" textAlign: "center" backgroundColor: "" color: "#8d8d8d" parent: @long Util.text.autoSize @long.confirm @long.confirm.props = x: Align.center, y: -(@long.contentInset.top + 32) @long.confirm.bar = new Layer x: Align.center, y: Align.bottom width: 80, height: 5 backgroundColor: "" parent: @long.confirm @long.confirm.bar.left = new Layer x: Align.left, y: Align.bottom width: 43, height: 5 originX: 0, originY: 0 borderRadius: 5 backgroundColor: "#8d8d8d" parent: @long.confirm.bar @long.confirm.bar.right = new Layer x: Align.right, y: Align.bottom width: 43, height: 5 originX: 1, originY: 0 borderRadius: 5 backgroundColor: "#8d8d8d" parent: @long.confirm.bar @long.confirm.changeMode = (mode=false) -> @isChangeMode = mode color = if mode then "white" else "#8d8d8d" rotation = if mode then 10 else 0 options = time: .15, curve: "spring(500,50,0)" @animate color: color, options: options @bar.left.animate rotation: rotation, backgroundColor: color, options: options @bar.right.animate rotation: -rotation,backgroundColor: color, options: options # Lonf looks : Time @long.time = new Layer name: ".long.time" x: Align.right(-4), y: Align.top(1) width: 150, height: 38 html: Util.date.timeFormatter Util.date.getTime() style: fontSize: "32px", fontWeight: 400, lineHeight: "38px" textAlign: "right" color: "#ABABAB" backgroundColor: "" parent: @long # Lonf looks : Message @long.message = createMessage options @long.message.parent = @long.content # Action buttons @long.buttons = [] # Create buttons if buttons for button, i in buttons actionBtn = createActionButton button actionBtn.y += @long.content.contentFrame().height + 8 @long.content.addChild actionBtn @long.buttons.push actionBtn # Button : Close @long.dismissBtn = createActionButton label: "닫기", bgColor: "rgba(242,244,255,.2)" @long.dismissBtn.y += @long.content.contentFrame().height + 24 @long.content.addChild @long.dismissBtn @long.buttons.push @long.dismissBtn # @short.visible = true @long.visible = false # Show background @bg.show = => @bg.animate opacity: 1 options: time: .3 curve: "linear" # Dismiss background @bg.dismiss = => @bg.animate opacity: 0 options: time: 1 curve: "linear" delay: .2 # Show Short looks @short.show = => @short.y = @maxY @short.animate y: 0 options: time: 4 curve: "spring(200,20,0)" # Dismiss Short looks @short.dismiss = => @short.removeChild @short.icon @short.icon.parent = @long @short.animate y: @short.y - 250 opacity: 0 options: time: .07 curve: "spring(500,50,0)" @short.once Events.AnimationEnd, => @short.destroy() @short.icon.animate x: -32, y: -49 # x: 22, y: 5 options: time: .4 curve: "spring(200,20,0)" @short.icon.animate scale: 88/@short.icon.width # width: 88, height: 88 options: time: .46 curve: "ease-in-out" # Show Long looks @long.show = => @long.visible = true @long.content.y = @maxY @long.content.animate y: @long.contentInset.top options: time: 1 curve: "spring(200,20,0)" @long.time.opacity = 0 @long.time.animate opacity: 1 options: time: 1 # Event : Animation end @long.content.once Events.AnimationEnd, => # Event : Scroll @short.icon.startY = @short.icon.y @long.time.startY = @long.time.y @long.confirm.startY = @long.confirm.y @long.onMove => posY = @long.scrollY @short.icon.y = @short.icon.startY - posY # print posY @long.time.y = @long.time.startY - posY if posY < 0 then @long.time.y = @long.time.startY @long.time.opacity = 1 + (posY / 40) @long.confirm.y = @long.confirm.startY - posY if @long.confirm.startY - posY < 0 @long.confirm.changeMode false else @long.confirm.changeMode true @long.onScrollEnd => @close() if @long.confirm.isChangeMode # Event : Action buttons for button in @long.buttons button.onClick => @dismiss() # Dismiss Long looks @long.dismiss = => @long.animate opacity: 0 options: time: .3 curve: "ease" @long.close = => @long.content.draggable.animateStop() @long.content.animateStop() @long.content.animate y: @maxY * 1.3, options: { time: .15, curve: "spring(500,50,0)" } # 알림 @show() # Show show: -> @bringToFront() @bg.show() @short.show() Utils.delay 1.3, => @short.dismiss() @long.show() # Dismiss dismiss: -> @bg.dismiss() @long.dismiss() Utils.delay 1.3, => @destroy() # Close close: -> @bg.dismiss() @long.close() Utils.delay .3, => @destroy() # 버튼 생성 createActionButton = (options = {}) -> options.label ?= "Action" options.style ?= Button.Style.Default options.bgColor ?= "rgba(242,244,255,.14)" options.labelColor ?= "white" options.isHaptic ?= false label = options.label style = options.style bgColor = options.bgColor labelColor = options.labelColor isHaptic = options.isHaptic # 버튼 button = new Layer name: ".notification.button-#{label}" x: Align.left(2) width: 308, height: 80 html: label style: fontSize: "32px", fontWeight: 400, lineHeight: "80px" textAlign: "center" letterSpacing: "-0.1px" color: if style is Button.Style.Destructive then "#FF3B30" else labelColor borderRadius: 15 backgroundColor: bgColor # 버튼 : 상태 button.states = pressed: scale: .95 opacity: .8 animationOptions: time: .15 curve: "spring(500,50,0)" normal: scale: 1 opacity: 1 animationOptions: time: .20 curve: "spring(500,50,0)" # 버튼 효과 button.onMouseDown -> @animate "pressed" button.onMouseUp -> @animate "normal" button.onMouseOut -> @animate "normal" button.onTap -> Device.playHaptic() if isHaptic return button # 메시지 생성 createMessage = (options = {}) -> # 컨텐츠 content = new Layer name: ".notification.content" x: Align.left(2) width: 308, height: 232 backgroundColor: options.bgColor borderRadius: 15 # 헤더 content.header = new Layer name: ".header" width: content.width, height: 60 html: options.appName style: fontSize: "28px", fontWeight: 400, lineHeight: "34px" letterSpacing: "0.5px" textAlign: "right" padding: "12px 21px 14px 0px" textTransform: "uppercase" borderRadius: "15px 15px 0px 0px" color: options.sashLabelColor backgroundColor: options.sashColor parent: content # 타이틀 content.title = new Layer name: ".title" x: Align.left(15), y: content.header.maxY + 25 width: 278 html: options.title style: fontSize: "32px", fontWeight: 600, lineHeight: 1 backgroundColor: "" parent: content Util.text.autoSize content.title, {}, { width: content.title.width } # 메시지 content.message = new Layer name: ".message" x: content.title.minX, y: content.title.maxY + 2 width: content.title.width html: options.message style: fontSize: "32px", fontWeight: 400, lineHeight: "37px" letterSpacing: "-0.2px" backgroundColor: "" parent: content Util.text.autoSize content.message, {}, { width: content.message.width } # 추가내용 if options.attach content.attach = new Layer name: ".attach" x: content.message.x, y: content.message.maxY + 2 width: content.message.width backgroundColor: "" parent: content content.attach.addChild options.attach options.attach.point = Align.center content.attach.height = content.attach.contentFrame().y + content.attach.contentFrame().height # 컨텐츠 높이 조정 : 하단 여백 추가 content.height = content.contentFrame().height + 33 return content
true
''' watchOS : Notification @auther PI:NAME:<NAME>END_PI (threeword.com) @since 2016.11.23 ''' class exports.Notification extends Layer # Button Button = {} # Button : Style Button.Style = {} Button.Style.Default = "buttonStyle.default" Button.Style.Destructive = "buttonStyle.destructive" # Static this.Button = Button ''' appName: 앱이름 [require] icon: 아이콘 이미지 경로 [require] accentColor: 대표 색상 (Shrot looks의 앱이름 색상이 됨) title: 제목 message: 내용 attach: 첨부 내용 (Layer) sashColor: 샤시 색상 (Long looks의 상단 색상) sashLabelColor: 샤시의 앱이름 색상 (Long looks의 상단레이블 색상) bgColoc: 배경 색상 (Long looks의 배경 색상) buttons: label: "상세보기" [require] style: Button.Style.Default bgColor: "rgba(242,244,255,.14)" labelColor: "white" isHaptic: false ''' # Constructor constructor: (options = {}) -> options.name = "Notification" options.width ?= Device.width options.height ?= Device.height options.backgroundColor ?= "" super options options.buttons ?= [] options.appName ?= "App" options.icon ?= "" options.accentColor ?= "white" options.title ?= "Title" options.message ?= "Message" options.sashColor ?= "rgba(255,255,255,.1)" options.bgColor ?= "rgba(255,255,255,.14)" options.sashLabelColor ?= "white" title = options.title message = options.message buttons = options.buttons appName = options.appName icon = options.icon accentColor = options.accentColor sashColor = options.sashColor bgColor = options.bgColor # bg @bg = new Layer name: ".bg" width: @width, height: @height backgroundColor: "rgba(0,0,0,.6)" opacity: 0 parent: @ Util.blur @bg # Short looks @short = new Layer name: ".short" width: @width, height: @height backgroundColor: "" parent: @ # Short looks : Icon @short.icon = new Layer name: ".short.icon" x: Align.center, y: Align.top(41) size: 196 image: icon borderRadius: 98 shadowY: 2, shadowBlur: 8, shadowColor: "rgba(0,0,0,.3)" backgroundColor: "white" parent: @short # Short looks : Title @short.title = new Layer name: ".short.title" x: Align.center, y: @short.icon.maxY + 18 html: title style: fontSize: "38px", fontWeight: 400, lineHeight: 1 letterSpacing: "-0.42px" textAlign: "center" backgroundColor: "" parent: @short Util.text.autoSize @short.title @short.title.centerX() # Short looks : App name @short.appName = new Layer name: ".short.appName" x: Align.center, y: @short.title.maxY + 9 html: appName style: fontSize: "28px", fontWeight: 400, lineHeight: 1 letterSpacing: "0.22px" textAlign: "center" textTransform: "uppercase" color: accentColor backgroundColor: "" parent: @short Util.text.autoSize @short.appName @short.appName.centerX() # Lonf looks @long = new Scroll name: ".long" width: @width, height: @height backgroundColor: "" contentInset: top: 42, bottom: 14 parent: @ @long.confirm = new Layer html: "확인" style: fontWeight: "400" fontSize: "24px" paddingBottom: "25px" textAlign: "center" backgroundColor: "" color: "#8d8d8d" parent: @long Util.text.autoSize @long.confirm @long.confirm.props = x: Align.center, y: -(@long.contentInset.top + 32) @long.confirm.bar = new Layer x: Align.center, y: Align.bottom width: 80, height: 5 backgroundColor: "" parent: @long.confirm @long.confirm.bar.left = new Layer x: Align.left, y: Align.bottom width: 43, height: 5 originX: 0, originY: 0 borderRadius: 5 backgroundColor: "#8d8d8d" parent: @long.confirm.bar @long.confirm.bar.right = new Layer x: Align.right, y: Align.bottom width: 43, height: 5 originX: 1, originY: 0 borderRadius: 5 backgroundColor: "#8d8d8d" parent: @long.confirm.bar @long.confirm.changeMode = (mode=false) -> @isChangeMode = mode color = if mode then "white" else "#8d8d8d" rotation = if mode then 10 else 0 options = time: .15, curve: "spring(500,50,0)" @animate color: color, options: options @bar.left.animate rotation: rotation, backgroundColor: color, options: options @bar.right.animate rotation: -rotation,backgroundColor: color, options: options # Lonf looks : Time @long.time = new Layer name: ".long.time" x: Align.right(-4), y: Align.top(1) width: 150, height: 38 html: Util.date.timeFormatter Util.date.getTime() style: fontSize: "32px", fontWeight: 400, lineHeight: "38px" textAlign: "right" color: "#ABABAB" backgroundColor: "" parent: @long # Lonf looks : Message @long.message = createMessage options @long.message.parent = @long.content # Action buttons @long.buttons = [] # Create buttons if buttons for button, i in buttons actionBtn = createActionButton button actionBtn.y += @long.content.contentFrame().height + 8 @long.content.addChild actionBtn @long.buttons.push actionBtn # Button : Close @long.dismissBtn = createActionButton label: "닫기", bgColor: "rgba(242,244,255,.2)" @long.dismissBtn.y += @long.content.contentFrame().height + 24 @long.content.addChild @long.dismissBtn @long.buttons.push @long.dismissBtn # @short.visible = true @long.visible = false # Show background @bg.show = => @bg.animate opacity: 1 options: time: .3 curve: "linear" # Dismiss background @bg.dismiss = => @bg.animate opacity: 0 options: time: 1 curve: "linear" delay: .2 # Show Short looks @short.show = => @short.y = @maxY @short.animate y: 0 options: time: 4 curve: "spring(200,20,0)" # Dismiss Short looks @short.dismiss = => @short.removeChild @short.icon @short.icon.parent = @long @short.animate y: @short.y - 250 opacity: 0 options: time: .07 curve: "spring(500,50,0)" @short.once Events.AnimationEnd, => @short.destroy() @short.icon.animate x: -32, y: -49 # x: 22, y: 5 options: time: .4 curve: "spring(200,20,0)" @short.icon.animate scale: 88/@short.icon.width # width: 88, height: 88 options: time: .46 curve: "ease-in-out" # Show Long looks @long.show = => @long.visible = true @long.content.y = @maxY @long.content.animate y: @long.contentInset.top options: time: 1 curve: "spring(200,20,0)" @long.time.opacity = 0 @long.time.animate opacity: 1 options: time: 1 # Event : Animation end @long.content.once Events.AnimationEnd, => # Event : Scroll @short.icon.startY = @short.icon.y @long.time.startY = @long.time.y @long.confirm.startY = @long.confirm.y @long.onMove => posY = @long.scrollY @short.icon.y = @short.icon.startY - posY # print posY @long.time.y = @long.time.startY - posY if posY < 0 then @long.time.y = @long.time.startY @long.time.opacity = 1 + (posY / 40) @long.confirm.y = @long.confirm.startY - posY if @long.confirm.startY - posY < 0 @long.confirm.changeMode false else @long.confirm.changeMode true @long.onScrollEnd => @close() if @long.confirm.isChangeMode # Event : Action buttons for button in @long.buttons button.onClick => @dismiss() # Dismiss Long looks @long.dismiss = => @long.animate opacity: 0 options: time: .3 curve: "ease" @long.close = => @long.content.draggable.animateStop() @long.content.animateStop() @long.content.animate y: @maxY * 1.3, options: { time: .15, curve: "spring(500,50,0)" } # 알림 @show() # Show show: -> @bringToFront() @bg.show() @short.show() Utils.delay 1.3, => @short.dismiss() @long.show() # Dismiss dismiss: -> @bg.dismiss() @long.dismiss() Utils.delay 1.3, => @destroy() # Close close: -> @bg.dismiss() @long.close() Utils.delay .3, => @destroy() # 버튼 생성 createActionButton = (options = {}) -> options.label ?= "Action" options.style ?= Button.Style.Default options.bgColor ?= "rgba(242,244,255,.14)" options.labelColor ?= "white" options.isHaptic ?= false label = options.label style = options.style bgColor = options.bgColor labelColor = options.labelColor isHaptic = options.isHaptic # 버튼 button = new Layer name: ".notification.button-#{label}" x: Align.left(2) width: 308, height: 80 html: label style: fontSize: "32px", fontWeight: 400, lineHeight: "80px" textAlign: "center" letterSpacing: "-0.1px" color: if style is Button.Style.Destructive then "#FF3B30" else labelColor borderRadius: 15 backgroundColor: bgColor # 버튼 : 상태 button.states = pressed: scale: .95 opacity: .8 animationOptions: time: .15 curve: "spring(500,50,0)" normal: scale: 1 opacity: 1 animationOptions: time: .20 curve: "spring(500,50,0)" # 버튼 효과 button.onMouseDown -> @animate "pressed" button.onMouseUp -> @animate "normal" button.onMouseOut -> @animate "normal" button.onTap -> Device.playHaptic() if isHaptic return button # 메시지 생성 createMessage = (options = {}) -> # 컨텐츠 content = new Layer name: ".notification.content" x: Align.left(2) width: 308, height: 232 backgroundColor: options.bgColor borderRadius: 15 # 헤더 content.header = new Layer name: ".header" width: content.width, height: 60 html: options.appName style: fontSize: "28px", fontWeight: 400, lineHeight: "34px" letterSpacing: "0.5px" textAlign: "right" padding: "12px 21px 14px 0px" textTransform: "uppercase" borderRadius: "15px 15px 0px 0px" color: options.sashLabelColor backgroundColor: options.sashColor parent: content # 타이틀 content.title = new Layer name: ".title" x: Align.left(15), y: content.header.maxY + 25 width: 278 html: options.title style: fontSize: "32px", fontWeight: 600, lineHeight: 1 backgroundColor: "" parent: content Util.text.autoSize content.title, {}, { width: content.title.width } # 메시지 content.message = new Layer name: ".message" x: content.title.minX, y: content.title.maxY + 2 width: content.title.width html: options.message style: fontSize: "32px", fontWeight: 400, lineHeight: "37px" letterSpacing: "-0.2px" backgroundColor: "" parent: content Util.text.autoSize content.message, {}, { width: content.message.width } # 추가내용 if options.attach content.attach = new Layer name: ".attach" x: content.message.x, y: content.message.maxY + 2 width: content.message.width backgroundColor: "" parent: content content.attach.addChild options.attach options.attach.point = Align.center content.attach.height = content.attach.contentFrame().y + content.attach.contentFrame().height # 컨텐츠 높이 조정 : 하단 여백 추가 content.height = content.contentFrame().height + 33 return content
[ { "context": "###\nBackbone.js 1.0.0\n\n(c) 2010-2011 Jeremy Ashkenas, DocumentCloud Inc.\n(c) 2011-2013 Jeremy Ashkenas", "end": 52, "score": 0.9998788833618164, "start": 37, "tag": "NAME", "value": "Jeremy Ashkenas" }, { "context": " Jeremy Ashkenas, DocumentCloud Inc.\n(c) 2011-2013 Jeremy Ashkenas, DocumentCloud and\nInvestigative Reporters & Edit", "end": 102, "score": 0.9998748898506165, "start": 87, "tag": "NAME", "value": "Jeremy Ashkenas" } ]
backbone.coffee
Whoaa512/backbone-livescript
1
### Backbone.js 1.0.0 (c) 2010-2011 Jeremy Ashkenas, DocumentCloud Inc. (c) 2011-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors Backbone may be freely distributed under the MIT license. For all details and documentation: http://www.backbonecoffee.org ### # Initial Setup # ------------- # Save a reference to the global object (`window` in the browser, `exports` # on the server). root = @ # Save the previous value of the `Backbone` variable, so that it can be # restored later on, if `noConflict` is used. previousBackbone = root.Backbone # Create local references to array methods we'll want to use later. array = [] push = array.push slice = array.slice splice = array.splice # The top-level namespace. All public Backbone classes and modules will # be attached to this. Exported for both the browser and the server. if exports? Backbone = exports else root.Backbone = {} Backbone = root.Backbone # Require Underscore, if we're on the server, and it's not already present. _ = root._ _ = require 'underscore' if not _? and require? # Map from CRUD to HTTP for our default `Backbone.sync` implementation. methodMap = create: 'POST' update: 'PUT' patch: 'PATCH' delete: 'DELETE' read: 'GET' _.extend Backbone, # Current version of the library. Keep in sync with `package.json`. VERSION: '1.0.0' # For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns # the `$` variable. $: root.jQuery or root.Zepto or root.ender or root.$ # Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable # to its previous owner. Returns a reference to this Backbone object. noConflict: -> root.Backbone = previousBackbone @ # Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option # will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and # set a `X-Http-Method-Override` header. emulateHTTP: false # Turn on `emulateJSON` to support legacy servers that can't deal with direct # `application/json` requests ... will encode the body as # `application/x-www-form-urlencoded` instead and will send the model in a # form param named `model`. emulateJSON: false # Set the default implementation of `Backbone.ajax` to proxy through to `$`. # Override this if you'd like to use a different library. ajax: -> Backbone.$.ajax arguments... # Backbone.sync # ------------- # # Override this function to change the manner in which Backbone persists # models to the server. You will be passed the type of request, and the # model in question. By default, makes a RESTful Ajax request # to the model's `url()`. Some possible customizations could be: # # * Use `setTimeout` to batch rapid-fire updates into a single request. # * Send up the models as XML instead of JSON. # * Persist models via WebSockets instead of Ajax. # # Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests # as `POST`, with a `_method` parameter containing the true HTTP method, # as well as all requests with the body as `application/x-www-form-urlencoded` # instead of `application/json` with the model in a param named `model`. # Useful when interfacing with server-side languages like **PHP** that make # it difficult to read the body of `PUT` requests. sync: (method, model, options = {}) -> type = methodMap[method] # Default options, unless specified. _.defaults options, emulateHTTP: Backbone.emulateHTTP emulateJSON: Backbone.emulateJSON # Default JSON-request options. params = type: type dataType: 'json' # Ensure that we have a URL. params.url = _.result(model, 'url') or urlError() unless options.url # Ensure that we have the appropriate request data. if not options.data? and model and (method is 'create' or method is 'update' or method is 'patch') params.contentType = 'application/json' params.data = JSON.stringify(options.attrs or model.toJSON options) # For older servers, emulate JSON by encoding the request into an HTML-form. if options.emulateJSON params.contentType = 'application/x-www-form-urlencoded' params.data = if params.data then model: params.data else {} # For older servers, emulate HTTP by mimicking the HTTP method with # `_method` and an `X-HTTP-Method-Override` header. if options.emulateHTTP and (type is 'PUT' or type is 'DELETE' or type is 'PATCH') params.type = 'POST' params.data._method = type if options.emulateJSON beforeSend = options.beforeSend options.beforeSend = (xhr) -> xhr.setRequestHeader 'X-HTTP-Method-Override', type beforeSend.apply @, arguments if beforeSend # Don't process data on a non-GET request. if params.type != 'GET' and not options.emulateJSON params.processData = false # If we're sending a `PATCH` request, and we're in an old Internet Explorer # that still has ActiveX enabled by default, override jQuery to use that # for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. if params.type is 'PATCH' and window.ActiveXObject and not (window.external and window.external.msActiveXFilteringEnabled) params.xhr = -> new ActiveXObject 'Microsoft.XMLHTTP' # Make the request, allowing the user to override any Ajax options. options.xhr = Backbone.ajax _.extend(params, options) xhr = options.xhr model.trigger 'request', model, xhr, options xhr ### Backbone.Events --------------- A module that can be mixed in to *any object* in order to provide it with custom events. You may bind with `on` or remove with `off` callback functions to an event; `trigger`-ing an event fires all callbacks in succession. var object = {}; _.extend(object, Backbone.Events); object.on('expand', function(){ alert('expanded'); }); object.trigger('expand'); ### class Backbone.Events # Bind an event to a `callback` function. Passing `"all"` will bind # the callback to all events fired. @on: (name, callback, context) -> return @ unless eventsApi(@, 'on', name, [callback, context]) and callback @_events ?= {} @_events[name] ?= [] events = @_events[name] events.push callback: callback context: context ctx: context or @ @ # Bind an event to only be triggered a single time. After the first time # the callback is invoked, it will be removed. @once: (name, callback, context) -> if not eventsApi(@, 'once', name, [callback, context]) or not callback return @ self = @ once = _.once -> self.off name, once callback.apply @, arguments once._callback = callback @on name, once, context # Remove one or many callbacks. If `context` is null, removes all # callbacks with that function. If `callback` is null, removes all # callbacks for the event. If `name` is null, removes all bound # callbacks for all events. @off: (name, callback, context) -> if not @_events or not eventsApi @, 'off', name, [callback, context] return @ if not name and not callback and not context @_events = {} return @ names = if name then [name] else _.keys @_events for name in names events = @_events[name] if events retain = [] @_events[name] = retain if callback or context for ev in events if (callback and callback != ev.callback and callback != ev.callback._callback) or (context and context != ev.context) retain.push ev delete @_events[name] unless retain.length @ # Trigger one or many events, firing all bound callbacks. Callbacks are # passed the same arguments as `trigger` is, apart from the event name # (unless you're listening on `"all"`, which will cause your callback to # receive the true name of the event as the first argument). @trigger: (name) -> return @ unless @_events args = slice.call arguments, 1 return @ unless eventsApi @, 'trigger', name, args events = @_events[name] allEvents = @_events.all triggerEvents events, args if events triggerEvents allEvents, arguments if allEvents @ # Tell this object to stop listening to either specific events ... or # to every object it's currently listening to. @stopListening: (obj, name, callback) -> listeners = @_listeners return @ unless listeners deleteListener = not name and not callback callback = @ if _.isObject name if obj listeners = {} listeners[obj._listenerId] = obj for id, v of listeners listeners[id].off name, callback, @ delete @_listeners[id] if deleteListener @ Events = Backbone.Events # Regular expression used to split event strings. eventSplitter = /\s+/ # Implement fancy features of the Events API such as multiple event # names `"change blur"` and jQuery-style event maps `{change: action}` # in terms of the existing API. eventsApi = (obj, action, name, rest) -> return true unless name # Handle event maps. if _.isObject name for key, v of name obj[action] ([key, name[key]].concat rest)... return false # Handle space separated event names. if eventSplitter.test name names = name.split eventSplitter for i in [0...names.length] obj[action] ([names[i]].concat rest)... return false true # A difficult-to-believe, but optimized internal dispatch function for # triggering events. Tries to keep the usual cases speedy (most internal # Backbone events have 3 arguments). triggerEvents = (events, args) -> i = -1 l = events.length [a1, a2, a3] = args switch args.length when 0 while ++i < l ev = events[i] ev.callback.call ev.ctx when 1 while ++i < l ev = events[i] ev.callback.call ev.ctx, a1 when 2 while ++i < l ev = events[i] ev.callback.call ev.ctx, a1, a2 when 3 while ++i < l ev = events[i] ev.callback.call ev.ctx, a1, a2, a3 else while ++i < l ev = events[i] ev.callback.apply ev.ctx, args listenMethods = listenTo: 'on' listenToOnce: 'once' # Inversion-of-control versions of `on` and `once`. Tell *this* object to # listen to an event in another object ... keeping track of what it's # listening to. _.each listenMethods, (implementation, method) -> Events[method] = (obj, name, callback) -> @_listeners ?= {} listeners = @_listeners obj._listenerId ?= _.uniqueId 'l' id = obj._listenerId listeners[id] = obj callback = @ if _.isObject name obj[implementation] name, callback, @ @ # Aliases for backwards compatibility. Events.bind = Events.on Events.unbind = Events.off # Allow the `Backbone` object to serve as a global event bus, for folks who # want global "pubsub" in a convenient place. _.extend Backbone, Events ### Backbone.Model -------------- Backbone **Models** are the basic data object in the framework -- frequently representing a row in a table in a database on your server. A discrete chunk of data and a bunch of useful, related methods for performing computations and transformations on that data. Create a new model with the specified attributes. A client id (`cid`) is automatically generated and assigned for you. ### class Backbone.Model _.extend @::, Events # A hash of attributes whose current and previous value differ. changed: null # The value returned during the last failed validation. validationError: null # The default name for the JSON `id` attribute is `"id"`. MongoDB and # CouchDB users may want to set this to `"_id"`. idAttribute: 'id' constructor: (attributes, options = {}) -> attrs = attributes or {} @cid = _.uniqueId 'c' @attributes = {} @collection = options.collection if options.collection attrs = @parse(attrs, options) or {} if options.parse options._attrs = attrs defaults = _.result @, 'defaults' attrs = _.defaults {}, attrs, defaults if defaults @set attrs, options @changed = {} @initialize arguments... # Initialize is an empty function by default. Override it with your own # initialization logic. initialize: -> # pass # Return a copy of the model's `attributes` object. toJSON: (options) -> _.clone @attributes # Proxy `Backbone.sync` by default -- but override this if you need # custom syncing semantics for *this* particular model. sync: -> Backbone.sync.apply @, arguments # Get the value of an attribute. get: (attr) -> @attributes[attr] # Get the HTML-escaped value of an attribute. escape: (attr) -> _.escape @get(attr) # Returns `true` if the attribute contains a value that != null # or undefined. has: (attr) -> @get(attr)? # Set a hash of model attributes on the object, firing `"change"`. This is # the core primitive operation of a model, updating the data and notifying # anyone who needs to know about the change in state. The heart of the beast. set: (key, val, options = {}) -> return this unless key? # Handle both `"key", value` and `{key: value}` -style arguments. if _.isObject key attrs = key options = val or {} else attrs = {} attrs[key] = val # Run validation. return false unless @_validate attrs, options # Extract attributes and options. unset = options.unset silent = options.silent changes = [] changing = @_changing @_changing = true unless changing @_previousAttributes = _.clone @attributes @changed = {} current = @attributes prev = @_previousAttributes # Check for changes of `id`. @id = attrs[@idAttribute] if _.has attrs, @idAttribute # For each `set` attribute, update or delete the current value. for attr, v of attrs val = attrs[attr] changes.push(attr) unless _.isEqual current[attr], val unless _.isEqual prev[attr], val @changed[attr] = val else delete @changed[attr] if unset delete current[attr] else current[attr] = val # Trigger all relevant attribute changes. unless silent @_pending = true if changes.length for change in changes @trigger 'change:' + change, @, current[change], options # You might be wondering why there's a `while` loop here. Changes can # be recursively nested within `"change"` events. return @ if changing unless silent while @_pending @_pending = false @trigger 'change', @, options @_pending = false @_changing = false @ # Remove an attribute from the model, firing `"change"`. `unset` is a noop # if the attribute doesn't exist. unset: (attr, options) -> @set attr, undefined, _.extend({}, options, unset: true) # Clear all attributes on the model, firing `"change"`. clear: (options) -> attrs = {} for key, v of @attributes attrs[key] = undefined @set attrs, _.extend({}, options, unset: true) # Determine if the model has changed since the last `"change"` event. # If you specify an attribute name, determine if that attribute has changed. hasChanged: (attr) -> return not _.isEmpty @changed unless attr? return _.has @changed, attr # Return an object containing all the attributes that have changed, or # false if there are no changed attributes. Useful for determining what # parts of a view need to be updated and/or what attributes need to be # persisted to the server. Unset attributes will be set to undefined. # You can also pass an attributes object to diff against the model, # determining if there *would be* a change. changedAttributes: (diff) -> unless diff return if @hasChanged() then _.clone(@changed) else false changed = false old = if @_changing then @_previousAttributes else @attributes for attr, v of diff continue if _.isEqual old[attr], v changed = {} unless changed changed[attr] = v return changed # Get the previous value of an attribute, recorded at the time the last # `"change"` event was fired. previous: (attr) -> return null if not attr? or not @_previousAttributes return @_previousAttributes[attr] # Get all of the attributes of the model at the time of the previous # `"change"` event. previousAttributes: -> _.clone @_previousAttributes # Fetch the model from the server. If the server's representation of the # model differs from its current attributes, they will be overridden, # triggering a `"change"` event. fetch: (options = {}) -> options = _.clone options options.parse = true unless options.parse? model = @ success = options.success options.success = (resp) -> return false unless model.set model.parse(resp, options), options success(model, resp, options) if success model.trigger 'sync', model, resp, options wrapError this, options @sync 'read', this, options # Set a hash of model attributes, and sync the model to the server. # If the server returns an attributes hash that differs, the model's # state will be `set` again. save: (key, val, options) -> attributes = @attributes # Handle both `"key", value` and `{key: value}` -style arguments. if not key? or _.isObject key attrs = key options = val else attrs = {} attrs[key] = val options = _.extend {validate: true}, options # If we're not waiting and attributes exist, save acts as # `set(attr).save(null, opts)` with validation. Otherwise, check if # the model will be valid when the attributes, if any, are set. if attrs and not options.wait return false unless @set attrs, options else return false unless @_validate attrs, options # Set temporary attributes if `{wait: true}`. if attrs and options.wait @attributes = _.extend {}, attributes, attrs # After a successful server-side save, the client is (optionally) # updated with the server-side state. options.parse = true unless options.parse? model = @ success = options.success options.success = (resp) -> # Ensure attributes are restored during synchronous saves. model.attributes = attributes serverAttrs = model.parse resp, options serverAttrs = _.extend(attrs or {}, serverAttrs) if options.wait if _.isObject(serverAttrs) and not model.set serverAttrs, options return false success model, resp, options if success model.trigger 'sync', model, resp, options wrapError @, options if @isNew() method = 'create' else method = (if options.patch then 'patch' else 'update') options.attrs = attrs if method is 'patch' xhr = @sync method, @, options # Restore attributes. @attributes = attributes if attrs and options.wait xhr # Destroy this model on the server if it was already persisted. # Optimistically removes the model from its collection, if it has one. # If `wait: true` is passed, waits for the server to respond before removal. destroy: (options = {}) -> options = _.clone options model = @ success = options.success destroy = -> model.trigger 'destroy', model, model.collection, options options.success = (resp) -> destroy() if options.wait or model.isNew() success(model, resp, options) if success model.trigger('sync', model, resp, options) unless model.isNew() if @isNew() options.success() return false wrapError @, options xhr = @sync 'delete', @, options destroy() unless options.wait xhr # Default URL for the model's representation on the server -- if you're # using Backbone's restful methods, override this to change the endpoint # that will be called. url: -> base = _.result(@, 'urlRoot') or _.result(@collection, 'url') or urlError() return base if @isNew() base + (if base.charAt(base.length - 1) is '/' then '' else '/') + encodeURIComponent @id # **parse** converts a response into the hash of attributes to be `set` on # the model. The default implementation is just to pass the response along. parse: (resp, options) -> resp # Create a new model with identical attributes to this one. clone: -> new @constructor @attributes # A model is new if it has never been saved to the server, and lacks an id. isNew: -> not @id? # Check if the model is currently in a valid state. isValid: (options) -> @_validate {}, _.extend(options or {}, validate: true) # Run validation against the next complete set of model attributes, # returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate: (attrs, options = {}) -> return true if not options.validate or not @validate attrs = _.extend {}, @attributes, attrs @validationError = @validate(attrs, options) or null error = @validationError return true unless error @trigger 'invalid', @, error, _.extend(options or {}, validationError: error) false Model = Backbone.Model # Underscore methods that we want to implement on the Model. modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'] # Mix in each Underscore method as a proxy to `Model#attributes`. _.each modelMethods, (method) -> Model.prototype[method] = -> args = slice.call arguments args.unshift @attributes _[method] args... ### Backbone.Collection ------------------- If models tend to represent a single row of data, a Backbone Collection is more analagous to a table full of data ... or a small slice or page of that table, or a collection of rows that belong together for a particular reason -- all of the messages in this particular folder, all of the documents belonging to this particular author, and so on. Collections maintain indexes of their models, both in order, and for lookup by `id`. Create a new **Collection**, perhaps to contain a specific type of `model`. If a `comparator` is specified, the Collection will maintain its models in sort order, as they're added and removed. ### # Default options for `Collection#set`. setOptions = add: true remove: true merge: true addOptions = add: true merge: false remove: false class Backbone.Collection _.extend @::, Events # The default model for a collection is just a **Backbone.Model**. # This should be overridden in most cases. model: Model constructor: (models, options) -> options or= {} @model = options.model if options.model @comparator = options.comparator unless _.isUndefined options.comparator @_reset() @initialize arguments... @reset models, _.extend({silent: true}, options) if models # Initialize is an empty function by default. Override it with your own # initialization logic. initialize: -> # pass # The JSON representation of a Collection is an array of the # models' attributes. toJSON: (options) -> @map (model) -> model.toJSON options # Proxy `Backbone.sync` by default. sync: -> Backbone.sync.apply @, arguments # Add a model, or list of models to the set. add: (models, options = {}) -> @set models, _.defaults(options, addOptions) # Remove a model, or a list of models from the set. remove: (models, options = {}) -> models = if _.isArray(models) then models.slice() else [models] for i in [0...models.length] model = @get models[i] continue unless model delete @_byId[model.id] delete @_byId[model.cid] index = @indexOf model @models.splice index, 1 @length-- unless options.silent options.index = index model.trigger 'remove', model, @, options @_removeReference model @ # Update a collection by `set`-ing a new list of models, adding new ones, # removing models that are no longer present, and merging models that # already exist in the collection, as necessary. Similar to **Model#set**, # the core operation for updating the data contained by the collection. set: (models, options = {}) -> options = _.defaults options, setOptions models = @parse(models, options) if options.parse unless _.isArray models models = if models then [models] else [] at = options.at sortable = @comparator and not at? and options.sort != false sortAttr = if _.isString @comparator then @comparator else null toAdd = [] toRemove = [] modelMap = {} add = options.add merge = options.merge remove = options.remove order = if not sortable and add and remove then [] else false # Turn bare objects into model references, and prevent invalid models # from being added. for i in [0...models.length] attrs = models[i] model = @_prepareModel attrs, options continue unless model # If a duplicate is found, prevent it from being added and # optionally merge it into the existing model. existing = @get model if existing modelMap[existing.cid] = true if remove if merge attrs = if attrs is model then model.attributes else options._attrs existing.set attrs, options sort = true if sortable and not sort and existing.hasChanged sortAttr # This is a new model, push it to the `toAdd` list. else if add toAdd.push model # Listen to added models' events, and index models for lookup by # `id` and by `cid`. model.on 'all', @_onModelEvent, @ @_byId[model.cid] = model @_byId[model.id] = model if model.id? order.push(existing or model) if order # Remove nonexistent models if appropriate. if remove for i in [0...@length] model = @models[i] toRemove.push model unless modelMap[model.cid] @remove(toRemove, options) if toRemove.length # See if sorting is needed, update `length` and splice in new models. if toAdd.length or (order and order.length) sort = true if sortable @length += toAdd.length if at? splice.apply @models, [at, 0].concat(toAdd) else @models.length = 0 if order push.apply @models, (order or toAdd) # Silently sort the collection if appropriate. @sort silent: true if sort return @ if options.silent # Trigger `add` events. for model in toAdd model.trigger 'add', model, @, options # Trigger `sort` if the collection was sorted. @trigger 'sort', @, options if sort or (order and order.length) @ # When you have more items than you want to add or remove individually, # you can reset the entire set with a new list of models, without firing # any granular `add` or `remove` events. Fires `reset` when finished. # Useful for bulk operations and optimizations. reset: (models, options = {}) -> @_removeReference model for model in @models options.previousModels = @models @_reset() @add models, _.extend({silent: true}, options) @trigger 'reset', @, options unless options.silent @ # Add a model to the end of the collection. push: (model, options) -> model = @_prepareModel model, options @add model, _.extend({at: @length}, options) model # Remove a model from the end of the collection. pop: (options) -> model = @at(@length - 1) @remove model, options model # Add a model to the beginning of the collection. unshift: (model, options) -> model = @_prepareModel model, options @add model, _.extend({at: 0}, options) model # Remove a model from the beginning of the collection. shift: (options) -> model = @at 0 @remove model, options model # Slice out a sub-array of models from the collection. slice: -> slice.apply @models, arguments # Get a model from the set by id. get: (obj) -> return undefined unless obj? @_byId[obj.id ? (obj.cid or obj)] # Get the model at the given index. at: (index) -> @models[index] # Return models with matching attributes. Useful for simple cases of # `filter`. where: (attrs, first) -> if _.isEmpty attrs return if first then undefined else [] @[if first then 'find' else 'filter'] (model) -> for key, v of attrs return false if v != model.get(key) true # Return the first model with matching attributes. Useful for simple cases # of `find`. findWhere: (attrs) -> @where attrs, true # Force the collection to re-sort itself. You don't need to call this under # normal circumstances, as the set will maintain sort order as each item # is added. sort: (options = {}) -> throw new Error('Cannot sort a set without a comparator') unless @comparator # Run sort based on type of `comparator`. if _.isString(@comparator) or @comparator.length is 1 @models = @sortBy @comparator, @ else @models.sort _.bind(@comparator, @) @trigger 'sort', @, options unless options.silent @ # Figure out the smallest index at which a model should be inserted so as # to maintain order. sortedIndex: (model, value, context) -> value = value or @comparator iterator = if _.isFunction value then value else (model) -> model.get(value) _.sortedIndex @models, model, iterator, context # Pluck an attribute from each model in the collection. pluck: (attr) -> _.invoke @models, 'get', attr # Fetch the default set of models for this collection, resetting the # collection when they arrive. If `reset: true` is passed, the response # data will be passed through the `reset` method instead of `set`. fetch: (options = {}) -> options = _.clone options options.parse = true unless options.parse? success = options.success collection = @ options.success = (resp) -> method = if options.reset then 'reset' else 'set' collection[method] resp, options success collection, resp, options if success collection.trigger 'sync', collection, resp, options wrapError @, options @sync 'read', @, options # Create a new instance of a model in this collection. Add the model to the # collection immediately, unless `wait: true` is passed, in which case we # wait for the server to agree. create: (model, options = {}) -> options = _.clone options model = @_prepareModel model, options return false unless model @add(model, options) unless options.wait collection = @ success = options.success options.success = (resp) -> collection.add model, options if options.wait success model, resp, options if success model.save null, options model # **parse** converts a response into a list of models to be added to the # collection. The default implementation is just to pass it through. parse: (resp, options) -> resp # Create a new collection with an identical list of models as this one. clone: -> new @constructor @models # Private method to reset all internal state. Called when the collection # is first initialized or reset. _reset: -> @length = 0 @models = [] @_byId = {} # Prepare a hash of attributes (or other model) to be added to this # collection. _prepareModel: (attrs, options = {}) -> if attrs instanceof Model attrs.collection = @ unless attrs.collection return attrs options.collection = @ model = new @model attrs, options unless model._validate attrs, options @trigger 'invalid', @, attrs, options return false model # Internal method to sever a model's ties to a collection. _removeReference: (model) -> delete model.collection if @ is model.collection model.off 'all', @_onModelEvent, @ # Internal method called every time a model in the set fires an event. # Sets need to update their indexes when models change ids. All other # events simply proxy through. "add" and "remove" events that originate # in other collections are ignored. _onModelEvent: (event, model, collection, options) -> return if (event is 'add' or event is 'remove') and collection != @ @remove model, options if event is 'destroy' if model and event is "change:#{model.idAttribute}" delete @_byId[model.previous model.idAttribute] @_byId[model.id] = model if model.id? @trigger.apply @, arguments Collection = Backbone.Collection # Underscore methods that we want to implement on the Collection. # 90% of the core usefulness of Backbone Collections is actually implemented # right here: methods = [ 'forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf', 'isEmpty', 'chain' ] # Mix in each Underscore method as a proxy to `Collection#models`. _.each methods, (method) -> Collection::[method] = -> args = slice.call arguments args.unshift @models _[method].apply _, args # Underscore methods that take a property name as an argument. attributeMethods = ['groupBy', 'countBy', 'sortBy'] # Use attributes instead of properties. _.each attributeMethods, (method) -> Collection::[method] = (value, context) -> iterator = if _.isFunction(value) then value else (model) -> model.get value _[method] @models, iterator, context ### Backbone.View ------------- Backbone Views are almost more convention than they are actual code. A View is simply a JavaScript object that represents a logical chunk of UI in the DOM. This might be a single item, an entire list, a sidebar or panel, or even the surrounding frame which wraps your whole app. Defining a chunk of UI as a **View** allows you to define your DOM events declaratively, without having to worry about render order ... and makes it easy for the view to react to specific changes in the state of your models. Options with special meaning *(e.g. model, collection, id, className)* are attached directly to the view. See `viewOptions` for an exhaustive list. Creating a Backbone.View creates its initial element outside of the DOM, if an existing element != provided... ### # Cached regex to split keys for `delegate`. delegateEventSplitter = /^(\S+)\s*(.*)$/ # List of view options to be merged as properties. viewOptions = [ 'model' 'collection' 'el' 'id' 'attributes' 'className' 'tagName' 'events' ] class Backbone.View _.extend @::, Events # The default `tagName` of a View's element is `"div"`. tagName: 'div' constructor: (options = {}) -> @cid = _.uniqueId 'view' _.extend @, _.pick(options, viewOptions) @_ensureElement() @initialize.apply @, arguments @delegateEvents() # jQuery delegate for element lookup, scoped to DOM elements within the # current view. This should be prefered to global lookups where possible. $: (selector) -> @$el.find selector # Initialize is an empty function by default. Override it with your own # initialization logic. initialize: -> # pass # **render** is the core function that your view should override, in order # to populate its element (`this.el`), with the appropriate HTML. The # convention is for **render** to always return `this`. render: -> @ # Remove this view by taking the element out of the DOM, and removing any # applicable Backbone.Events listeners. remove: -> @$el.remove() @stopListening() @ # Change the view's element (`this.el` property), including event # re-delegation. setElement: (element, delegate) -> @undelegateEvents() if @$el @$el = if element instanceof Backbone.$ then element else Backbone.$ element @el = @$el[0] @delegateEvents() if delegate != false @ # Set callbacks, where `this.events` is a hash of # # *{"event selector": "callback"}* # # { # 'mousedown .title': 'edit', # 'click .button': 'save' # 'click .open': function(e) { ... } # } # # pairs. Callbacks will be bound to the view, with `this` set properly. # Uses event delegation for efficiency. # Omitting the selector binds the event to `this.el`. # This only works for delegate-able events: not `focus`, `blur`, and # not `change`, `submit`, and `reset` in Internet Explorer. delegateEvents: (events) -> events = events or _.result @, 'events' return @ unless events @undelegateEvents() for key, method of events method = @[events[key]] unless _.isFunction method continue unless method match = key.match delegateEventSplitter eventName = match[1] selector = match[2] method = _.bind method, @ eventName += ".delegateEvents#{@cid}" if selector is '' @$el.on eventName, method else @$el.on eventName, selector, method @ # Clears all callbacks previously bound to the view with `delegateEvents`. # You usually don't need to use this, but may wish to if you have multiple # Backbone views attached to the same DOM element. undelegateEvents: -> @$el.off '.delegateEvents' + @cid @ # Ensure that the View has a DOM element to render into. # If `this.el` is a string, pass it through `$()`, take the first # matching element, and re-assign it to `el`. Otherwise, create # an element from the `id`, `className` and `tagName` properties. _ensureElement: -> if not @el attrs = _.extend {}, _.result(@, 'attributes') attrs.id = _.result(@, 'id') if @id attrs['class'] = _.result(@, 'className') if @className $el = Backbone.$("<#{_.result @, 'tagName'}>").attr attrs @setElement $el, false else @setElement _.result(@, 'el'), false View = Backbone.View ### Backbone.Router --------------- Routers map faux-URLs to actions, and fire events when routes are matched. Creating a new one sets its `routes` hash, if not set statically. ### # Cached regular expressions for matching named param parts and splatted # parts of route strings. optionalParam = /\((.*?)\)/g namedParam = /(\(\?)?:\w+/g splatParam = /\*\w+/g escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g class Backbone.Router _.extend @::, Events constructor: (options = {}) -> @routes = options.routes if options.routes @_bindRoutes() @initialize arguments... # Initialize is an empty function by default. Override it with your own # initialization logic. initialize: -> # pass # Manually bind a single named route to a callback. For example: # # this.route('search/:query/p:num', 'search', function(query, num) { # ... # }); # route: (route, name, callback) -> route = @_routeToRegExp(route) unless _.isRegExp route if _.isFunction name callback = name name = '' callback = @[name] unless callback router = @ Backbone.history.route route, (fragment) -> args = router._extractParameters route, fragment callback?.apply router, args router.trigger.apply router, ['route:' + name].concat(args) router.trigger 'route', name, args Backbone.history.trigger 'route', router, name, args @ # Simple proxy to `Backbone.history` to save a fragment into the history. navigate: (fragment, options) -> Backbone.history.navigate fragment, options @ # Bind all defined routes to `Backbone.history`. We have to reverse the # order of the routes here to support behavior where the most general # routes can be defined at the bottom of the route map. _bindRoutes: -> return unless @routes @routes = _.result @, 'routes' routes = _.keys @routes route = routes.pop() while route? @route route, @routes[route] route = routes.pop() # Convert a route string into a regular expression, suitable for matching # against the current location hash. _routeToRegExp: (route) -> route = route .replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, (match, optional) -> if optional then match else '([^\/]+)') .replace(splatParam, '(.*?)') new RegExp "^#{route}$" # Given a route, and a URL fragment that it matches, return the array of # extracted decoded parameters. Empty or unmatched parameters will be # treated as `null` to normalize cross-browser behavior. _extractParameters: (route, fragment) -> params = route.exec(fragment).slice(1) _.map params, (param) -> if param then decodeURIComponent(param) else null Router = Backbone.Router ### Backbone.History ---------------- Handles cross-browser history management, based on either [pushState](http:#diveintohtml5.info/history.html) and real URLs, or [onhashchange](https:#developer.mozilla.org/en-US/docs/DOM/window.onhashchange) and URL fragments. If the browser supports neither (old IE, natch), falls back to polling. ### # Cached regex for stripping a leading hash/slash and trailing space. routeStripper = /^[#\/]|\s+$/g # Cached regex for stripping leading and trailing slashes. rootStripper = /^\/+|\/+$/g # Cached regex for detecting MSIE. isExplorer = /msie [\w.]+/ # Cached regex for removing a trailing slash. trailingSlash = /\/$/ class Backbone.History _.extend @::, Events # Has the history handling already been started? @started: false # The default interval to poll for hash changes, if necessary, is # twenty times a second. interval: 50 constructor: -> @handlers = [] _.bindAll @, 'checkUrl' # Ensure that `History` can be used outside of the browser. if typeof window != 'undefined' @location = window.location @history = window.history # Gets the true hash value. Cannot use location.hash directly due to bug # in Firefox where location.hash will always be decoded. getHash: (window) -> match = (window or @).location.href.match /#(.*)$/ if match then match[1] else '' # Get the cross-browser normalized URL fragment, either from the URL, # the hash, or the override. getFragment: (fragment, forcePushState) -> unless fragment? if @_hasPushState or not @_wantsHashChange or forcePushState fragment = @location.pathname root = @root.replace trailingSlash, '' fragment = fragment.substr root.length unless fragment.indexOf root else fragment = @getHash() fragment.replace routeStripper, '' # Start the hash change handling, returning `true` if the current URL matches # an existing route, and `false` otherwise. start: (options) -> if History.started throw new Error 'Backbone.history has already been started' History.started = true # Figure out the initial configuration. Do we need an iframe? # Is pushState desired ... is it available? @options = _.extend {}, {root: '/'}, @options, options @root = @options.root @_wantsHashChange = @options.hashChange != false @_wantsPushState = !!@options.pushState @_hasPushState = !!(@options.pushState and @history and @history.pushState) fragment = @getFragment() docMode = document.documentMode oldIE = isExplorer.exec(navigator.userAgent.toLowerCase()) and (not docMode or docMode <= 7) # Normalize root to always include a leading and trailing slash. @root = "/#{@root}/".replace rootStripper, '/' if oldIE and @_wantsHashChange @iframe = Backbone .$('<iframe src="javascript:0" tabindex="-1" />') .hide() .appendTo('body')[0] .contentWindow @navigate fragment # Depending on whether we're using pushState or hashes, and whether # 'onhashchange' is supported, determine how we check the URL state. if @_hasPushState Backbone.$(window).on 'popstate', @checkUrl else if @_wantsHashChange and ('onhashchange' in window) and not oldIE Backbone.$(window).on 'hashchange', @checkUrl else if @_wantsHashChange @_checkUrlInterval = setInterval @checkUrl, @interval # Determine if we need to change the base url, for a pushState link # opened by a non-pushState browser. @fragment = fragment loc = @location atRoot = loc.pathname.replace(/[^\/]$/, '$&/') is @root # If we've started off with a route from a `pushState`-enabled browser, # but we're currently in a browser that doesn't support it... if @_wantsHashChange and @_wantsPushState and not @_hasPushState and not atRoot @fragment = @getFragment null, true @location.replace @root + @location.search + '#' + @fragment # Return immediately as browser will do redirect to new url return true # Or if we've started out with a hash-based route, but we're currently # in a browser where it could be `pushState`-based instead... else if @_wantsPushState and @_hasPushState and atRoot and loc.hash @fragment = @getHash().replace routeStripper, '' @history.replaceState {}, document.title, @root + @fragment + loc.search @loadUrl() unless @options.silent # Disable Backbone.history, perhaps temporarily. Not useful in a real app, # but possibly useful for unit testing Routers. stop: -> Backbone.$(window).off('popstate', @checkUrl).off 'hashchange', @checkUrl clearInterval @_checkUrlInterval History.started = false # Add a route to be tested when the fragment changes. Routes added later # may override previous routes. route: (route, callback) -> @handlers.unshift(route: route, callback: callback) # Checks the current URL to see if it has changed, and if it has, # calls `loadUrl`, normalizing across the hidden iframe. checkUrl: (e) -> current = @getFragment() if current is @fragment and @iframe current = @getFragment @getHash(@iframe) return false if current is @fragment @navigate(current) if @iframe @loadUrl() or @loadUrl @getHash() # Attempt to load the current URL fragment. If a route succeeds with a # match, returns `true`. If no defined routes matches the fragment, # returns `false`. loadUrl: (fragmentOverride) -> @fragment = @getFragment fragmentOverride fragment = @fragment matched = _.any @handlers, (handler) -> if handler.route.test fragment handler.callback fragment true matched # Save a fragment into the hash history, or replace the URL state if the # 'replace' option is passed. You are responsible for properly URL-encoding # the fragment in advance. # # The options object can contain `trigger: true` if you wish to have the # route callback be fired (not usually desirable), or `replace: true`, if # you wish to modify the current URL without adding an entry to the history. navigate: (fragment, options) -> return false unless History.started options = trigger: options if not options or options is true fragment = @getFragment fragment or '' return if @fragment is fragment @fragment = fragment url = @root + fragment # If pushState is available, we use it to set the fragment as a real URL. if @_hasPushState method = if options.replace then 'replaceState' else 'pushState' @history[method] {}, document.title, url # If hash changes haven't been explicitly disabled, update the hash # fragment to store history. else if @_wantsHashChange @_updateHash @location, fragment, options.replace if @iframe and (fragment != @getFragment(@getHash @iframe)) # Opening and closing the iframe tricks IE7 and earlier to push a # history entry on hash-tag change. When replace is true, we don't # want this. @iframe.document.open().close() unless options.replace @_updateHash @iframe.location, fragment, options.replace # If you've told us that you explicitly don't want fallback hashchange- # based history, then `navigate` becomes a page refresh. else return @location.assign url @loadUrl fragment if options.trigger # Update the hash location, either replacing the current entry, or adding # a new one to the browser history. _updateHash: (location, fragment, replace) -> if replace href = location.href.replace /(javascript:|#).*$/, '' location.replace href + '#' + fragment else # Some browsers require that `hash` contains a leading #. location.hash = '#' + fragment History = Backbone.History # Create the default Backbone.history. Backbone.history = new History ### Helpers ------- Helper function to correctly set up the prototype chain, for subclasses. Similar to `goog.inherits`, but uses a hash of prototype properties and class properties to be extended. ### extend = (protoProps, staticProps) -> parent = @ # The constructor function for the new subclass is either defined by you # (the "constructor" property in your `extend` definition), or defaulted # by us to simply call the parent's constructor. if protoProps and _.has protoProps, 'constructor' child = protoProps.constructor else child = -> parent.apply @, arguments # Add static properties to the constructor function, if supplied. _.extend child, parent, staticProps # Set the prototype chain to inherit from `parent`, without calling # `parent`'s constructor function. class Surrogate constructor: -> @constructor = child Surrogate.prototype = parent.prototype child.prototype = new Surrogate # Add prototype properties (instance properties) to the subclass, # if supplied. _.extend(child.prototype, protoProps) if protoProps # Set a convenience property in case the parent's prototype is needed # later. child.__super__ = parent.prototype child # Set up inheritance for the model, collection, router, view and history. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend # Throw an error when a URL is needed, and none is supplied. urlError = -> throw new Error 'A "url" property or function must be specified' # Wrap an optional error callback with a fallback error event. wrapError = (model, options) -> error = options.error options.error = (resp) -> error(model, resp, options) if error model.trigger 'error', model, resp, options
62039
### Backbone.js 1.0.0 (c) 2010-2011 <NAME>, DocumentCloud Inc. (c) 2011-2013 <NAME>, DocumentCloud and Investigative Reporters & Editors Backbone may be freely distributed under the MIT license. For all details and documentation: http://www.backbonecoffee.org ### # Initial Setup # ------------- # Save a reference to the global object (`window` in the browser, `exports` # on the server). root = @ # Save the previous value of the `Backbone` variable, so that it can be # restored later on, if `noConflict` is used. previousBackbone = root.Backbone # Create local references to array methods we'll want to use later. array = [] push = array.push slice = array.slice splice = array.splice # The top-level namespace. All public Backbone classes and modules will # be attached to this. Exported for both the browser and the server. if exports? Backbone = exports else root.Backbone = {} Backbone = root.Backbone # Require Underscore, if we're on the server, and it's not already present. _ = root._ _ = require 'underscore' if not _? and require? # Map from CRUD to HTTP for our default `Backbone.sync` implementation. methodMap = create: 'POST' update: 'PUT' patch: 'PATCH' delete: 'DELETE' read: 'GET' _.extend Backbone, # Current version of the library. Keep in sync with `package.json`. VERSION: '1.0.0' # For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns # the `$` variable. $: root.jQuery or root.Zepto or root.ender or root.$ # Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable # to its previous owner. Returns a reference to this Backbone object. noConflict: -> root.Backbone = previousBackbone @ # Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option # will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and # set a `X-Http-Method-Override` header. emulateHTTP: false # Turn on `emulateJSON` to support legacy servers that can't deal with direct # `application/json` requests ... will encode the body as # `application/x-www-form-urlencoded` instead and will send the model in a # form param named `model`. emulateJSON: false # Set the default implementation of `Backbone.ajax` to proxy through to `$`. # Override this if you'd like to use a different library. ajax: -> Backbone.$.ajax arguments... # Backbone.sync # ------------- # # Override this function to change the manner in which Backbone persists # models to the server. You will be passed the type of request, and the # model in question. By default, makes a RESTful Ajax request # to the model's `url()`. Some possible customizations could be: # # * Use `setTimeout` to batch rapid-fire updates into a single request. # * Send up the models as XML instead of JSON. # * Persist models via WebSockets instead of Ajax. # # Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests # as `POST`, with a `_method` parameter containing the true HTTP method, # as well as all requests with the body as `application/x-www-form-urlencoded` # instead of `application/json` with the model in a param named `model`. # Useful when interfacing with server-side languages like **PHP** that make # it difficult to read the body of `PUT` requests. sync: (method, model, options = {}) -> type = methodMap[method] # Default options, unless specified. _.defaults options, emulateHTTP: Backbone.emulateHTTP emulateJSON: Backbone.emulateJSON # Default JSON-request options. params = type: type dataType: 'json' # Ensure that we have a URL. params.url = _.result(model, 'url') or urlError() unless options.url # Ensure that we have the appropriate request data. if not options.data? and model and (method is 'create' or method is 'update' or method is 'patch') params.contentType = 'application/json' params.data = JSON.stringify(options.attrs or model.toJSON options) # For older servers, emulate JSON by encoding the request into an HTML-form. if options.emulateJSON params.contentType = 'application/x-www-form-urlencoded' params.data = if params.data then model: params.data else {} # For older servers, emulate HTTP by mimicking the HTTP method with # `_method` and an `X-HTTP-Method-Override` header. if options.emulateHTTP and (type is 'PUT' or type is 'DELETE' or type is 'PATCH') params.type = 'POST' params.data._method = type if options.emulateJSON beforeSend = options.beforeSend options.beforeSend = (xhr) -> xhr.setRequestHeader 'X-HTTP-Method-Override', type beforeSend.apply @, arguments if beforeSend # Don't process data on a non-GET request. if params.type != 'GET' and not options.emulateJSON params.processData = false # If we're sending a `PATCH` request, and we're in an old Internet Explorer # that still has ActiveX enabled by default, override jQuery to use that # for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. if params.type is 'PATCH' and window.ActiveXObject and not (window.external and window.external.msActiveXFilteringEnabled) params.xhr = -> new ActiveXObject 'Microsoft.XMLHTTP' # Make the request, allowing the user to override any Ajax options. options.xhr = Backbone.ajax _.extend(params, options) xhr = options.xhr model.trigger 'request', model, xhr, options xhr ### Backbone.Events --------------- A module that can be mixed in to *any object* in order to provide it with custom events. You may bind with `on` or remove with `off` callback functions to an event; `trigger`-ing an event fires all callbacks in succession. var object = {}; _.extend(object, Backbone.Events); object.on('expand', function(){ alert('expanded'); }); object.trigger('expand'); ### class Backbone.Events # Bind an event to a `callback` function. Passing `"all"` will bind # the callback to all events fired. @on: (name, callback, context) -> return @ unless eventsApi(@, 'on', name, [callback, context]) and callback @_events ?= {} @_events[name] ?= [] events = @_events[name] events.push callback: callback context: context ctx: context or @ @ # Bind an event to only be triggered a single time. After the first time # the callback is invoked, it will be removed. @once: (name, callback, context) -> if not eventsApi(@, 'once', name, [callback, context]) or not callback return @ self = @ once = _.once -> self.off name, once callback.apply @, arguments once._callback = callback @on name, once, context # Remove one or many callbacks. If `context` is null, removes all # callbacks with that function. If `callback` is null, removes all # callbacks for the event. If `name` is null, removes all bound # callbacks for all events. @off: (name, callback, context) -> if not @_events or not eventsApi @, 'off', name, [callback, context] return @ if not name and not callback and not context @_events = {} return @ names = if name then [name] else _.keys @_events for name in names events = @_events[name] if events retain = [] @_events[name] = retain if callback or context for ev in events if (callback and callback != ev.callback and callback != ev.callback._callback) or (context and context != ev.context) retain.push ev delete @_events[name] unless retain.length @ # Trigger one or many events, firing all bound callbacks. Callbacks are # passed the same arguments as `trigger` is, apart from the event name # (unless you're listening on `"all"`, which will cause your callback to # receive the true name of the event as the first argument). @trigger: (name) -> return @ unless @_events args = slice.call arguments, 1 return @ unless eventsApi @, 'trigger', name, args events = @_events[name] allEvents = @_events.all triggerEvents events, args if events triggerEvents allEvents, arguments if allEvents @ # Tell this object to stop listening to either specific events ... or # to every object it's currently listening to. @stopListening: (obj, name, callback) -> listeners = @_listeners return @ unless listeners deleteListener = not name and not callback callback = @ if _.isObject name if obj listeners = {} listeners[obj._listenerId] = obj for id, v of listeners listeners[id].off name, callback, @ delete @_listeners[id] if deleteListener @ Events = Backbone.Events # Regular expression used to split event strings. eventSplitter = /\s+/ # Implement fancy features of the Events API such as multiple event # names `"change blur"` and jQuery-style event maps `{change: action}` # in terms of the existing API. eventsApi = (obj, action, name, rest) -> return true unless name # Handle event maps. if _.isObject name for key, v of name obj[action] ([key, name[key]].concat rest)... return false # Handle space separated event names. if eventSplitter.test name names = name.split eventSplitter for i in [0...names.length] obj[action] ([names[i]].concat rest)... return false true # A difficult-to-believe, but optimized internal dispatch function for # triggering events. Tries to keep the usual cases speedy (most internal # Backbone events have 3 arguments). triggerEvents = (events, args) -> i = -1 l = events.length [a1, a2, a3] = args switch args.length when 0 while ++i < l ev = events[i] ev.callback.call ev.ctx when 1 while ++i < l ev = events[i] ev.callback.call ev.ctx, a1 when 2 while ++i < l ev = events[i] ev.callback.call ev.ctx, a1, a2 when 3 while ++i < l ev = events[i] ev.callback.call ev.ctx, a1, a2, a3 else while ++i < l ev = events[i] ev.callback.apply ev.ctx, args listenMethods = listenTo: 'on' listenToOnce: 'once' # Inversion-of-control versions of `on` and `once`. Tell *this* object to # listen to an event in another object ... keeping track of what it's # listening to. _.each listenMethods, (implementation, method) -> Events[method] = (obj, name, callback) -> @_listeners ?= {} listeners = @_listeners obj._listenerId ?= _.uniqueId 'l' id = obj._listenerId listeners[id] = obj callback = @ if _.isObject name obj[implementation] name, callback, @ @ # Aliases for backwards compatibility. Events.bind = Events.on Events.unbind = Events.off # Allow the `Backbone` object to serve as a global event bus, for folks who # want global "pubsub" in a convenient place. _.extend Backbone, Events ### Backbone.Model -------------- Backbone **Models** are the basic data object in the framework -- frequently representing a row in a table in a database on your server. A discrete chunk of data and a bunch of useful, related methods for performing computations and transformations on that data. Create a new model with the specified attributes. A client id (`cid`) is automatically generated and assigned for you. ### class Backbone.Model _.extend @::, Events # A hash of attributes whose current and previous value differ. changed: null # The value returned during the last failed validation. validationError: null # The default name for the JSON `id` attribute is `"id"`. MongoDB and # CouchDB users may want to set this to `"_id"`. idAttribute: 'id' constructor: (attributes, options = {}) -> attrs = attributes or {} @cid = _.uniqueId 'c' @attributes = {} @collection = options.collection if options.collection attrs = @parse(attrs, options) or {} if options.parse options._attrs = attrs defaults = _.result @, 'defaults' attrs = _.defaults {}, attrs, defaults if defaults @set attrs, options @changed = {} @initialize arguments... # Initialize is an empty function by default. Override it with your own # initialization logic. initialize: -> # pass # Return a copy of the model's `attributes` object. toJSON: (options) -> _.clone @attributes # Proxy `Backbone.sync` by default -- but override this if you need # custom syncing semantics for *this* particular model. sync: -> Backbone.sync.apply @, arguments # Get the value of an attribute. get: (attr) -> @attributes[attr] # Get the HTML-escaped value of an attribute. escape: (attr) -> _.escape @get(attr) # Returns `true` if the attribute contains a value that != null # or undefined. has: (attr) -> @get(attr)? # Set a hash of model attributes on the object, firing `"change"`. This is # the core primitive operation of a model, updating the data and notifying # anyone who needs to know about the change in state. The heart of the beast. set: (key, val, options = {}) -> return this unless key? # Handle both `"key", value` and `{key: value}` -style arguments. if _.isObject key attrs = key options = val or {} else attrs = {} attrs[key] = val # Run validation. return false unless @_validate attrs, options # Extract attributes and options. unset = options.unset silent = options.silent changes = [] changing = @_changing @_changing = true unless changing @_previousAttributes = _.clone @attributes @changed = {} current = @attributes prev = @_previousAttributes # Check for changes of `id`. @id = attrs[@idAttribute] if _.has attrs, @idAttribute # For each `set` attribute, update or delete the current value. for attr, v of attrs val = attrs[attr] changes.push(attr) unless _.isEqual current[attr], val unless _.isEqual prev[attr], val @changed[attr] = val else delete @changed[attr] if unset delete current[attr] else current[attr] = val # Trigger all relevant attribute changes. unless silent @_pending = true if changes.length for change in changes @trigger 'change:' + change, @, current[change], options # You might be wondering why there's a `while` loop here. Changes can # be recursively nested within `"change"` events. return @ if changing unless silent while @_pending @_pending = false @trigger 'change', @, options @_pending = false @_changing = false @ # Remove an attribute from the model, firing `"change"`. `unset` is a noop # if the attribute doesn't exist. unset: (attr, options) -> @set attr, undefined, _.extend({}, options, unset: true) # Clear all attributes on the model, firing `"change"`. clear: (options) -> attrs = {} for key, v of @attributes attrs[key] = undefined @set attrs, _.extend({}, options, unset: true) # Determine if the model has changed since the last `"change"` event. # If you specify an attribute name, determine if that attribute has changed. hasChanged: (attr) -> return not _.isEmpty @changed unless attr? return _.has @changed, attr # Return an object containing all the attributes that have changed, or # false if there are no changed attributes. Useful for determining what # parts of a view need to be updated and/or what attributes need to be # persisted to the server. Unset attributes will be set to undefined. # You can also pass an attributes object to diff against the model, # determining if there *would be* a change. changedAttributes: (diff) -> unless diff return if @hasChanged() then _.clone(@changed) else false changed = false old = if @_changing then @_previousAttributes else @attributes for attr, v of diff continue if _.isEqual old[attr], v changed = {} unless changed changed[attr] = v return changed # Get the previous value of an attribute, recorded at the time the last # `"change"` event was fired. previous: (attr) -> return null if not attr? or not @_previousAttributes return @_previousAttributes[attr] # Get all of the attributes of the model at the time of the previous # `"change"` event. previousAttributes: -> _.clone @_previousAttributes # Fetch the model from the server. If the server's representation of the # model differs from its current attributes, they will be overridden, # triggering a `"change"` event. fetch: (options = {}) -> options = _.clone options options.parse = true unless options.parse? model = @ success = options.success options.success = (resp) -> return false unless model.set model.parse(resp, options), options success(model, resp, options) if success model.trigger 'sync', model, resp, options wrapError this, options @sync 'read', this, options # Set a hash of model attributes, and sync the model to the server. # If the server returns an attributes hash that differs, the model's # state will be `set` again. save: (key, val, options) -> attributes = @attributes # Handle both `"key", value` and `{key: value}` -style arguments. if not key? or _.isObject key attrs = key options = val else attrs = {} attrs[key] = val options = _.extend {validate: true}, options # If we're not waiting and attributes exist, save acts as # `set(attr).save(null, opts)` with validation. Otherwise, check if # the model will be valid when the attributes, if any, are set. if attrs and not options.wait return false unless @set attrs, options else return false unless @_validate attrs, options # Set temporary attributes if `{wait: true}`. if attrs and options.wait @attributes = _.extend {}, attributes, attrs # After a successful server-side save, the client is (optionally) # updated with the server-side state. options.parse = true unless options.parse? model = @ success = options.success options.success = (resp) -> # Ensure attributes are restored during synchronous saves. model.attributes = attributes serverAttrs = model.parse resp, options serverAttrs = _.extend(attrs or {}, serverAttrs) if options.wait if _.isObject(serverAttrs) and not model.set serverAttrs, options return false success model, resp, options if success model.trigger 'sync', model, resp, options wrapError @, options if @isNew() method = 'create' else method = (if options.patch then 'patch' else 'update') options.attrs = attrs if method is 'patch' xhr = @sync method, @, options # Restore attributes. @attributes = attributes if attrs and options.wait xhr # Destroy this model on the server if it was already persisted. # Optimistically removes the model from its collection, if it has one. # If `wait: true` is passed, waits for the server to respond before removal. destroy: (options = {}) -> options = _.clone options model = @ success = options.success destroy = -> model.trigger 'destroy', model, model.collection, options options.success = (resp) -> destroy() if options.wait or model.isNew() success(model, resp, options) if success model.trigger('sync', model, resp, options) unless model.isNew() if @isNew() options.success() return false wrapError @, options xhr = @sync 'delete', @, options destroy() unless options.wait xhr # Default URL for the model's representation on the server -- if you're # using Backbone's restful methods, override this to change the endpoint # that will be called. url: -> base = _.result(@, 'urlRoot') or _.result(@collection, 'url') or urlError() return base if @isNew() base + (if base.charAt(base.length - 1) is '/' then '' else '/') + encodeURIComponent @id # **parse** converts a response into the hash of attributes to be `set` on # the model. The default implementation is just to pass the response along. parse: (resp, options) -> resp # Create a new model with identical attributes to this one. clone: -> new @constructor @attributes # A model is new if it has never been saved to the server, and lacks an id. isNew: -> not @id? # Check if the model is currently in a valid state. isValid: (options) -> @_validate {}, _.extend(options or {}, validate: true) # Run validation against the next complete set of model attributes, # returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate: (attrs, options = {}) -> return true if not options.validate or not @validate attrs = _.extend {}, @attributes, attrs @validationError = @validate(attrs, options) or null error = @validationError return true unless error @trigger 'invalid', @, error, _.extend(options or {}, validationError: error) false Model = Backbone.Model # Underscore methods that we want to implement on the Model. modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'] # Mix in each Underscore method as a proxy to `Model#attributes`. _.each modelMethods, (method) -> Model.prototype[method] = -> args = slice.call arguments args.unshift @attributes _[method] args... ### Backbone.Collection ------------------- If models tend to represent a single row of data, a Backbone Collection is more analagous to a table full of data ... or a small slice or page of that table, or a collection of rows that belong together for a particular reason -- all of the messages in this particular folder, all of the documents belonging to this particular author, and so on. Collections maintain indexes of their models, both in order, and for lookup by `id`. Create a new **Collection**, perhaps to contain a specific type of `model`. If a `comparator` is specified, the Collection will maintain its models in sort order, as they're added and removed. ### # Default options for `Collection#set`. setOptions = add: true remove: true merge: true addOptions = add: true merge: false remove: false class Backbone.Collection _.extend @::, Events # The default model for a collection is just a **Backbone.Model**. # This should be overridden in most cases. model: Model constructor: (models, options) -> options or= {} @model = options.model if options.model @comparator = options.comparator unless _.isUndefined options.comparator @_reset() @initialize arguments... @reset models, _.extend({silent: true}, options) if models # Initialize is an empty function by default. Override it with your own # initialization logic. initialize: -> # pass # The JSON representation of a Collection is an array of the # models' attributes. toJSON: (options) -> @map (model) -> model.toJSON options # Proxy `Backbone.sync` by default. sync: -> Backbone.sync.apply @, arguments # Add a model, or list of models to the set. add: (models, options = {}) -> @set models, _.defaults(options, addOptions) # Remove a model, or a list of models from the set. remove: (models, options = {}) -> models = if _.isArray(models) then models.slice() else [models] for i in [0...models.length] model = @get models[i] continue unless model delete @_byId[model.id] delete @_byId[model.cid] index = @indexOf model @models.splice index, 1 @length-- unless options.silent options.index = index model.trigger 'remove', model, @, options @_removeReference model @ # Update a collection by `set`-ing a new list of models, adding new ones, # removing models that are no longer present, and merging models that # already exist in the collection, as necessary. Similar to **Model#set**, # the core operation for updating the data contained by the collection. set: (models, options = {}) -> options = _.defaults options, setOptions models = @parse(models, options) if options.parse unless _.isArray models models = if models then [models] else [] at = options.at sortable = @comparator and not at? and options.sort != false sortAttr = if _.isString @comparator then @comparator else null toAdd = [] toRemove = [] modelMap = {} add = options.add merge = options.merge remove = options.remove order = if not sortable and add and remove then [] else false # Turn bare objects into model references, and prevent invalid models # from being added. for i in [0...models.length] attrs = models[i] model = @_prepareModel attrs, options continue unless model # If a duplicate is found, prevent it from being added and # optionally merge it into the existing model. existing = @get model if existing modelMap[existing.cid] = true if remove if merge attrs = if attrs is model then model.attributes else options._attrs existing.set attrs, options sort = true if sortable and not sort and existing.hasChanged sortAttr # This is a new model, push it to the `toAdd` list. else if add toAdd.push model # Listen to added models' events, and index models for lookup by # `id` and by `cid`. model.on 'all', @_onModelEvent, @ @_byId[model.cid] = model @_byId[model.id] = model if model.id? order.push(existing or model) if order # Remove nonexistent models if appropriate. if remove for i in [0...@length] model = @models[i] toRemove.push model unless modelMap[model.cid] @remove(toRemove, options) if toRemove.length # See if sorting is needed, update `length` and splice in new models. if toAdd.length or (order and order.length) sort = true if sortable @length += toAdd.length if at? splice.apply @models, [at, 0].concat(toAdd) else @models.length = 0 if order push.apply @models, (order or toAdd) # Silently sort the collection if appropriate. @sort silent: true if sort return @ if options.silent # Trigger `add` events. for model in toAdd model.trigger 'add', model, @, options # Trigger `sort` if the collection was sorted. @trigger 'sort', @, options if sort or (order and order.length) @ # When you have more items than you want to add or remove individually, # you can reset the entire set with a new list of models, without firing # any granular `add` or `remove` events. Fires `reset` when finished. # Useful for bulk operations and optimizations. reset: (models, options = {}) -> @_removeReference model for model in @models options.previousModels = @models @_reset() @add models, _.extend({silent: true}, options) @trigger 'reset', @, options unless options.silent @ # Add a model to the end of the collection. push: (model, options) -> model = @_prepareModel model, options @add model, _.extend({at: @length}, options) model # Remove a model from the end of the collection. pop: (options) -> model = @at(@length - 1) @remove model, options model # Add a model to the beginning of the collection. unshift: (model, options) -> model = @_prepareModel model, options @add model, _.extend({at: 0}, options) model # Remove a model from the beginning of the collection. shift: (options) -> model = @at 0 @remove model, options model # Slice out a sub-array of models from the collection. slice: -> slice.apply @models, arguments # Get a model from the set by id. get: (obj) -> return undefined unless obj? @_byId[obj.id ? (obj.cid or obj)] # Get the model at the given index. at: (index) -> @models[index] # Return models with matching attributes. Useful for simple cases of # `filter`. where: (attrs, first) -> if _.isEmpty attrs return if first then undefined else [] @[if first then 'find' else 'filter'] (model) -> for key, v of attrs return false if v != model.get(key) true # Return the first model with matching attributes. Useful for simple cases # of `find`. findWhere: (attrs) -> @where attrs, true # Force the collection to re-sort itself. You don't need to call this under # normal circumstances, as the set will maintain sort order as each item # is added. sort: (options = {}) -> throw new Error('Cannot sort a set without a comparator') unless @comparator # Run sort based on type of `comparator`. if _.isString(@comparator) or @comparator.length is 1 @models = @sortBy @comparator, @ else @models.sort _.bind(@comparator, @) @trigger 'sort', @, options unless options.silent @ # Figure out the smallest index at which a model should be inserted so as # to maintain order. sortedIndex: (model, value, context) -> value = value or @comparator iterator = if _.isFunction value then value else (model) -> model.get(value) _.sortedIndex @models, model, iterator, context # Pluck an attribute from each model in the collection. pluck: (attr) -> _.invoke @models, 'get', attr # Fetch the default set of models for this collection, resetting the # collection when they arrive. If `reset: true` is passed, the response # data will be passed through the `reset` method instead of `set`. fetch: (options = {}) -> options = _.clone options options.parse = true unless options.parse? success = options.success collection = @ options.success = (resp) -> method = if options.reset then 'reset' else 'set' collection[method] resp, options success collection, resp, options if success collection.trigger 'sync', collection, resp, options wrapError @, options @sync 'read', @, options # Create a new instance of a model in this collection. Add the model to the # collection immediately, unless `wait: true` is passed, in which case we # wait for the server to agree. create: (model, options = {}) -> options = _.clone options model = @_prepareModel model, options return false unless model @add(model, options) unless options.wait collection = @ success = options.success options.success = (resp) -> collection.add model, options if options.wait success model, resp, options if success model.save null, options model # **parse** converts a response into a list of models to be added to the # collection. The default implementation is just to pass it through. parse: (resp, options) -> resp # Create a new collection with an identical list of models as this one. clone: -> new @constructor @models # Private method to reset all internal state. Called when the collection # is first initialized or reset. _reset: -> @length = 0 @models = [] @_byId = {} # Prepare a hash of attributes (or other model) to be added to this # collection. _prepareModel: (attrs, options = {}) -> if attrs instanceof Model attrs.collection = @ unless attrs.collection return attrs options.collection = @ model = new @model attrs, options unless model._validate attrs, options @trigger 'invalid', @, attrs, options return false model # Internal method to sever a model's ties to a collection. _removeReference: (model) -> delete model.collection if @ is model.collection model.off 'all', @_onModelEvent, @ # Internal method called every time a model in the set fires an event. # Sets need to update their indexes when models change ids. All other # events simply proxy through. "add" and "remove" events that originate # in other collections are ignored. _onModelEvent: (event, model, collection, options) -> return if (event is 'add' or event is 'remove') and collection != @ @remove model, options if event is 'destroy' if model and event is "change:#{model.idAttribute}" delete @_byId[model.previous model.idAttribute] @_byId[model.id] = model if model.id? @trigger.apply @, arguments Collection = Backbone.Collection # Underscore methods that we want to implement on the Collection. # 90% of the core usefulness of Backbone Collections is actually implemented # right here: methods = [ 'forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf', 'isEmpty', 'chain' ] # Mix in each Underscore method as a proxy to `Collection#models`. _.each methods, (method) -> Collection::[method] = -> args = slice.call arguments args.unshift @models _[method].apply _, args # Underscore methods that take a property name as an argument. attributeMethods = ['groupBy', 'countBy', 'sortBy'] # Use attributes instead of properties. _.each attributeMethods, (method) -> Collection::[method] = (value, context) -> iterator = if _.isFunction(value) then value else (model) -> model.get value _[method] @models, iterator, context ### Backbone.View ------------- Backbone Views are almost more convention than they are actual code. A View is simply a JavaScript object that represents a logical chunk of UI in the DOM. This might be a single item, an entire list, a sidebar or panel, or even the surrounding frame which wraps your whole app. Defining a chunk of UI as a **View** allows you to define your DOM events declaratively, without having to worry about render order ... and makes it easy for the view to react to specific changes in the state of your models. Options with special meaning *(e.g. model, collection, id, className)* are attached directly to the view. See `viewOptions` for an exhaustive list. Creating a Backbone.View creates its initial element outside of the DOM, if an existing element != provided... ### # Cached regex to split keys for `delegate`. delegateEventSplitter = /^(\S+)\s*(.*)$/ # List of view options to be merged as properties. viewOptions = [ 'model' 'collection' 'el' 'id' 'attributes' 'className' 'tagName' 'events' ] class Backbone.View _.extend @::, Events # The default `tagName` of a View's element is `"div"`. tagName: 'div' constructor: (options = {}) -> @cid = _.uniqueId 'view' _.extend @, _.pick(options, viewOptions) @_ensureElement() @initialize.apply @, arguments @delegateEvents() # jQuery delegate for element lookup, scoped to DOM elements within the # current view. This should be prefered to global lookups where possible. $: (selector) -> @$el.find selector # Initialize is an empty function by default. Override it with your own # initialization logic. initialize: -> # pass # **render** is the core function that your view should override, in order # to populate its element (`this.el`), with the appropriate HTML. The # convention is for **render** to always return `this`. render: -> @ # Remove this view by taking the element out of the DOM, and removing any # applicable Backbone.Events listeners. remove: -> @$el.remove() @stopListening() @ # Change the view's element (`this.el` property), including event # re-delegation. setElement: (element, delegate) -> @undelegateEvents() if @$el @$el = if element instanceof Backbone.$ then element else Backbone.$ element @el = @$el[0] @delegateEvents() if delegate != false @ # Set callbacks, where `this.events` is a hash of # # *{"event selector": "callback"}* # # { # 'mousedown .title': 'edit', # 'click .button': 'save' # 'click .open': function(e) { ... } # } # # pairs. Callbacks will be bound to the view, with `this` set properly. # Uses event delegation for efficiency. # Omitting the selector binds the event to `this.el`. # This only works for delegate-able events: not `focus`, `blur`, and # not `change`, `submit`, and `reset` in Internet Explorer. delegateEvents: (events) -> events = events or _.result @, 'events' return @ unless events @undelegateEvents() for key, method of events method = @[events[key]] unless _.isFunction method continue unless method match = key.match delegateEventSplitter eventName = match[1] selector = match[2] method = _.bind method, @ eventName += ".delegateEvents#{@cid}" if selector is '' @$el.on eventName, method else @$el.on eventName, selector, method @ # Clears all callbacks previously bound to the view with `delegateEvents`. # You usually don't need to use this, but may wish to if you have multiple # Backbone views attached to the same DOM element. undelegateEvents: -> @$el.off '.delegateEvents' + @cid @ # Ensure that the View has a DOM element to render into. # If `this.el` is a string, pass it through `$()`, take the first # matching element, and re-assign it to `el`. Otherwise, create # an element from the `id`, `className` and `tagName` properties. _ensureElement: -> if not @el attrs = _.extend {}, _.result(@, 'attributes') attrs.id = _.result(@, 'id') if @id attrs['class'] = _.result(@, 'className') if @className $el = Backbone.$("<#{_.result @, 'tagName'}>").attr attrs @setElement $el, false else @setElement _.result(@, 'el'), false View = Backbone.View ### Backbone.Router --------------- Routers map faux-URLs to actions, and fire events when routes are matched. Creating a new one sets its `routes` hash, if not set statically. ### # Cached regular expressions for matching named param parts and splatted # parts of route strings. optionalParam = /\((.*?)\)/g namedParam = /(\(\?)?:\w+/g splatParam = /\*\w+/g escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g class Backbone.Router _.extend @::, Events constructor: (options = {}) -> @routes = options.routes if options.routes @_bindRoutes() @initialize arguments... # Initialize is an empty function by default. Override it with your own # initialization logic. initialize: -> # pass # Manually bind a single named route to a callback. For example: # # this.route('search/:query/p:num', 'search', function(query, num) { # ... # }); # route: (route, name, callback) -> route = @_routeToRegExp(route) unless _.isRegExp route if _.isFunction name callback = name name = '' callback = @[name] unless callback router = @ Backbone.history.route route, (fragment) -> args = router._extractParameters route, fragment callback?.apply router, args router.trigger.apply router, ['route:' + name].concat(args) router.trigger 'route', name, args Backbone.history.trigger 'route', router, name, args @ # Simple proxy to `Backbone.history` to save a fragment into the history. navigate: (fragment, options) -> Backbone.history.navigate fragment, options @ # Bind all defined routes to `Backbone.history`. We have to reverse the # order of the routes here to support behavior where the most general # routes can be defined at the bottom of the route map. _bindRoutes: -> return unless @routes @routes = _.result @, 'routes' routes = _.keys @routes route = routes.pop() while route? @route route, @routes[route] route = routes.pop() # Convert a route string into a regular expression, suitable for matching # against the current location hash. _routeToRegExp: (route) -> route = route .replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, (match, optional) -> if optional then match else '([^\/]+)') .replace(splatParam, '(.*?)') new RegExp "^#{route}$" # Given a route, and a URL fragment that it matches, return the array of # extracted decoded parameters. Empty or unmatched parameters will be # treated as `null` to normalize cross-browser behavior. _extractParameters: (route, fragment) -> params = route.exec(fragment).slice(1) _.map params, (param) -> if param then decodeURIComponent(param) else null Router = Backbone.Router ### Backbone.History ---------------- Handles cross-browser history management, based on either [pushState](http:#diveintohtml5.info/history.html) and real URLs, or [onhashchange](https:#developer.mozilla.org/en-US/docs/DOM/window.onhashchange) and URL fragments. If the browser supports neither (old IE, natch), falls back to polling. ### # Cached regex for stripping a leading hash/slash and trailing space. routeStripper = /^[#\/]|\s+$/g # Cached regex for stripping leading and trailing slashes. rootStripper = /^\/+|\/+$/g # Cached regex for detecting MSIE. isExplorer = /msie [\w.]+/ # Cached regex for removing a trailing slash. trailingSlash = /\/$/ class Backbone.History _.extend @::, Events # Has the history handling already been started? @started: false # The default interval to poll for hash changes, if necessary, is # twenty times a second. interval: 50 constructor: -> @handlers = [] _.bindAll @, 'checkUrl' # Ensure that `History` can be used outside of the browser. if typeof window != 'undefined' @location = window.location @history = window.history # Gets the true hash value. Cannot use location.hash directly due to bug # in Firefox where location.hash will always be decoded. getHash: (window) -> match = (window or @).location.href.match /#(.*)$/ if match then match[1] else '' # Get the cross-browser normalized URL fragment, either from the URL, # the hash, or the override. getFragment: (fragment, forcePushState) -> unless fragment? if @_hasPushState or not @_wantsHashChange or forcePushState fragment = @location.pathname root = @root.replace trailingSlash, '' fragment = fragment.substr root.length unless fragment.indexOf root else fragment = @getHash() fragment.replace routeStripper, '' # Start the hash change handling, returning `true` if the current URL matches # an existing route, and `false` otherwise. start: (options) -> if History.started throw new Error 'Backbone.history has already been started' History.started = true # Figure out the initial configuration. Do we need an iframe? # Is pushState desired ... is it available? @options = _.extend {}, {root: '/'}, @options, options @root = @options.root @_wantsHashChange = @options.hashChange != false @_wantsPushState = !!@options.pushState @_hasPushState = !!(@options.pushState and @history and @history.pushState) fragment = @getFragment() docMode = document.documentMode oldIE = isExplorer.exec(navigator.userAgent.toLowerCase()) and (not docMode or docMode <= 7) # Normalize root to always include a leading and trailing slash. @root = "/#{@root}/".replace rootStripper, '/' if oldIE and @_wantsHashChange @iframe = Backbone .$('<iframe src="javascript:0" tabindex="-1" />') .hide() .appendTo('body')[0] .contentWindow @navigate fragment # Depending on whether we're using pushState or hashes, and whether # 'onhashchange' is supported, determine how we check the URL state. if @_hasPushState Backbone.$(window).on 'popstate', @checkUrl else if @_wantsHashChange and ('onhashchange' in window) and not oldIE Backbone.$(window).on 'hashchange', @checkUrl else if @_wantsHashChange @_checkUrlInterval = setInterval @checkUrl, @interval # Determine if we need to change the base url, for a pushState link # opened by a non-pushState browser. @fragment = fragment loc = @location atRoot = loc.pathname.replace(/[^\/]$/, '$&/') is @root # If we've started off with a route from a `pushState`-enabled browser, # but we're currently in a browser that doesn't support it... if @_wantsHashChange and @_wantsPushState and not @_hasPushState and not atRoot @fragment = @getFragment null, true @location.replace @root + @location.search + '#' + @fragment # Return immediately as browser will do redirect to new url return true # Or if we've started out with a hash-based route, but we're currently # in a browser where it could be `pushState`-based instead... else if @_wantsPushState and @_hasPushState and atRoot and loc.hash @fragment = @getHash().replace routeStripper, '' @history.replaceState {}, document.title, @root + @fragment + loc.search @loadUrl() unless @options.silent # Disable Backbone.history, perhaps temporarily. Not useful in a real app, # but possibly useful for unit testing Routers. stop: -> Backbone.$(window).off('popstate', @checkUrl).off 'hashchange', @checkUrl clearInterval @_checkUrlInterval History.started = false # Add a route to be tested when the fragment changes. Routes added later # may override previous routes. route: (route, callback) -> @handlers.unshift(route: route, callback: callback) # Checks the current URL to see if it has changed, and if it has, # calls `loadUrl`, normalizing across the hidden iframe. checkUrl: (e) -> current = @getFragment() if current is @fragment and @iframe current = @getFragment @getHash(@iframe) return false if current is @fragment @navigate(current) if @iframe @loadUrl() or @loadUrl @getHash() # Attempt to load the current URL fragment. If a route succeeds with a # match, returns `true`. If no defined routes matches the fragment, # returns `false`. loadUrl: (fragmentOverride) -> @fragment = @getFragment fragmentOverride fragment = @fragment matched = _.any @handlers, (handler) -> if handler.route.test fragment handler.callback fragment true matched # Save a fragment into the hash history, or replace the URL state if the # 'replace' option is passed. You are responsible for properly URL-encoding # the fragment in advance. # # The options object can contain `trigger: true` if you wish to have the # route callback be fired (not usually desirable), or `replace: true`, if # you wish to modify the current URL without adding an entry to the history. navigate: (fragment, options) -> return false unless History.started options = trigger: options if not options or options is true fragment = @getFragment fragment or '' return if @fragment is fragment @fragment = fragment url = @root + fragment # If pushState is available, we use it to set the fragment as a real URL. if @_hasPushState method = if options.replace then 'replaceState' else 'pushState' @history[method] {}, document.title, url # If hash changes haven't been explicitly disabled, update the hash # fragment to store history. else if @_wantsHashChange @_updateHash @location, fragment, options.replace if @iframe and (fragment != @getFragment(@getHash @iframe)) # Opening and closing the iframe tricks IE7 and earlier to push a # history entry on hash-tag change. When replace is true, we don't # want this. @iframe.document.open().close() unless options.replace @_updateHash @iframe.location, fragment, options.replace # If you've told us that you explicitly don't want fallback hashchange- # based history, then `navigate` becomes a page refresh. else return @location.assign url @loadUrl fragment if options.trigger # Update the hash location, either replacing the current entry, or adding # a new one to the browser history. _updateHash: (location, fragment, replace) -> if replace href = location.href.replace /(javascript:|#).*$/, '' location.replace href + '#' + fragment else # Some browsers require that `hash` contains a leading #. location.hash = '#' + fragment History = Backbone.History # Create the default Backbone.history. Backbone.history = new History ### Helpers ------- Helper function to correctly set up the prototype chain, for subclasses. Similar to `goog.inherits`, but uses a hash of prototype properties and class properties to be extended. ### extend = (protoProps, staticProps) -> parent = @ # The constructor function for the new subclass is either defined by you # (the "constructor" property in your `extend` definition), or defaulted # by us to simply call the parent's constructor. if protoProps and _.has protoProps, 'constructor' child = protoProps.constructor else child = -> parent.apply @, arguments # Add static properties to the constructor function, if supplied. _.extend child, parent, staticProps # Set the prototype chain to inherit from `parent`, without calling # `parent`'s constructor function. class Surrogate constructor: -> @constructor = child Surrogate.prototype = parent.prototype child.prototype = new Surrogate # Add prototype properties (instance properties) to the subclass, # if supplied. _.extend(child.prototype, protoProps) if protoProps # Set a convenience property in case the parent's prototype is needed # later. child.__super__ = parent.prototype child # Set up inheritance for the model, collection, router, view and history. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend # Throw an error when a URL is needed, and none is supplied. urlError = -> throw new Error 'A "url" property or function must be specified' # Wrap an optional error callback with a fallback error event. wrapError = (model, options) -> error = options.error options.error = (resp) -> error(model, resp, options) if error model.trigger 'error', model, resp, options
true
### Backbone.js 1.0.0 (c) 2010-2011 PI:NAME:<NAME>END_PI, DocumentCloud Inc. (c) 2011-2013 PI:NAME:<NAME>END_PI, DocumentCloud and Investigative Reporters & Editors Backbone may be freely distributed under the MIT license. For all details and documentation: http://www.backbonecoffee.org ### # Initial Setup # ------------- # Save a reference to the global object (`window` in the browser, `exports` # on the server). root = @ # Save the previous value of the `Backbone` variable, so that it can be # restored later on, if `noConflict` is used. previousBackbone = root.Backbone # Create local references to array methods we'll want to use later. array = [] push = array.push slice = array.slice splice = array.splice # The top-level namespace. All public Backbone classes and modules will # be attached to this. Exported for both the browser and the server. if exports? Backbone = exports else root.Backbone = {} Backbone = root.Backbone # Require Underscore, if we're on the server, and it's not already present. _ = root._ _ = require 'underscore' if not _? and require? # Map from CRUD to HTTP for our default `Backbone.sync` implementation. methodMap = create: 'POST' update: 'PUT' patch: 'PATCH' delete: 'DELETE' read: 'GET' _.extend Backbone, # Current version of the library. Keep in sync with `package.json`. VERSION: '1.0.0' # For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns # the `$` variable. $: root.jQuery or root.Zepto or root.ender or root.$ # Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable # to its previous owner. Returns a reference to this Backbone object. noConflict: -> root.Backbone = previousBackbone @ # Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option # will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and # set a `X-Http-Method-Override` header. emulateHTTP: false # Turn on `emulateJSON` to support legacy servers that can't deal with direct # `application/json` requests ... will encode the body as # `application/x-www-form-urlencoded` instead and will send the model in a # form param named `model`. emulateJSON: false # Set the default implementation of `Backbone.ajax` to proxy through to `$`. # Override this if you'd like to use a different library. ajax: -> Backbone.$.ajax arguments... # Backbone.sync # ------------- # # Override this function to change the manner in which Backbone persists # models to the server. You will be passed the type of request, and the # model in question. By default, makes a RESTful Ajax request # to the model's `url()`. Some possible customizations could be: # # * Use `setTimeout` to batch rapid-fire updates into a single request. # * Send up the models as XML instead of JSON. # * Persist models via WebSockets instead of Ajax. # # Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests # as `POST`, with a `_method` parameter containing the true HTTP method, # as well as all requests with the body as `application/x-www-form-urlencoded` # instead of `application/json` with the model in a param named `model`. # Useful when interfacing with server-side languages like **PHP** that make # it difficult to read the body of `PUT` requests. sync: (method, model, options = {}) -> type = methodMap[method] # Default options, unless specified. _.defaults options, emulateHTTP: Backbone.emulateHTTP emulateJSON: Backbone.emulateJSON # Default JSON-request options. params = type: type dataType: 'json' # Ensure that we have a URL. params.url = _.result(model, 'url') or urlError() unless options.url # Ensure that we have the appropriate request data. if not options.data? and model and (method is 'create' or method is 'update' or method is 'patch') params.contentType = 'application/json' params.data = JSON.stringify(options.attrs or model.toJSON options) # For older servers, emulate JSON by encoding the request into an HTML-form. if options.emulateJSON params.contentType = 'application/x-www-form-urlencoded' params.data = if params.data then model: params.data else {} # For older servers, emulate HTTP by mimicking the HTTP method with # `_method` and an `X-HTTP-Method-Override` header. if options.emulateHTTP and (type is 'PUT' or type is 'DELETE' or type is 'PATCH') params.type = 'POST' params.data._method = type if options.emulateJSON beforeSend = options.beforeSend options.beforeSend = (xhr) -> xhr.setRequestHeader 'X-HTTP-Method-Override', type beforeSend.apply @, arguments if beforeSend # Don't process data on a non-GET request. if params.type != 'GET' and not options.emulateJSON params.processData = false # If we're sending a `PATCH` request, and we're in an old Internet Explorer # that still has ActiveX enabled by default, override jQuery to use that # for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. if params.type is 'PATCH' and window.ActiveXObject and not (window.external and window.external.msActiveXFilteringEnabled) params.xhr = -> new ActiveXObject 'Microsoft.XMLHTTP' # Make the request, allowing the user to override any Ajax options. options.xhr = Backbone.ajax _.extend(params, options) xhr = options.xhr model.trigger 'request', model, xhr, options xhr ### Backbone.Events --------------- A module that can be mixed in to *any object* in order to provide it with custom events. You may bind with `on` or remove with `off` callback functions to an event; `trigger`-ing an event fires all callbacks in succession. var object = {}; _.extend(object, Backbone.Events); object.on('expand', function(){ alert('expanded'); }); object.trigger('expand'); ### class Backbone.Events # Bind an event to a `callback` function. Passing `"all"` will bind # the callback to all events fired. @on: (name, callback, context) -> return @ unless eventsApi(@, 'on', name, [callback, context]) and callback @_events ?= {} @_events[name] ?= [] events = @_events[name] events.push callback: callback context: context ctx: context or @ @ # Bind an event to only be triggered a single time. After the first time # the callback is invoked, it will be removed. @once: (name, callback, context) -> if not eventsApi(@, 'once', name, [callback, context]) or not callback return @ self = @ once = _.once -> self.off name, once callback.apply @, arguments once._callback = callback @on name, once, context # Remove one or many callbacks. If `context` is null, removes all # callbacks with that function. If `callback` is null, removes all # callbacks for the event. If `name` is null, removes all bound # callbacks for all events. @off: (name, callback, context) -> if not @_events or not eventsApi @, 'off', name, [callback, context] return @ if not name and not callback and not context @_events = {} return @ names = if name then [name] else _.keys @_events for name in names events = @_events[name] if events retain = [] @_events[name] = retain if callback or context for ev in events if (callback and callback != ev.callback and callback != ev.callback._callback) or (context and context != ev.context) retain.push ev delete @_events[name] unless retain.length @ # Trigger one or many events, firing all bound callbacks. Callbacks are # passed the same arguments as `trigger` is, apart from the event name # (unless you're listening on `"all"`, which will cause your callback to # receive the true name of the event as the first argument). @trigger: (name) -> return @ unless @_events args = slice.call arguments, 1 return @ unless eventsApi @, 'trigger', name, args events = @_events[name] allEvents = @_events.all triggerEvents events, args if events triggerEvents allEvents, arguments if allEvents @ # Tell this object to stop listening to either specific events ... or # to every object it's currently listening to. @stopListening: (obj, name, callback) -> listeners = @_listeners return @ unless listeners deleteListener = not name and not callback callback = @ if _.isObject name if obj listeners = {} listeners[obj._listenerId] = obj for id, v of listeners listeners[id].off name, callback, @ delete @_listeners[id] if deleteListener @ Events = Backbone.Events # Regular expression used to split event strings. eventSplitter = /\s+/ # Implement fancy features of the Events API such as multiple event # names `"change blur"` and jQuery-style event maps `{change: action}` # in terms of the existing API. eventsApi = (obj, action, name, rest) -> return true unless name # Handle event maps. if _.isObject name for key, v of name obj[action] ([key, name[key]].concat rest)... return false # Handle space separated event names. if eventSplitter.test name names = name.split eventSplitter for i in [0...names.length] obj[action] ([names[i]].concat rest)... return false true # A difficult-to-believe, but optimized internal dispatch function for # triggering events. Tries to keep the usual cases speedy (most internal # Backbone events have 3 arguments). triggerEvents = (events, args) -> i = -1 l = events.length [a1, a2, a3] = args switch args.length when 0 while ++i < l ev = events[i] ev.callback.call ev.ctx when 1 while ++i < l ev = events[i] ev.callback.call ev.ctx, a1 when 2 while ++i < l ev = events[i] ev.callback.call ev.ctx, a1, a2 when 3 while ++i < l ev = events[i] ev.callback.call ev.ctx, a1, a2, a3 else while ++i < l ev = events[i] ev.callback.apply ev.ctx, args listenMethods = listenTo: 'on' listenToOnce: 'once' # Inversion-of-control versions of `on` and `once`. Tell *this* object to # listen to an event in another object ... keeping track of what it's # listening to. _.each listenMethods, (implementation, method) -> Events[method] = (obj, name, callback) -> @_listeners ?= {} listeners = @_listeners obj._listenerId ?= _.uniqueId 'l' id = obj._listenerId listeners[id] = obj callback = @ if _.isObject name obj[implementation] name, callback, @ @ # Aliases for backwards compatibility. Events.bind = Events.on Events.unbind = Events.off # Allow the `Backbone` object to serve as a global event bus, for folks who # want global "pubsub" in a convenient place. _.extend Backbone, Events ### Backbone.Model -------------- Backbone **Models** are the basic data object in the framework -- frequently representing a row in a table in a database on your server. A discrete chunk of data and a bunch of useful, related methods for performing computations and transformations on that data. Create a new model with the specified attributes. A client id (`cid`) is automatically generated and assigned for you. ### class Backbone.Model _.extend @::, Events # A hash of attributes whose current and previous value differ. changed: null # The value returned during the last failed validation. validationError: null # The default name for the JSON `id` attribute is `"id"`. MongoDB and # CouchDB users may want to set this to `"_id"`. idAttribute: 'id' constructor: (attributes, options = {}) -> attrs = attributes or {} @cid = _.uniqueId 'c' @attributes = {} @collection = options.collection if options.collection attrs = @parse(attrs, options) or {} if options.parse options._attrs = attrs defaults = _.result @, 'defaults' attrs = _.defaults {}, attrs, defaults if defaults @set attrs, options @changed = {} @initialize arguments... # Initialize is an empty function by default. Override it with your own # initialization logic. initialize: -> # pass # Return a copy of the model's `attributes` object. toJSON: (options) -> _.clone @attributes # Proxy `Backbone.sync` by default -- but override this if you need # custom syncing semantics for *this* particular model. sync: -> Backbone.sync.apply @, arguments # Get the value of an attribute. get: (attr) -> @attributes[attr] # Get the HTML-escaped value of an attribute. escape: (attr) -> _.escape @get(attr) # Returns `true` if the attribute contains a value that != null # or undefined. has: (attr) -> @get(attr)? # Set a hash of model attributes on the object, firing `"change"`. This is # the core primitive operation of a model, updating the data and notifying # anyone who needs to know about the change in state. The heart of the beast. set: (key, val, options = {}) -> return this unless key? # Handle both `"key", value` and `{key: value}` -style arguments. if _.isObject key attrs = key options = val or {} else attrs = {} attrs[key] = val # Run validation. return false unless @_validate attrs, options # Extract attributes and options. unset = options.unset silent = options.silent changes = [] changing = @_changing @_changing = true unless changing @_previousAttributes = _.clone @attributes @changed = {} current = @attributes prev = @_previousAttributes # Check for changes of `id`. @id = attrs[@idAttribute] if _.has attrs, @idAttribute # For each `set` attribute, update or delete the current value. for attr, v of attrs val = attrs[attr] changes.push(attr) unless _.isEqual current[attr], val unless _.isEqual prev[attr], val @changed[attr] = val else delete @changed[attr] if unset delete current[attr] else current[attr] = val # Trigger all relevant attribute changes. unless silent @_pending = true if changes.length for change in changes @trigger 'change:' + change, @, current[change], options # You might be wondering why there's a `while` loop here. Changes can # be recursively nested within `"change"` events. return @ if changing unless silent while @_pending @_pending = false @trigger 'change', @, options @_pending = false @_changing = false @ # Remove an attribute from the model, firing `"change"`. `unset` is a noop # if the attribute doesn't exist. unset: (attr, options) -> @set attr, undefined, _.extend({}, options, unset: true) # Clear all attributes on the model, firing `"change"`. clear: (options) -> attrs = {} for key, v of @attributes attrs[key] = undefined @set attrs, _.extend({}, options, unset: true) # Determine if the model has changed since the last `"change"` event. # If you specify an attribute name, determine if that attribute has changed. hasChanged: (attr) -> return not _.isEmpty @changed unless attr? return _.has @changed, attr # Return an object containing all the attributes that have changed, or # false if there are no changed attributes. Useful for determining what # parts of a view need to be updated and/or what attributes need to be # persisted to the server. Unset attributes will be set to undefined. # You can also pass an attributes object to diff against the model, # determining if there *would be* a change. changedAttributes: (diff) -> unless diff return if @hasChanged() then _.clone(@changed) else false changed = false old = if @_changing then @_previousAttributes else @attributes for attr, v of diff continue if _.isEqual old[attr], v changed = {} unless changed changed[attr] = v return changed # Get the previous value of an attribute, recorded at the time the last # `"change"` event was fired. previous: (attr) -> return null if not attr? or not @_previousAttributes return @_previousAttributes[attr] # Get all of the attributes of the model at the time of the previous # `"change"` event. previousAttributes: -> _.clone @_previousAttributes # Fetch the model from the server. If the server's representation of the # model differs from its current attributes, they will be overridden, # triggering a `"change"` event. fetch: (options = {}) -> options = _.clone options options.parse = true unless options.parse? model = @ success = options.success options.success = (resp) -> return false unless model.set model.parse(resp, options), options success(model, resp, options) if success model.trigger 'sync', model, resp, options wrapError this, options @sync 'read', this, options # Set a hash of model attributes, and sync the model to the server. # If the server returns an attributes hash that differs, the model's # state will be `set` again. save: (key, val, options) -> attributes = @attributes # Handle both `"key", value` and `{key: value}` -style arguments. if not key? or _.isObject key attrs = key options = val else attrs = {} attrs[key] = val options = _.extend {validate: true}, options # If we're not waiting and attributes exist, save acts as # `set(attr).save(null, opts)` with validation. Otherwise, check if # the model will be valid when the attributes, if any, are set. if attrs and not options.wait return false unless @set attrs, options else return false unless @_validate attrs, options # Set temporary attributes if `{wait: true}`. if attrs and options.wait @attributes = _.extend {}, attributes, attrs # After a successful server-side save, the client is (optionally) # updated with the server-side state. options.parse = true unless options.parse? model = @ success = options.success options.success = (resp) -> # Ensure attributes are restored during synchronous saves. model.attributes = attributes serverAttrs = model.parse resp, options serverAttrs = _.extend(attrs or {}, serverAttrs) if options.wait if _.isObject(serverAttrs) and not model.set serverAttrs, options return false success model, resp, options if success model.trigger 'sync', model, resp, options wrapError @, options if @isNew() method = 'create' else method = (if options.patch then 'patch' else 'update') options.attrs = attrs if method is 'patch' xhr = @sync method, @, options # Restore attributes. @attributes = attributes if attrs and options.wait xhr # Destroy this model on the server if it was already persisted. # Optimistically removes the model from its collection, if it has one. # If `wait: true` is passed, waits for the server to respond before removal. destroy: (options = {}) -> options = _.clone options model = @ success = options.success destroy = -> model.trigger 'destroy', model, model.collection, options options.success = (resp) -> destroy() if options.wait or model.isNew() success(model, resp, options) if success model.trigger('sync', model, resp, options) unless model.isNew() if @isNew() options.success() return false wrapError @, options xhr = @sync 'delete', @, options destroy() unless options.wait xhr # Default URL for the model's representation on the server -- if you're # using Backbone's restful methods, override this to change the endpoint # that will be called. url: -> base = _.result(@, 'urlRoot') or _.result(@collection, 'url') or urlError() return base if @isNew() base + (if base.charAt(base.length - 1) is '/' then '' else '/') + encodeURIComponent @id # **parse** converts a response into the hash of attributes to be `set` on # the model. The default implementation is just to pass the response along. parse: (resp, options) -> resp # Create a new model with identical attributes to this one. clone: -> new @constructor @attributes # A model is new if it has never been saved to the server, and lacks an id. isNew: -> not @id? # Check if the model is currently in a valid state. isValid: (options) -> @_validate {}, _.extend(options or {}, validate: true) # Run validation against the next complete set of model attributes, # returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate: (attrs, options = {}) -> return true if not options.validate or not @validate attrs = _.extend {}, @attributes, attrs @validationError = @validate(attrs, options) or null error = @validationError return true unless error @trigger 'invalid', @, error, _.extend(options or {}, validationError: error) false Model = Backbone.Model # Underscore methods that we want to implement on the Model. modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'] # Mix in each Underscore method as a proxy to `Model#attributes`. _.each modelMethods, (method) -> Model.prototype[method] = -> args = slice.call arguments args.unshift @attributes _[method] args... ### Backbone.Collection ------------------- If models tend to represent a single row of data, a Backbone Collection is more analagous to a table full of data ... or a small slice or page of that table, or a collection of rows that belong together for a particular reason -- all of the messages in this particular folder, all of the documents belonging to this particular author, and so on. Collections maintain indexes of their models, both in order, and for lookup by `id`. Create a new **Collection**, perhaps to contain a specific type of `model`. If a `comparator` is specified, the Collection will maintain its models in sort order, as they're added and removed. ### # Default options for `Collection#set`. setOptions = add: true remove: true merge: true addOptions = add: true merge: false remove: false class Backbone.Collection _.extend @::, Events # The default model for a collection is just a **Backbone.Model**. # This should be overridden in most cases. model: Model constructor: (models, options) -> options or= {} @model = options.model if options.model @comparator = options.comparator unless _.isUndefined options.comparator @_reset() @initialize arguments... @reset models, _.extend({silent: true}, options) if models # Initialize is an empty function by default. Override it with your own # initialization logic. initialize: -> # pass # The JSON representation of a Collection is an array of the # models' attributes. toJSON: (options) -> @map (model) -> model.toJSON options # Proxy `Backbone.sync` by default. sync: -> Backbone.sync.apply @, arguments # Add a model, or list of models to the set. add: (models, options = {}) -> @set models, _.defaults(options, addOptions) # Remove a model, or a list of models from the set. remove: (models, options = {}) -> models = if _.isArray(models) then models.slice() else [models] for i in [0...models.length] model = @get models[i] continue unless model delete @_byId[model.id] delete @_byId[model.cid] index = @indexOf model @models.splice index, 1 @length-- unless options.silent options.index = index model.trigger 'remove', model, @, options @_removeReference model @ # Update a collection by `set`-ing a new list of models, adding new ones, # removing models that are no longer present, and merging models that # already exist in the collection, as necessary. Similar to **Model#set**, # the core operation for updating the data contained by the collection. set: (models, options = {}) -> options = _.defaults options, setOptions models = @parse(models, options) if options.parse unless _.isArray models models = if models then [models] else [] at = options.at sortable = @comparator and not at? and options.sort != false sortAttr = if _.isString @comparator then @comparator else null toAdd = [] toRemove = [] modelMap = {} add = options.add merge = options.merge remove = options.remove order = if not sortable and add and remove then [] else false # Turn bare objects into model references, and prevent invalid models # from being added. for i in [0...models.length] attrs = models[i] model = @_prepareModel attrs, options continue unless model # If a duplicate is found, prevent it from being added and # optionally merge it into the existing model. existing = @get model if existing modelMap[existing.cid] = true if remove if merge attrs = if attrs is model then model.attributes else options._attrs existing.set attrs, options sort = true if sortable and not sort and existing.hasChanged sortAttr # This is a new model, push it to the `toAdd` list. else if add toAdd.push model # Listen to added models' events, and index models for lookup by # `id` and by `cid`. model.on 'all', @_onModelEvent, @ @_byId[model.cid] = model @_byId[model.id] = model if model.id? order.push(existing or model) if order # Remove nonexistent models if appropriate. if remove for i in [0...@length] model = @models[i] toRemove.push model unless modelMap[model.cid] @remove(toRemove, options) if toRemove.length # See if sorting is needed, update `length` and splice in new models. if toAdd.length or (order and order.length) sort = true if sortable @length += toAdd.length if at? splice.apply @models, [at, 0].concat(toAdd) else @models.length = 0 if order push.apply @models, (order or toAdd) # Silently sort the collection if appropriate. @sort silent: true if sort return @ if options.silent # Trigger `add` events. for model in toAdd model.trigger 'add', model, @, options # Trigger `sort` if the collection was sorted. @trigger 'sort', @, options if sort or (order and order.length) @ # When you have more items than you want to add or remove individually, # you can reset the entire set with a new list of models, without firing # any granular `add` or `remove` events. Fires `reset` when finished. # Useful for bulk operations and optimizations. reset: (models, options = {}) -> @_removeReference model for model in @models options.previousModels = @models @_reset() @add models, _.extend({silent: true}, options) @trigger 'reset', @, options unless options.silent @ # Add a model to the end of the collection. push: (model, options) -> model = @_prepareModel model, options @add model, _.extend({at: @length}, options) model # Remove a model from the end of the collection. pop: (options) -> model = @at(@length - 1) @remove model, options model # Add a model to the beginning of the collection. unshift: (model, options) -> model = @_prepareModel model, options @add model, _.extend({at: 0}, options) model # Remove a model from the beginning of the collection. shift: (options) -> model = @at 0 @remove model, options model # Slice out a sub-array of models from the collection. slice: -> slice.apply @models, arguments # Get a model from the set by id. get: (obj) -> return undefined unless obj? @_byId[obj.id ? (obj.cid or obj)] # Get the model at the given index. at: (index) -> @models[index] # Return models with matching attributes. Useful for simple cases of # `filter`. where: (attrs, first) -> if _.isEmpty attrs return if first then undefined else [] @[if first then 'find' else 'filter'] (model) -> for key, v of attrs return false if v != model.get(key) true # Return the first model with matching attributes. Useful for simple cases # of `find`. findWhere: (attrs) -> @where attrs, true # Force the collection to re-sort itself. You don't need to call this under # normal circumstances, as the set will maintain sort order as each item # is added. sort: (options = {}) -> throw new Error('Cannot sort a set without a comparator') unless @comparator # Run sort based on type of `comparator`. if _.isString(@comparator) or @comparator.length is 1 @models = @sortBy @comparator, @ else @models.sort _.bind(@comparator, @) @trigger 'sort', @, options unless options.silent @ # Figure out the smallest index at which a model should be inserted so as # to maintain order. sortedIndex: (model, value, context) -> value = value or @comparator iterator = if _.isFunction value then value else (model) -> model.get(value) _.sortedIndex @models, model, iterator, context # Pluck an attribute from each model in the collection. pluck: (attr) -> _.invoke @models, 'get', attr # Fetch the default set of models for this collection, resetting the # collection when they arrive. If `reset: true` is passed, the response # data will be passed through the `reset` method instead of `set`. fetch: (options = {}) -> options = _.clone options options.parse = true unless options.parse? success = options.success collection = @ options.success = (resp) -> method = if options.reset then 'reset' else 'set' collection[method] resp, options success collection, resp, options if success collection.trigger 'sync', collection, resp, options wrapError @, options @sync 'read', @, options # Create a new instance of a model in this collection. Add the model to the # collection immediately, unless `wait: true` is passed, in which case we # wait for the server to agree. create: (model, options = {}) -> options = _.clone options model = @_prepareModel model, options return false unless model @add(model, options) unless options.wait collection = @ success = options.success options.success = (resp) -> collection.add model, options if options.wait success model, resp, options if success model.save null, options model # **parse** converts a response into a list of models to be added to the # collection. The default implementation is just to pass it through. parse: (resp, options) -> resp # Create a new collection with an identical list of models as this one. clone: -> new @constructor @models # Private method to reset all internal state. Called when the collection # is first initialized or reset. _reset: -> @length = 0 @models = [] @_byId = {} # Prepare a hash of attributes (or other model) to be added to this # collection. _prepareModel: (attrs, options = {}) -> if attrs instanceof Model attrs.collection = @ unless attrs.collection return attrs options.collection = @ model = new @model attrs, options unless model._validate attrs, options @trigger 'invalid', @, attrs, options return false model # Internal method to sever a model's ties to a collection. _removeReference: (model) -> delete model.collection if @ is model.collection model.off 'all', @_onModelEvent, @ # Internal method called every time a model in the set fires an event. # Sets need to update their indexes when models change ids. All other # events simply proxy through. "add" and "remove" events that originate # in other collections are ignored. _onModelEvent: (event, model, collection, options) -> return if (event is 'add' or event is 'remove') and collection != @ @remove model, options if event is 'destroy' if model and event is "change:#{model.idAttribute}" delete @_byId[model.previous model.idAttribute] @_byId[model.id] = model if model.id? @trigger.apply @, arguments Collection = Backbone.Collection # Underscore methods that we want to implement on the Collection. # 90% of the core usefulness of Backbone Collections is actually implemented # right here: methods = [ 'forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf', 'isEmpty', 'chain' ] # Mix in each Underscore method as a proxy to `Collection#models`. _.each methods, (method) -> Collection::[method] = -> args = slice.call arguments args.unshift @models _[method].apply _, args # Underscore methods that take a property name as an argument. attributeMethods = ['groupBy', 'countBy', 'sortBy'] # Use attributes instead of properties. _.each attributeMethods, (method) -> Collection::[method] = (value, context) -> iterator = if _.isFunction(value) then value else (model) -> model.get value _[method] @models, iterator, context ### Backbone.View ------------- Backbone Views are almost more convention than they are actual code. A View is simply a JavaScript object that represents a logical chunk of UI in the DOM. This might be a single item, an entire list, a sidebar or panel, or even the surrounding frame which wraps your whole app. Defining a chunk of UI as a **View** allows you to define your DOM events declaratively, without having to worry about render order ... and makes it easy for the view to react to specific changes in the state of your models. Options with special meaning *(e.g. model, collection, id, className)* are attached directly to the view. See `viewOptions` for an exhaustive list. Creating a Backbone.View creates its initial element outside of the DOM, if an existing element != provided... ### # Cached regex to split keys for `delegate`. delegateEventSplitter = /^(\S+)\s*(.*)$/ # List of view options to be merged as properties. viewOptions = [ 'model' 'collection' 'el' 'id' 'attributes' 'className' 'tagName' 'events' ] class Backbone.View _.extend @::, Events # The default `tagName` of a View's element is `"div"`. tagName: 'div' constructor: (options = {}) -> @cid = _.uniqueId 'view' _.extend @, _.pick(options, viewOptions) @_ensureElement() @initialize.apply @, arguments @delegateEvents() # jQuery delegate for element lookup, scoped to DOM elements within the # current view. This should be prefered to global lookups where possible. $: (selector) -> @$el.find selector # Initialize is an empty function by default. Override it with your own # initialization logic. initialize: -> # pass # **render** is the core function that your view should override, in order # to populate its element (`this.el`), with the appropriate HTML. The # convention is for **render** to always return `this`. render: -> @ # Remove this view by taking the element out of the DOM, and removing any # applicable Backbone.Events listeners. remove: -> @$el.remove() @stopListening() @ # Change the view's element (`this.el` property), including event # re-delegation. setElement: (element, delegate) -> @undelegateEvents() if @$el @$el = if element instanceof Backbone.$ then element else Backbone.$ element @el = @$el[0] @delegateEvents() if delegate != false @ # Set callbacks, where `this.events` is a hash of # # *{"event selector": "callback"}* # # { # 'mousedown .title': 'edit', # 'click .button': 'save' # 'click .open': function(e) { ... } # } # # pairs. Callbacks will be bound to the view, with `this` set properly. # Uses event delegation for efficiency. # Omitting the selector binds the event to `this.el`. # This only works for delegate-able events: not `focus`, `blur`, and # not `change`, `submit`, and `reset` in Internet Explorer. delegateEvents: (events) -> events = events or _.result @, 'events' return @ unless events @undelegateEvents() for key, method of events method = @[events[key]] unless _.isFunction method continue unless method match = key.match delegateEventSplitter eventName = match[1] selector = match[2] method = _.bind method, @ eventName += ".delegateEvents#{@cid}" if selector is '' @$el.on eventName, method else @$el.on eventName, selector, method @ # Clears all callbacks previously bound to the view with `delegateEvents`. # You usually don't need to use this, but may wish to if you have multiple # Backbone views attached to the same DOM element. undelegateEvents: -> @$el.off '.delegateEvents' + @cid @ # Ensure that the View has a DOM element to render into. # If `this.el` is a string, pass it through `$()`, take the first # matching element, and re-assign it to `el`. Otherwise, create # an element from the `id`, `className` and `tagName` properties. _ensureElement: -> if not @el attrs = _.extend {}, _.result(@, 'attributes') attrs.id = _.result(@, 'id') if @id attrs['class'] = _.result(@, 'className') if @className $el = Backbone.$("<#{_.result @, 'tagName'}>").attr attrs @setElement $el, false else @setElement _.result(@, 'el'), false View = Backbone.View ### Backbone.Router --------------- Routers map faux-URLs to actions, and fire events when routes are matched. Creating a new one sets its `routes` hash, if not set statically. ### # Cached regular expressions for matching named param parts and splatted # parts of route strings. optionalParam = /\((.*?)\)/g namedParam = /(\(\?)?:\w+/g splatParam = /\*\w+/g escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g class Backbone.Router _.extend @::, Events constructor: (options = {}) -> @routes = options.routes if options.routes @_bindRoutes() @initialize arguments... # Initialize is an empty function by default. Override it with your own # initialization logic. initialize: -> # pass # Manually bind a single named route to a callback. For example: # # this.route('search/:query/p:num', 'search', function(query, num) { # ... # }); # route: (route, name, callback) -> route = @_routeToRegExp(route) unless _.isRegExp route if _.isFunction name callback = name name = '' callback = @[name] unless callback router = @ Backbone.history.route route, (fragment) -> args = router._extractParameters route, fragment callback?.apply router, args router.trigger.apply router, ['route:' + name].concat(args) router.trigger 'route', name, args Backbone.history.trigger 'route', router, name, args @ # Simple proxy to `Backbone.history` to save a fragment into the history. navigate: (fragment, options) -> Backbone.history.navigate fragment, options @ # Bind all defined routes to `Backbone.history`. We have to reverse the # order of the routes here to support behavior where the most general # routes can be defined at the bottom of the route map. _bindRoutes: -> return unless @routes @routes = _.result @, 'routes' routes = _.keys @routes route = routes.pop() while route? @route route, @routes[route] route = routes.pop() # Convert a route string into a regular expression, suitable for matching # against the current location hash. _routeToRegExp: (route) -> route = route .replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, (match, optional) -> if optional then match else '([^\/]+)') .replace(splatParam, '(.*?)') new RegExp "^#{route}$" # Given a route, and a URL fragment that it matches, return the array of # extracted decoded parameters. Empty or unmatched parameters will be # treated as `null` to normalize cross-browser behavior. _extractParameters: (route, fragment) -> params = route.exec(fragment).slice(1) _.map params, (param) -> if param then decodeURIComponent(param) else null Router = Backbone.Router ### Backbone.History ---------------- Handles cross-browser history management, based on either [pushState](http:#diveintohtml5.info/history.html) and real URLs, or [onhashchange](https:#developer.mozilla.org/en-US/docs/DOM/window.onhashchange) and URL fragments. If the browser supports neither (old IE, natch), falls back to polling. ### # Cached regex for stripping a leading hash/slash and trailing space. routeStripper = /^[#\/]|\s+$/g # Cached regex for stripping leading and trailing slashes. rootStripper = /^\/+|\/+$/g # Cached regex for detecting MSIE. isExplorer = /msie [\w.]+/ # Cached regex for removing a trailing slash. trailingSlash = /\/$/ class Backbone.History _.extend @::, Events # Has the history handling already been started? @started: false # The default interval to poll for hash changes, if necessary, is # twenty times a second. interval: 50 constructor: -> @handlers = [] _.bindAll @, 'checkUrl' # Ensure that `History` can be used outside of the browser. if typeof window != 'undefined' @location = window.location @history = window.history # Gets the true hash value. Cannot use location.hash directly due to bug # in Firefox where location.hash will always be decoded. getHash: (window) -> match = (window or @).location.href.match /#(.*)$/ if match then match[1] else '' # Get the cross-browser normalized URL fragment, either from the URL, # the hash, or the override. getFragment: (fragment, forcePushState) -> unless fragment? if @_hasPushState or not @_wantsHashChange or forcePushState fragment = @location.pathname root = @root.replace trailingSlash, '' fragment = fragment.substr root.length unless fragment.indexOf root else fragment = @getHash() fragment.replace routeStripper, '' # Start the hash change handling, returning `true` if the current URL matches # an existing route, and `false` otherwise. start: (options) -> if History.started throw new Error 'Backbone.history has already been started' History.started = true # Figure out the initial configuration. Do we need an iframe? # Is pushState desired ... is it available? @options = _.extend {}, {root: '/'}, @options, options @root = @options.root @_wantsHashChange = @options.hashChange != false @_wantsPushState = !!@options.pushState @_hasPushState = !!(@options.pushState and @history and @history.pushState) fragment = @getFragment() docMode = document.documentMode oldIE = isExplorer.exec(navigator.userAgent.toLowerCase()) and (not docMode or docMode <= 7) # Normalize root to always include a leading and trailing slash. @root = "/#{@root}/".replace rootStripper, '/' if oldIE and @_wantsHashChange @iframe = Backbone .$('<iframe src="javascript:0" tabindex="-1" />') .hide() .appendTo('body')[0] .contentWindow @navigate fragment # Depending on whether we're using pushState or hashes, and whether # 'onhashchange' is supported, determine how we check the URL state. if @_hasPushState Backbone.$(window).on 'popstate', @checkUrl else if @_wantsHashChange and ('onhashchange' in window) and not oldIE Backbone.$(window).on 'hashchange', @checkUrl else if @_wantsHashChange @_checkUrlInterval = setInterval @checkUrl, @interval # Determine if we need to change the base url, for a pushState link # opened by a non-pushState browser. @fragment = fragment loc = @location atRoot = loc.pathname.replace(/[^\/]$/, '$&/') is @root # If we've started off with a route from a `pushState`-enabled browser, # but we're currently in a browser that doesn't support it... if @_wantsHashChange and @_wantsPushState and not @_hasPushState and not atRoot @fragment = @getFragment null, true @location.replace @root + @location.search + '#' + @fragment # Return immediately as browser will do redirect to new url return true # Or if we've started out with a hash-based route, but we're currently # in a browser where it could be `pushState`-based instead... else if @_wantsPushState and @_hasPushState and atRoot and loc.hash @fragment = @getHash().replace routeStripper, '' @history.replaceState {}, document.title, @root + @fragment + loc.search @loadUrl() unless @options.silent # Disable Backbone.history, perhaps temporarily. Not useful in a real app, # but possibly useful for unit testing Routers. stop: -> Backbone.$(window).off('popstate', @checkUrl).off 'hashchange', @checkUrl clearInterval @_checkUrlInterval History.started = false # Add a route to be tested when the fragment changes. Routes added later # may override previous routes. route: (route, callback) -> @handlers.unshift(route: route, callback: callback) # Checks the current URL to see if it has changed, and if it has, # calls `loadUrl`, normalizing across the hidden iframe. checkUrl: (e) -> current = @getFragment() if current is @fragment and @iframe current = @getFragment @getHash(@iframe) return false if current is @fragment @navigate(current) if @iframe @loadUrl() or @loadUrl @getHash() # Attempt to load the current URL fragment. If a route succeeds with a # match, returns `true`. If no defined routes matches the fragment, # returns `false`. loadUrl: (fragmentOverride) -> @fragment = @getFragment fragmentOverride fragment = @fragment matched = _.any @handlers, (handler) -> if handler.route.test fragment handler.callback fragment true matched # Save a fragment into the hash history, or replace the URL state if the # 'replace' option is passed. You are responsible for properly URL-encoding # the fragment in advance. # # The options object can contain `trigger: true` if you wish to have the # route callback be fired (not usually desirable), or `replace: true`, if # you wish to modify the current URL without adding an entry to the history. navigate: (fragment, options) -> return false unless History.started options = trigger: options if not options or options is true fragment = @getFragment fragment or '' return if @fragment is fragment @fragment = fragment url = @root + fragment # If pushState is available, we use it to set the fragment as a real URL. if @_hasPushState method = if options.replace then 'replaceState' else 'pushState' @history[method] {}, document.title, url # If hash changes haven't been explicitly disabled, update the hash # fragment to store history. else if @_wantsHashChange @_updateHash @location, fragment, options.replace if @iframe and (fragment != @getFragment(@getHash @iframe)) # Opening and closing the iframe tricks IE7 and earlier to push a # history entry on hash-tag change. When replace is true, we don't # want this. @iframe.document.open().close() unless options.replace @_updateHash @iframe.location, fragment, options.replace # If you've told us that you explicitly don't want fallback hashchange- # based history, then `navigate` becomes a page refresh. else return @location.assign url @loadUrl fragment if options.trigger # Update the hash location, either replacing the current entry, or adding # a new one to the browser history. _updateHash: (location, fragment, replace) -> if replace href = location.href.replace /(javascript:|#).*$/, '' location.replace href + '#' + fragment else # Some browsers require that `hash` contains a leading #. location.hash = '#' + fragment History = Backbone.History # Create the default Backbone.history. Backbone.history = new History ### Helpers ------- Helper function to correctly set up the prototype chain, for subclasses. Similar to `goog.inherits`, but uses a hash of prototype properties and class properties to be extended. ### extend = (protoProps, staticProps) -> parent = @ # The constructor function for the new subclass is either defined by you # (the "constructor" property in your `extend` definition), or defaulted # by us to simply call the parent's constructor. if protoProps and _.has protoProps, 'constructor' child = protoProps.constructor else child = -> parent.apply @, arguments # Add static properties to the constructor function, if supplied. _.extend child, parent, staticProps # Set the prototype chain to inherit from `parent`, without calling # `parent`'s constructor function. class Surrogate constructor: -> @constructor = child Surrogate.prototype = parent.prototype child.prototype = new Surrogate # Add prototype properties (instance properties) to the subclass, # if supplied. _.extend(child.prototype, protoProps) if protoProps # Set a convenience property in case the parent's prototype is needed # later. child.__super__ = parent.prototype child # Set up inheritance for the model, collection, router, view and history. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend # Throw an error when a URL is needed, and none is supplied. urlError = -> throw new Error 'A "url" property or function must be specified' # Wrap an optional error callback with a fallback error event. wrapError = (model, options) -> error = options.error options.error = (resp) -> error(model, resp, options) if error model.trigger 'error', model, resp, options
[ { "context": "= 0\n while i isnt 10\n key = (if (i < 8) then \"push\" else \"pop\")\n array[key] i\n i++\n assertEqu", "end": 2032, "score": 0.41779181361198425, "start": 2028, "tag": "KEY", "value": "push" }, { "context": "i isnt 10\n key = (if (i < 8) then \"push\" else \"pop\")\n array[key] i\n i++\n assertEquals 6, arra", "end": 2043, "score": 0.4664289355278015, "start": 2040, "tag": "KEY", "value": "pop" }, { "context": "ast property\n f.field = ->\n \"field\"\n\n key = \"field\"\n i = 0\n while i isnt 10\n assertEquals key, ", "end": 3280, "score": 0.9130495190620422, "start": 3275, "tag": "KEY", "value": "field" }, { "context": "->\n \"four\"\n\n f.five = ->\n \"five\"\n\n key = \"four\"\n i = 0\n while i isnt 10\n assertEquals key, ", "end": 3577, "score": 0.9835085272789001, "start": 3573, "tag": "KEY", "value": "four" }, { "context": "isnt 10\n assertEquals key, f[key]()\n key = \"five\" if i is 5\n i++\n \n # Calling on global obje", "end": 3651, "score": 0.8716992139816284, "start": 3647, "tag": "KEY", "value": "five" }, { "context": "\n i++\n \n # Calling on global object\n key = \"globalFunction1\"\n expect = \"function1\"\n i = 0\n while i isnt 10", "end": 3728, "score": 0.9929280877113342, "start": 3713, "tag": "KEY", "value": "globalFunction1" }, { "context": " expect, global[key]()\n if i is 5\n key = \"globalFunction2\"\n expect = \"function2\"\n i++\n return\ntest", "end": 3860, "score": 0.9977414608001709, "start": 3845, "tag": "KEY", "value": "globalFunction2" } ]
deps/v8/test/mjsunit/keyed-call-ic.coffee
lxe/io.coffee
0
# Copyright 2010 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # A test for keyed call ICs. globalFunction1 = -> "function1" globalFunction2 = -> "function2" testGlobals = -> assertEquals "[object global]", this[toStringName]() assertEquals "[object global]", global[toStringName]() return F = -> testKeyTransitions = -> i = undefined key = undefined result = undefined message = undefined f = new F() # Custom call generators array = [] i = 0 while i isnt 10 key = (if (i < 8) then "push" else "pop") array[key] i i++ assertEquals 6, array.length i = 0 while i isnt array.length assertEquals i, array[i] i++ i = 0 while i isnt 10 key = (if (i < 3) then "pop" else "push") array[key] i i++ assertEquals 10, array.length i = 0 while i isnt array.length assertEquals i, array[i] i++ string = "ABCDEFGHIJ" i = 0 while i isnt 10 key = ((if (i < 5) then "charAt" else "charCodeAt")) result = string[key](i) message = "'" + string + "'['" + key + "'](" + i + ")" if i < 5 assertEquals string.charAt(i), result, message else assertEquals string.charCodeAt(i), result, message i++ i = 0 while i isnt 10 key = ((if (i < 5) then "charCodeAt" else "charAt")) result = string[key](i) message = "'" + string + "'['" + key + "'](" + i + ")" if i < 5 assertEquals string.charCodeAt(i), result, message else assertEquals string.charAt(i), result, message i++ # Function is a constant property key = "one" i = 0 while i isnt 10 assertEquals key, f[key]() key = "two" if i is 5 # the name change should case a miss i++ # Function is a fast property f.field = -> "field" key = "field" i = 0 while i isnt 10 assertEquals key, f[key]() key = "two" if i is 5 # the name change should case a miss i++ # Calling on slow case object f.prop = 0 delete f.prop # force the object to the slow case f.four = -> "four" f.five = -> "five" key = "four" i = 0 while i isnt 10 assertEquals key, f[key]() key = "five" if i is 5 i++ # Calling on global object key = "globalFunction1" expect = "function1" i = 0 while i isnt 10 assertEquals expect, global[key]() if i is 5 key = "globalFunction2" expect = "function2" i++ return testTypeTransitions = -> f = new F() s = "" m = "one" i = undefined s = "" i = 0 while i isnt 10 if i is 5 F::one = -> "1" s += f[m]() i++ assertEquals "oneoneoneoneone11111", s s = "" i = 0 while i isnt 10 if i is 5 f.__proto__ = one: -> "I" s += f[m]() i++ assertEquals "11111IIIII", s s = "" i = 0 while i isnt 10 if i is 5 f.one = -> "ONE" s += f[m]() i++ assertEquals "IIIIIONEONEONEONEONE", s m = "toString" s = "" obj = toString: -> "2" i = 0 while i isnt 10 obj = "TWO" if i is 5 s += obj[m]() i++ assertEquals "22222TWOTWOTWOTWOTWO", s s = "" obj = toString: -> "ONE" m = "toString" i = 0 while i isnt 10 obj = 1 if i is 5 s += obj[m]() i++ assertEquals "ONEONEONEONEONE11111", s return toStringName = "toString" global = this assertEquals "[object global]", this[toStringName]() assertEquals "[object global]", global[toStringName]() testGlobals() F::one = -> "one" F::two = -> "two" F::three = -> "three" keys = [ "one" "one" "one" "one" "two" "two" "one" "three" "one" "two" ] testKeyTransitions() testTypeTransitions()
171759
# Copyright 2010 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # A test for keyed call ICs. globalFunction1 = -> "function1" globalFunction2 = -> "function2" testGlobals = -> assertEquals "[object global]", this[toStringName]() assertEquals "[object global]", global[toStringName]() return F = -> testKeyTransitions = -> i = undefined key = undefined result = undefined message = undefined f = new F() # Custom call generators array = [] i = 0 while i isnt 10 key = (if (i < 8) then "<KEY>" else "<KEY>") array[key] i i++ assertEquals 6, array.length i = 0 while i isnt array.length assertEquals i, array[i] i++ i = 0 while i isnt 10 key = (if (i < 3) then "pop" else "push") array[key] i i++ assertEquals 10, array.length i = 0 while i isnt array.length assertEquals i, array[i] i++ string = "ABCDEFGHIJ" i = 0 while i isnt 10 key = ((if (i < 5) then "charAt" else "charCodeAt")) result = string[key](i) message = "'" + string + "'['" + key + "'](" + i + ")" if i < 5 assertEquals string.charAt(i), result, message else assertEquals string.charCodeAt(i), result, message i++ i = 0 while i isnt 10 key = ((if (i < 5) then "charCodeAt" else "charAt")) result = string[key](i) message = "'" + string + "'['" + key + "'](" + i + ")" if i < 5 assertEquals string.charCodeAt(i), result, message else assertEquals string.charAt(i), result, message i++ # Function is a constant property key = "one" i = 0 while i isnt 10 assertEquals key, f[key]() key = "two" if i is 5 # the name change should case a miss i++ # Function is a fast property f.field = -> "field" key = "<KEY>" i = 0 while i isnt 10 assertEquals key, f[key]() key = "two" if i is 5 # the name change should case a miss i++ # Calling on slow case object f.prop = 0 delete f.prop # force the object to the slow case f.four = -> "four" f.five = -> "five" key = "<KEY>" i = 0 while i isnt 10 assertEquals key, f[key]() key = "<KEY>" if i is 5 i++ # Calling on global object key = "<KEY>" expect = "function1" i = 0 while i isnt 10 assertEquals expect, global[key]() if i is 5 key = "<KEY>" expect = "function2" i++ return testTypeTransitions = -> f = new F() s = "" m = "one" i = undefined s = "" i = 0 while i isnt 10 if i is 5 F::one = -> "1" s += f[m]() i++ assertEquals "oneoneoneoneone11111", s s = "" i = 0 while i isnt 10 if i is 5 f.__proto__ = one: -> "I" s += f[m]() i++ assertEquals "11111IIIII", s s = "" i = 0 while i isnt 10 if i is 5 f.one = -> "ONE" s += f[m]() i++ assertEquals "IIIIIONEONEONEONEONE", s m = "toString" s = "" obj = toString: -> "2" i = 0 while i isnt 10 obj = "TWO" if i is 5 s += obj[m]() i++ assertEquals "22222TWOTWOTWOTWOTWO", s s = "" obj = toString: -> "ONE" m = "toString" i = 0 while i isnt 10 obj = 1 if i is 5 s += obj[m]() i++ assertEquals "ONEONEONEONEONE11111", s return toStringName = "toString" global = this assertEquals "[object global]", this[toStringName]() assertEquals "[object global]", global[toStringName]() testGlobals() F::one = -> "one" F::two = -> "two" F::three = -> "three" keys = [ "one" "one" "one" "one" "two" "two" "one" "three" "one" "two" ] testKeyTransitions() testTypeTransitions()
true
# Copyright 2010 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # A test for keyed call ICs. globalFunction1 = -> "function1" globalFunction2 = -> "function2" testGlobals = -> assertEquals "[object global]", this[toStringName]() assertEquals "[object global]", global[toStringName]() return F = -> testKeyTransitions = -> i = undefined key = undefined result = undefined message = undefined f = new F() # Custom call generators array = [] i = 0 while i isnt 10 key = (if (i < 8) then "PI:KEY:<KEY>END_PI" else "PI:KEY:<KEY>END_PI") array[key] i i++ assertEquals 6, array.length i = 0 while i isnt array.length assertEquals i, array[i] i++ i = 0 while i isnt 10 key = (if (i < 3) then "pop" else "push") array[key] i i++ assertEquals 10, array.length i = 0 while i isnt array.length assertEquals i, array[i] i++ string = "ABCDEFGHIJ" i = 0 while i isnt 10 key = ((if (i < 5) then "charAt" else "charCodeAt")) result = string[key](i) message = "'" + string + "'['" + key + "'](" + i + ")" if i < 5 assertEquals string.charAt(i), result, message else assertEquals string.charCodeAt(i), result, message i++ i = 0 while i isnt 10 key = ((if (i < 5) then "charCodeAt" else "charAt")) result = string[key](i) message = "'" + string + "'['" + key + "'](" + i + ")" if i < 5 assertEquals string.charCodeAt(i), result, message else assertEquals string.charAt(i), result, message i++ # Function is a constant property key = "one" i = 0 while i isnt 10 assertEquals key, f[key]() key = "two" if i is 5 # the name change should case a miss i++ # Function is a fast property f.field = -> "field" key = "PI:KEY:<KEY>END_PI" i = 0 while i isnt 10 assertEquals key, f[key]() key = "two" if i is 5 # the name change should case a miss i++ # Calling on slow case object f.prop = 0 delete f.prop # force the object to the slow case f.four = -> "four" f.five = -> "five" key = "PI:KEY:<KEY>END_PI" i = 0 while i isnt 10 assertEquals key, f[key]() key = "PI:KEY:<KEY>END_PI" if i is 5 i++ # Calling on global object key = "PI:KEY:<KEY>END_PI" expect = "function1" i = 0 while i isnt 10 assertEquals expect, global[key]() if i is 5 key = "PI:KEY:<KEY>END_PI" expect = "function2" i++ return testTypeTransitions = -> f = new F() s = "" m = "one" i = undefined s = "" i = 0 while i isnt 10 if i is 5 F::one = -> "1" s += f[m]() i++ assertEquals "oneoneoneoneone11111", s s = "" i = 0 while i isnt 10 if i is 5 f.__proto__ = one: -> "I" s += f[m]() i++ assertEquals "11111IIIII", s s = "" i = 0 while i isnt 10 if i is 5 f.one = -> "ONE" s += f[m]() i++ assertEquals "IIIIIONEONEONEONEONE", s m = "toString" s = "" obj = toString: -> "2" i = 0 while i isnt 10 obj = "TWO" if i is 5 s += obj[m]() i++ assertEquals "22222TWOTWOTWOTWOTWO", s s = "" obj = toString: -> "ONE" m = "toString" i = 0 while i isnt 10 obj = 1 if i is 5 s += obj[m]() i++ assertEquals "ONEONEONEONEONE11111", s return toStringName = "toString" global = this assertEquals "[object global]", this[toStringName]() assertEquals "[object global]", global[toStringName]() testGlobals() F::one = -> "one" F::two = -> "two" F::three = -> "three" keys = [ "one" "one" "one" "one" "two" "two" "one" "three" "one" "two" ] testKeyTransitions() testTypeTransitions()
[ { "context": "Items.SearchBinSets.SearchBinSet.Bin'\n key: 'BinParameter.Value'\n value: 'BinItemCount'\n aggregate: (ke", "end": 328, "score": 0.9392437934875488, "start": 310, "tag": "KEY", "value": "BinParameter.Value" }, { "context": " 'SimilarProducts.SimilarProduct'\n key: 'ASIN'\n value: 'Title'\n images:\n ", "end": 1138, "score": 0.9801808595657349, "start": 1134, "tag": "KEY", "value": "ASIN" }, { "context": " path: 'ImageSets.ImageSet'\n key: '@.Category'\n choose: (node, value, key) -> key isnt", "end": 1551, "score": 0.6417528986930847, "start": 1540, "tag": "KEY", "value": "'@.Category" } ]
example/template.coffee
djelic/json2json
128
tmpl = path: '.' aggregate: total: (key, value, existing) -> if !isArray(value) then value else value.sort().reverse()[0] pages: (key, value, existing) -> if !isArray(value) then value else value.sort().reverse()[0] as: bins: path: 'Items.SearchBinSets.SearchBinSet.Bin' key: 'BinParameter.Value' value: 'BinItemCount' aggregate: (key, value, existing) -> Math.max(value, existing || 0) items: path: 'Items.Item' all: true as: rank: 'SalesRank' title: 'ItemAttributes.Title' artist: 'ItemAttributes.Artist' manufacturer: 'ItemAttributes.Manufacturer' category: 'ItemAttributes.ProductGroup' price: 'Offers.Offer.OfferListing.Price.FormattedPrice' percent_saved: 'Offers.Offer.OfferListing.PercentageSaved' availability: 'Offers.Offer.OfferListing.Availability' price_new: 'OfferSummary.LowestNewPrice.FormattedPrice' price_used: 'OfferSummary.LowestUsedPrice.FormattedPrice' url: 'DetailPageURL' similar: path: 'SimilarProducts.SimilarProduct' key: 'ASIN' value: 'Title' images: path: '.' choose: ['SmallImage', 'MediumImage', 'LargeImage'] format: (node, value, key) -> key: key.replace(/Image$/, '').toLowerCase() nested: true as: url: 'URL' height: 'Height.#' width: 'Width.#' image_sets: path: 'ImageSets.ImageSet' key: '@.Category' choose: (node, value, key) -> key isnt '@' format: (node, value, key) -> key: key.replace(/Image$/, '').toLowerCase() nested: true as: url: 'URL' height: 'Height.#' width: 'Width.#' links: path: 'ItemLinks.ItemLink' key: 'Description' value: 'URL' new ObjectTemplate(tmpl).transform data
124043
tmpl = path: '.' aggregate: total: (key, value, existing) -> if !isArray(value) then value else value.sort().reverse()[0] pages: (key, value, existing) -> if !isArray(value) then value else value.sort().reverse()[0] as: bins: path: 'Items.SearchBinSets.SearchBinSet.Bin' key: '<KEY>' value: 'BinItemCount' aggregate: (key, value, existing) -> Math.max(value, existing || 0) items: path: 'Items.Item' all: true as: rank: 'SalesRank' title: 'ItemAttributes.Title' artist: 'ItemAttributes.Artist' manufacturer: 'ItemAttributes.Manufacturer' category: 'ItemAttributes.ProductGroup' price: 'Offers.Offer.OfferListing.Price.FormattedPrice' percent_saved: 'Offers.Offer.OfferListing.PercentageSaved' availability: 'Offers.Offer.OfferListing.Availability' price_new: 'OfferSummary.LowestNewPrice.FormattedPrice' price_used: 'OfferSummary.LowestUsedPrice.FormattedPrice' url: 'DetailPageURL' similar: path: 'SimilarProducts.SimilarProduct' key: '<KEY>' value: 'Title' images: path: '.' choose: ['SmallImage', 'MediumImage', 'LargeImage'] format: (node, value, key) -> key: key.replace(/Image$/, '').toLowerCase() nested: true as: url: 'URL' height: 'Height.#' width: 'Width.#' image_sets: path: 'ImageSets.ImageSet' key: <KEY>' choose: (node, value, key) -> key isnt '@' format: (node, value, key) -> key: key.replace(/Image$/, '').toLowerCase() nested: true as: url: 'URL' height: 'Height.#' width: 'Width.#' links: path: 'ItemLinks.ItemLink' key: 'Description' value: 'URL' new ObjectTemplate(tmpl).transform data
true
tmpl = path: '.' aggregate: total: (key, value, existing) -> if !isArray(value) then value else value.sort().reverse()[0] pages: (key, value, existing) -> if !isArray(value) then value else value.sort().reverse()[0] as: bins: path: 'Items.SearchBinSets.SearchBinSet.Bin' key: 'PI:KEY:<KEY>END_PI' value: 'BinItemCount' aggregate: (key, value, existing) -> Math.max(value, existing || 0) items: path: 'Items.Item' all: true as: rank: 'SalesRank' title: 'ItemAttributes.Title' artist: 'ItemAttributes.Artist' manufacturer: 'ItemAttributes.Manufacturer' category: 'ItemAttributes.ProductGroup' price: 'Offers.Offer.OfferListing.Price.FormattedPrice' percent_saved: 'Offers.Offer.OfferListing.PercentageSaved' availability: 'Offers.Offer.OfferListing.Availability' price_new: 'OfferSummary.LowestNewPrice.FormattedPrice' price_used: 'OfferSummary.LowestUsedPrice.FormattedPrice' url: 'DetailPageURL' similar: path: 'SimilarProducts.SimilarProduct' key: 'PI:KEY:<KEY>END_PI' value: 'Title' images: path: '.' choose: ['SmallImage', 'MediumImage', 'LargeImage'] format: (node, value, key) -> key: key.replace(/Image$/, '').toLowerCase() nested: true as: url: 'URL' height: 'Height.#' width: 'Width.#' image_sets: path: 'ImageSets.ImageSet' key: PI:KEY:<KEY>END_PI' choose: (node, value, key) -> key isnt '@' format: (node, value, key) -> key: key.replace(/Image$/, '').toLowerCase() nested: true as: url: 'URL' height: 'Height.#' width: 'Width.#' links: path: 'ItemLinks.ItemLink' key: 'Description' value: 'URL' new ObjectTemplate(tmpl).transform data
[ { "context": " ->\n callback(body)\n ).auth( @user, @password, true)\n\n\n # Used to get an object i", "end": 794, "score": 0.8210268020629883, "start": 789, "tag": "USERNAME", "value": "@user" }, { "context": " ->\n callback(body)\n ).auth( @user, @password, true)\n\n\n # Used to get an object i", "end": 1330, "score": 0.8922994136810303, "start": 1325, "tag": "USERNAME", "value": "@user" }, { "context": " ->\n callback(body)\n ).auth( @user, @password, true)\n\n\n getExtraCommand: (command", "end": 1784, "score": 0.8728554248809814, "start": 1779, "tag": "USERNAME", "value": "@user" }, { "context": " ->\n callback(body)\n ).auth( @user, @password, true)\n\n addCommand: (command, id, ", "end": 2102, "score": 0.9109514951705933, "start": 2097, "tag": "USERNAME", "value": "@user" }, { "context": " ->\n callback(body)\n ).auth( @user, @password, true)\n\n addExtraCommand: (command,", "end": 2437, "score": 0.9994252324104309, "start": 2432, "tag": "USERNAME", "value": "@user" }, { "context": " ->\n callback(body)\n ).auth( @user, @password, true)\n\n sendCommand: (projectID, c", "end": 2793, "score": 0.999030590057373, "start": 2788, "tag": "USERNAME", "value": "@user" }, { "context": " ->\n return res.body\n ).auth @user, @password, true\n\n constructPostData: (status_", "end": 3148, "score": 0.9991793036460876, "start": 3143, "tag": "USERNAME", "value": "@user" }, { "context": "callback) ->\n json = {}\n json.name = name\n json.description = description\n js", "end": 7453, "score": 0.810498058795929, "start": 7449, "tag": "NAME", "value": "name" }, { "context": "callback) ->\n json = {}\n json.name = name\n json.description = description\n js", "end": 7842, "score": 0.9903337955474854, "start": 7838, "tag": "NAME", "value": "name" }, { "context": "callback) ->\n json = {}\n json.name = name\n json.description = description\n th", "end": 13843, "score": 0.8038924336433411, "start": 13839, "tag": "NAME", "value": "name" } ]
src/testrail.coffee
Valencia2019/Node-TestRail
0
request = require("request") API_ROUTE = "/index.php?/api/v2/" class TestRail constructor: (@host, @user, @password) -> # used to construct the host name for the API request # Internal Command # getFullHostName: () -> return @host + API_ROUTE # Used to perform a close command on the API # Internal Command # # @param [command] The command to send to the API # @param [id] The id of the object to target in the API # @return [callback] The callback # closeCommand: (command, id, callback) -> request.post( uri: this.getFullHostName() + command + id headers: "content-type": "application/json" , (err, res, body) -> callback(body) ).auth( @user, @password, true) # Used to get an object in the API by the ID # Internal Command # # @param [command] The command to send to the API # @param [id] The id of the object to target in the API # @return [callback] The callback # getIdCommand: (command , id, callback) -> request.get( uri: this.getFullHostName() + command + id headers: "content-type": "application/json" ,(err, res, body) -> callback(body) ).auth( @user, @password, true) # Used to get an object in the API # Internal Command # # @param [command] The command to send to the API # @return [callback] The callback # getCommand: (command, callback) -> request.get( uri: this.getFullHostName() + command headers: "content-type": "application/json" ,(err, res, body) -> callback(body) ).auth( @user, @password, true) getExtraCommand: (command, id, extra, callback) -> request.get( uri: this.getFullHostName() + command + id + extra headers: "content-type": "application/json" , (err, res, body) -> callback(body) ).auth( @user, @password, true) addCommand: (command, id, postData, callback) -> request.post( uri: this.getFullHostName() + command + id headers: "content-type": "application/json" body: postData , (err, res, body) -> callback(body) ).auth( @user, @password, true) addExtraCommand: (command, id, extra, postData, callback) -> request.post( uri: this.getFullHostName() + command + id + extra, headers: "content-type": "application/json" body: postData , (err, res, body) -> callback(body) ).auth( @user, @password, true) sendCommand: (projectID, command, json) -> request.post( uri: @host + "/index.php?/api/v2/" + command + projectID headers: "content-type": "application/json" body: JSON.stringify(json) , (err, res, body) -> return res.body ).auth @user, @password, true constructPostData: (status_id, comment, test_id, seconds) -> post_data = {} post_data.status_id = status_id post_data.comment = comment post_data.elapsed = (seconds + "s") JSON.stringify post_data #-------- CASES ---------------------- # Used to fetch a case from the API # # @param [case_id] The ID of the case to fetch # @return [callback] The callback with the case object # getCase: (case_id, callback) -> this.getIdCommand("get_case/", case_id, callback) # Used to fetch cases from the API # # @param [project_id] The ID of the project # @param [suite_id] The ID of the suite # @param [section_id] The ID of the section # @return [callback] The callback with the case object # getCases: (project_id, suite_id, section_id, callback) -> if section_id? this.getExtraCommand("get_cases/", project_id, "&suite_id=" + suite_id + "&section_id=" + section_id, callback) else this.getExtraCommand("get_cases/", project_id, "&suite_id=" + suite_id , callback) # Used to add cases to the API # # @param [section_id] The ID of the section where to add # @param [title] The title of the case # @param [type_id] The id for the type of case # @param [project_id] The ID of the project # @param [estimate] The estimate of the case # @param [milestone_id] The ID of the milestone to add to # @param [refs] # @return [callback] The callback with the case object # addCase: (section_id, title, type_id, project_id, estimate, milestone_id, refs, callback) -> json = {} json.title = title json.type_id = type_id json.project_id = project_id json.estimate = estimate json.milestone_id = milestone_id json.refs = refs this.addCommand("add_case/", section_id, JSON.stringify(json) , callback) updateCase: (case_id, title, type_id,project_id,estimate,milestone_id,refs, callback) -> json = {} json.title = title json.type_id = type_id json.project_id = project_id json.estimate = estimate json.milestone_id = milestone_id json.refs = refs this.addCommand("update_case/", case_id, JSON.stringify(json) , callback) deleteCase:(case_id, callback) -> this.closeCommand("delete_case/" , case_id, callback) #-------- CASE FIELDS ----------------- getCaseFields: ( callback) -> this.getCommand("get_case_fields/" , callback) #-------- CASE TYPES ------------------ getCaseTypes: ( callback) -> this.getCommand("get_case_types/" , callback) #-------- CONFIGURATIONS ------------------ getConfigs: (project_id, callback) -> this.getIdCommand("get_configs/" , project_id, callback) addConfigGroup: (project_id, name, callback) -> json = {} json.name = name this.addCommand("add_config_group/" , project_id, JSON.stringify(json), callback) addConfig: (config_group_id, name, callback) -> json = {} json.name = name this.addCommand("add_config/" , config_group_id, JSON.stringify(json), callback) updateConfigGroup: (config_group_id, name, callback) -> json = {} json.name = name this.addCommand("update_config_group/" , config_group_id, JSON.stringify(json), callback) updateConfig: (config_id, name, callback) -> json = {} json.name = name this.addCommand("update_config/" , config_id, JSON.stringify(json), callback) deleteConfigGroup: (config_group_id, callback) -> this.closeCommand("delete_config_group/", config_group_id, callback) deleteConfig: (config_id, callback) -> this.closeCommand("delete_config/", config_id, callback) #-------- MILESTONES ------------------ getMilestone: (milestone_id, callback) -> this.getIdCommand("get_milestone/" , milestone_id, callback) getMilestones: (project_id, callback) -> this.getIdCommand("get_milestones/",project_id, callback) addMilestone: (project_id, name, description, due_on, parent_id, start_on, callback) -> json = {} json.name = name json.description = description json.due_on = due_on json.parent_id = parent_id json.start_on = start_on this.addCommand("add_milestone/", project_id, JSON.stringify(json), callback) updateMilestone: (milestone_id, name, description, due_on, start_on, is_completed, is_started, parent_id, callback) -> json = {} json.name = name json.description = description json.due_on = due_on json.parent_id = parent_id json.is_completed = is_completed json.start_on = start_on json.is_started = is_started this.addCommand("update_milestone/", milestone_id, JSON.stringify(json), callback) deleteMilestone: (milestone_id, callback) -> this.closeCommand("delete_milestone/", milestone_id, callback) #-------- PLANS ----------------------- getPlan: (plan_id, callback) -> this.getIdCommand("get_plan/",plan_id, callback) getPlans: (project_id, callback) -> this.getIdCommand("get_plans/",project_id, callback) addPlan: (project_id, name, description, milestone_id, callback) -> json = {} json.name = name json.description = description json.milestone_id = milestone_id this.addCommand("add_plan/", project_id, JSON.stringify(json), callback) #TODO: update to handle extra params addPlanEntry: (plan_id, suite_id, name, assignedto_id,include_all, callback) -> json = {} json.suite_id = suite_id json.name = name json.assignedto_id = assignedto_id json.include_all = include_all this.addCommand("add_plan_entry/", plan_id, JSON.stringify(json), callback) updatePlan: (plan_id, name, description, milestone_id,callback) -> json = {} json.name = name json.description = description json.milestone_id = milestone_id this.addCommand("update_plan/", plan_id, JSON.stringify(json), callback) updatePlanEntry: (plan_id, entry_id, name, assignedto_id,include_all, callback) -> json = {} json.name = name json.assignedto_id = assignedto_id json.include_all = include_all this.addCommand("update_plan_entry/", (plan_id + "/" + entry_id), JSON.stringify(json), callback) closePlan: (plan_id, callback) -> this.closeCommand("close_plan/", plan_id, callback) deletePlan: (plan_id, callback) -> this.closeCommand("delete_plan/", plan_id, callback) deletePlanEntry: (plan_id, entry_id, callback) -> this.closeCommand("delete_plan_entry/", (plan_id + "/" + entry_id), callback) #-------- PRIORITIES ------------------ getPriorities: (callback) -> this.getCommand("get_priorities/", callback) #-------- PROJECTS -------------------- getProject: (project_id, callback) -> this.getIdCommand("get_project/",project_id, callback) getProjects: (callback) -> this.getCommand("get_projects/", callback) addProject: (name,announcement,show_announcement, callback) -> json = {} json.name = name json.announcement = announcement json.show_announcement = show_announcement this.addCommand("add_project/", "", JSON.stringify(json), callback) updateProject: (project_id, name,announcement,show_announcement, is_completed, callback) -> json = {} json.name = name json.announcement = announcement json.show_announcement = show_announcement json.is_completed = is_completed this.addCommand("add_project/", project_id, JSON.stringify(json), callback) deleteProject: (project_id, callback) -> this.closeCommand("delete_project/",project_id, callback) #-------- RESULTS --------------------- getResults: (test_id, callback, limit) -> if not limit? this.getIdCommand("get_results/",test_id, callback) else extra = "&limit=" + limit this.getExtraCommand("get_results/",test_id, extra, callback) getResultsForCase: (run_id, case_id, limit, callback) -> if not limit? extra = "/" + case_id this.getExtraCommand("get_results_for_case/",run_id, extra, callback) else extra = "/" + case_id + "&limit=" + limit this.getExtraCommand("get_results_for_case/",run_id, extra, callback) addResult: (test_id, status_id, comment, version, elapsed, defects, assignedto_id, callback) -> json = {} json.status_id = status_id json.comment = comment json.version = version json.elapsed = elapsed json.defects = defects json.assignedto_id = assignedto_id this.addCommand("add_result/", test_id, JSON.stringify(json), callback) addResults: (run_id, results, callback) -> this.addExtraCommand("add_results/", run_id, JSON.stringify(results), callback) addResultForCase: (run_id, case_id, status_id, comment, version, elapsed, defects, assignedto_id, callback) -> json = {} json.status_id = status_id json.comment = comment json.version = version json.elapsed = elapsed json.defects = defects json.assignedto_id = assignedto_id this.addExtraCommand("add_result_for_case/", run_id, ("/" + case_id), JSON.stringify(json), callback) addResultsForCases: (run_id, results, callback) -> this.addExtraCommand("add_results_for_cases/", run_id, "", JSON.stringify(results), callback) #-------- RESULT FIELDS --------------------- getResultFields: (callback) -> this.getIdCommand("get_result_fields/" , "", callback) #-------- RUNS ------------------------ getRun: (run_id, callback) -> this.getIdCommand("get_run/" , run_id, callback) getRuns: (run_id, callback) -> this.getIdCommand("get_runs/" , run_id, callback) #TODO: Include all switch and case id select addRun: (projectID,suite_id,name,description, milestone_id, callback) -> json = {} json.suite_id = suite_id json.name = name json.description = description json.milestone_id = milestone_id this.addCommand("add_run/", projectID, JSON.stringify(json) , callback) updateRun: (runID,name,description, callback) -> json = {} json.name = name json.description = description this.addCommand("update_run/", runID, JSON.stringify(json) , callback) closeRun: (run_id,callback) -> this.closeCommand("close_run/", run_id, callback) deleteRun: (run_id,callback) -> this.closeCommand("delete_run/", run_id, callback) #-------- STATUSES -------------------- getStatuses: (callback) -> this.getCommand("get_statuses/", callback) #-------- SECTIONS -------------------- getSection: (section_id , callback) -> this.getIdCommand("get_section/" , section_id, callback) getSections: (project_id, suite_id, callback) -> this.getExtraCommand("get_sections/" , project_id, "&suite_id=" + suite_id, callback) addSection: (project_id, suite_id, parent_id, name, callback) -> json = {} json.suite_id = suite_id json.parent_id = parent_id json.name = name this.addCommand("add_section/", project_id, JSON.stringify(json) , callback) updateSection: (section_id, name, callback) -> json = {} json.name = name this.addCommand("update_Section/", section_id, JSON.stringify(json) , callback) deleteSection: (section_id, callback) -> this.closeCommand("delete_section/", section_id, callback) #-------- SUITES ----------- getSuite: (suite_id, callback) -> this.getIdCommand("get_suite/" , suite_id, callback) getSuites: (project_id, callback) -> this.getIdCommand("get_suites/" , project_id, callback) addSuite: (project_id,name, description, callback) -> json = {} json.name = name json.description = description this.addCommand("add_suite/", project_id, JSON.stringify(json) , callback) updateSuite: (suite_id,name, description, callback) -> json = {} json.name = name json.description = description this.addCommand("update_suite/", suite_id, JSON.stringify(json) , callback) deleteSuite: (suite_id, callback) -> this.closeCommand("delete_suite/", suite_id, callback) #-------- TESTS ----------------------- getTest: (test_id, callback) -> this.getIdCommand("get_test/" , test_id, callback) getTests: (run_id, callback) -> this.getIdCommand("get_tests/" , run_id, callback) #-------- USERS ----------------------- getUser: (user_id, callback) -> this.getIdCommand("get_user/" , user_id, callback) getUserByEmail: (email, callback) -> this.getExtraCommand("" , "", "get_user_by_email&email=" + email, callback) getUsers: (callback) -> this.getCommand("get_users/" , callback) module.exports = TestRail
179628
request = require("request") API_ROUTE = "/index.php?/api/v2/" class TestRail constructor: (@host, @user, @password) -> # used to construct the host name for the API request # Internal Command # getFullHostName: () -> return @host + API_ROUTE # Used to perform a close command on the API # Internal Command # # @param [command] The command to send to the API # @param [id] The id of the object to target in the API # @return [callback] The callback # closeCommand: (command, id, callback) -> request.post( uri: this.getFullHostName() + command + id headers: "content-type": "application/json" , (err, res, body) -> callback(body) ).auth( @user, @password, true) # Used to get an object in the API by the ID # Internal Command # # @param [command] The command to send to the API # @param [id] The id of the object to target in the API # @return [callback] The callback # getIdCommand: (command , id, callback) -> request.get( uri: this.getFullHostName() + command + id headers: "content-type": "application/json" ,(err, res, body) -> callback(body) ).auth( @user, @password, true) # Used to get an object in the API # Internal Command # # @param [command] The command to send to the API # @return [callback] The callback # getCommand: (command, callback) -> request.get( uri: this.getFullHostName() + command headers: "content-type": "application/json" ,(err, res, body) -> callback(body) ).auth( @user, @password, true) getExtraCommand: (command, id, extra, callback) -> request.get( uri: this.getFullHostName() + command + id + extra headers: "content-type": "application/json" , (err, res, body) -> callback(body) ).auth( @user, @password, true) addCommand: (command, id, postData, callback) -> request.post( uri: this.getFullHostName() + command + id headers: "content-type": "application/json" body: postData , (err, res, body) -> callback(body) ).auth( @user, @password, true) addExtraCommand: (command, id, extra, postData, callback) -> request.post( uri: this.getFullHostName() + command + id + extra, headers: "content-type": "application/json" body: postData , (err, res, body) -> callback(body) ).auth( @user, @password, true) sendCommand: (projectID, command, json) -> request.post( uri: @host + "/index.php?/api/v2/" + command + projectID headers: "content-type": "application/json" body: JSON.stringify(json) , (err, res, body) -> return res.body ).auth @user, @password, true constructPostData: (status_id, comment, test_id, seconds) -> post_data = {} post_data.status_id = status_id post_data.comment = comment post_data.elapsed = (seconds + "s") JSON.stringify post_data #-------- CASES ---------------------- # Used to fetch a case from the API # # @param [case_id] The ID of the case to fetch # @return [callback] The callback with the case object # getCase: (case_id, callback) -> this.getIdCommand("get_case/", case_id, callback) # Used to fetch cases from the API # # @param [project_id] The ID of the project # @param [suite_id] The ID of the suite # @param [section_id] The ID of the section # @return [callback] The callback with the case object # getCases: (project_id, suite_id, section_id, callback) -> if section_id? this.getExtraCommand("get_cases/", project_id, "&suite_id=" + suite_id + "&section_id=" + section_id, callback) else this.getExtraCommand("get_cases/", project_id, "&suite_id=" + suite_id , callback) # Used to add cases to the API # # @param [section_id] The ID of the section where to add # @param [title] The title of the case # @param [type_id] The id for the type of case # @param [project_id] The ID of the project # @param [estimate] The estimate of the case # @param [milestone_id] The ID of the milestone to add to # @param [refs] # @return [callback] The callback with the case object # addCase: (section_id, title, type_id, project_id, estimate, milestone_id, refs, callback) -> json = {} json.title = title json.type_id = type_id json.project_id = project_id json.estimate = estimate json.milestone_id = milestone_id json.refs = refs this.addCommand("add_case/", section_id, JSON.stringify(json) , callback) updateCase: (case_id, title, type_id,project_id,estimate,milestone_id,refs, callback) -> json = {} json.title = title json.type_id = type_id json.project_id = project_id json.estimate = estimate json.milestone_id = milestone_id json.refs = refs this.addCommand("update_case/", case_id, JSON.stringify(json) , callback) deleteCase:(case_id, callback) -> this.closeCommand("delete_case/" , case_id, callback) #-------- CASE FIELDS ----------------- getCaseFields: ( callback) -> this.getCommand("get_case_fields/" , callback) #-------- CASE TYPES ------------------ getCaseTypes: ( callback) -> this.getCommand("get_case_types/" , callback) #-------- CONFIGURATIONS ------------------ getConfigs: (project_id, callback) -> this.getIdCommand("get_configs/" , project_id, callback) addConfigGroup: (project_id, name, callback) -> json = {} json.name = name this.addCommand("add_config_group/" , project_id, JSON.stringify(json), callback) addConfig: (config_group_id, name, callback) -> json = {} json.name = name this.addCommand("add_config/" , config_group_id, JSON.stringify(json), callback) updateConfigGroup: (config_group_id, name, callback) -> json = {} json.name = name this.addCommand("update_config_group/" , config_group_id, JSON.stringify(json), callback) updateConfig: (config_id, name, callback) -> json = {} json.name = name this.addCommand("update_config/" , config_id, JSON.stringify(json), callback) deleteConfigGroup: (config_group_id, callback) -> this.closeCommand("delete_config_group/", config_group_id, callback) deleteConfig: (config_id, callback) -> this.closeCommand("delete_config/", config_id, callback) #-------- MILESTONES ------------------ getMilestone: (milestone_id, callback) -> this.getIdCommand("get_milestone/" , milestone_id, callback) getMilestones: (project_id, callback) -> this.getIdCommand("get_milestones/",project_id, callback) addMilestone: (project_id, name, description, due_on, parent_id, start_on, callback) -> json = {} json.name = <NAME> json.description = description json.due_on = due_on json.parent_id = parent_id json.start_on = start_on this.addCommand("add_milestone/", project_id, JSON.stringify(json), callback) updateMilestone: (milestone_id, name, description, due_on, start_on, is_completed, is_started, parent_id, callback) -> json = {} json.name = <NAME> json.description = description json.due_on = due_on json.parent_id = parent_id json.is_completed = is_completed json.start_on = start_on json.is_started = is_started this.addCommand("update_milestone/", milestone_id, JSON.stringify(json), callback) deleteMilestone: (milestone_id, callback) -> this.closeCommand("delete_milestone/", milestone_id, callback) #-------- PLANS ----------------------- getPlan: (plan_id, callback) -> this.getIdCommand("get_plan/",plan_id, callback) getPlans: (project_id, callback) -> this.getIdCommand("get_plans/",project_id, callback) addPlan: (project_id, name, description, milestone_id, callback) -> json = {} json.name = name json.description = description json.milestone_id = milestone_id this.addCommand("add_plan/", project_id, JSON.stringify(json), callback) #TODO: update to handle extra params addPlanEntry: (plan_id, suite_id, name, assignedto_id,include_all, callback) -> json = {} json.suite_id = suite_id json.name = name json.assignedto_id = assignedto_id json.include_all = include_all this.addCommand("add_plan_entry/", plan_id, JSON.stringify(json), callback) updatePlan: (plan_id, name, description, milestone_id,callback) -> json = {} json.name = name json.description = description json.milestone_id = milestone_id this.addCommand("update_plan/", plan_id, JSON.stringify(json), callback) updatePlanEntry: (plan_id, entry_id, name, assignedto_id,include_all, callback) -> json = {} json.name = name json.assignedto_id = assignedto_id json.include_all = include_all this.addCommand("update_plan_entry/", (plan_id + "/" + entry_id), JSON.stringify(json), callback) closePlan: (plan_id, callback) -> this.closeCommand("close_plan/", plan_id, callback) deletePlan: (plan_id, callback) -> this.closeCommand("delete_plan/", plan_id, callback) deletePlanEntry: (plan_id, entry_id, callback) -> this.closeCommand("delete_plan_entry/", (plan_id + "/" + entry_id), callback) #-------- PRIORITIES ------------------ getPriorities: (callback) -> this.getCommand("get_priorities/", callback) #-------- PROJECTS -------------------- getProject: (project_id, callback) -> this.getIdCommand("get_project/",project_id, callback) getProjects: (callback) -> this.getCommand("get_projects/", callback) addProject: (name,announcement,show_announcement, callback) -> json = {} json.name = name json.announcement = announcement json.show_announcement = show_announcement this.addCommand("add_project/", "", JSON.stringify(json), callback) updateProject: (project_id, name,announcement,show_announcement, is_completed, callback) -> json = {} json.name = name json.announcement = announcement json.show_announcement = show_announcement json.is_completed = is_completed this.addCommand("add_project/", project_id, JSON.stringify(json), callback) deleteProject: (project_id, callback) -> this.closeCommand("delete_project/",project_id, callback) #-------- RESULTS --------------------- getResults: (test_id, callback, limit) -> if not limit? this.getIdCommand("get_results/",test_id, callback) else extra = "&limit=" + limit this.getExtraCommand("get_results/",test_id, extra, callback) getResultsForCase: (run_id, case_id, limit, callback) -> if not limit? extra = "/" + case_id this.getExtraCommand("get_results_for_case/",run_id, extra, callback) else extra = "/" + case_id + "&limit=" + limit this.getExtraCommand("get_results_for_case/",run_id, extra, callback) addResult: (test_id, status_id, comment, version, elapsed, defects, assignedto_id, callback) -> json = {} json.status_id = status_id json.comment = comment json.version = version json.elapsed = elapsed json.defects = defects json.assignedto_id = assignedto_id this.addCommand("add_result/", test_id, JSON.stringify(json), callback) addResults: (run_id, results, callback) -> this.addExtraCommand("add_results/", run_id, JSON.stringify(results), callback) addResultForCase: (run_id, case_id, status_id, comment, version, elapsed, defects, assignedto_id, callback) -> json = {} json.status_id = status_id json.comment = comment json.version = version json.elapsed = elapsed json.defects = defects json.assignedto_id = assignedto_id this.addExtraCommand("add_result_for_case/", run_id, ("/" + case_id), JSON.stringify(json), callback) addResultsForCases: (run_id, results, callback) -> this.addExtraCommand("add_results_for_cases/", run_id, "", JSON.stringify(results), callback) #-------- RESULT FIELDS --------------------- getResultFields: (callback) -> this.getIdCommand("get_result_fields/" , "", callback) #-------- RUNS ------------------------ getRun: (run_id, callback) -> this.getIdCommand("get_run/" , run_id, callback) getRuns: (run_id, callback) -> this.getIdCommand("get_runs/" , run_id, callback) #TODO: Include all switch and case id select addRun: (projectID,suite_id,name,description, milestone_id, callback) -> json = {} json.suite_id = suite_id json.name = name json.description = description json.milestone_id = milestone_id this.addCommand("add_run/", projectID, JSON.stringify(json) , callback) updateRun: (runID,name,description, callback) -> json = {} json.name = <NAME> json.description = description this.addCommand("update_run/", runID, JSON.stringify(json) , callback) closeRun: (run_id,callback) -> this.closeCommand("close_run/", run_id, callback) deleteRun: (run_id,callback) -> this.closeCommand("delete_run/", run_id, callback) #-------- STATUSES -------------------- getStatuses: (callback) -> this.getCommand("get_statuses/", callback) #-------- SECTIONS -------------------- getSection: (section_id , callback) -> this.getIdCommand("get_section/" , section_id, callback) getSections: (project_id, suite_id, callback) -> this.getExtraCommand("get_sections/" , project_id, "&suite_id=" + suite_id, callback) addSection: (project_id, suite_id, parent_id, name, callback) -> json = {} json.suite_id = suite_id json.parent_id = parent_id json.name = name this.addCommand("add_section/", project_id, JSON.stringify(json) , callback) updateSection: (section_id, name, callback) -> json = {} json.name = name this.addCommand("update_Section/", section_id, JSON.stringify(json) , callback) deleteSection: (section_id, callback) -> this.closeCommand("delete_section/", section_id, callback) #-------- SUITES ----------- getSuite: (suite_id, callback) -> this.getIdCommand("get_suite/" , suite_id, callback) getSuites: (project_id, callback) -> this.getIdCommand("get_suites/" , project_id, callback) addSuite: (project_id,name, description, callback) -> json = {} json.name = name json.description = description this.addCommand("add_suite/", project_id, JSON.stringify(json) , callback) updateSuite: (suite_id,name, description, callback) -> json = {} json.name = name json.description = description this.addCommand("update_suite/", suite_id, JSON.stringify(json) , callback) deleteSuite: (suite_id, callback) -> this.closeCommand("delete_suite/", suite_id, callback) #-------- TESTS ----------------------- getTest: (test_id, callback) -> this.getIdCommand("get_test/" , test_id, callback) getTests: (run_id, callback) -> this.getIdCommand("get_tests/" , run_id, callback) #-------- USERS ----------------------- getUser: (user_id, callback) -> this.getIdCommand("get_user/" , user_id, callback) getUserByEmail: (email, callback) -> this.getExtraCommand("" , "", "get_user_by_email&email=" + email, callback) getUsers: (callback) -> this.getCommand("get_users/" , callback) module.exports = TestRail
true
request = require("request") API_ROUTE = "/index.php?/api/v2/" class TestRail constructor: (@host, @user, @password) -> # used to construct the host name for the API request # Internal Command # getFullHostName: () -> return @host + API_ROUTE # Used to perform a close command on the API # Internal Command # # @param [command] The command to send to the API # @param [id] The id of the object to target in the API # @return [callback] The callback # closeCommand: (command, id, callback) -> request.post( uri: this.getFullHostName() + command + id headers: "content-type": "application/json" , (err, res, body) -> callback(body) ).auth( @user, @password, true) # Used to get an object in the API by the ID # Internal Command # # @param [command] The command to send to the API # @param [id] The id of the object to target in the API # @return [callback] The callback # getIdCommand: (command , id, callback) -> request.get( uri: this.getFullHostName() + command + id headers: "content-type": "application/json" ,(err, res, body) -> callback(body) ).auth( @user, @password, true) # Used to get an object in the API # Internal Command # # @param [command] The command to send to the API # @return [callback] The callback # getCommand: (command, callback) -> request.get( uri: this.getFullHostName() + command headers: "content-type": "application/json" ,(err, res, body) -> callback(body) ).auth( @user, @password, true) getExtraCommand: (command, id, extra, callback) -> request.get( uri: this.getFullHostName() + command + id + extra headers: "content-type": "application/json" , (err, res, body) -> callback(body) ).auth( @user, @password, true) addCommand: (command, id, postData, callback) -> request.post( uri: this.getFullHostName() + command + id headers: "content-type": "application/json" body: postData , (err, res, body) -> callback(body) ).auth( @user, @password, true) addExtraCommand: (command, id, extra, postData, callback) -> request.post( uri: this.getFullHostName() + command + id + extra, headers: "content-type": "application/json" body: postData , (err, res, body) -> callback(body) ).auth( @user, @password, true) sendCommand: (projectID, command, json) -> request.post( uri: @host + "/index.php?/api/v2/" + command + projectID headers: "content-type": "application/json" body: JSON.stringify(json) , (err, res, body) -> return res.body ).auth @user, @password, true constructPostData: (status_id, comment, test_id, seconds) -> post_data = {} post_data.status_id = status_id post_data.comment = comment post_data.elapsed = (seconds + "s") JSON.stringify post_data #-------- CASES ---------------------- # Used to fetch a case from the API # # @param [case_id] The ID of the case to fetch # @return [callback] The callback with the case object # getCase: (case_id, callback) -> this.getIdCommand("get_case/", case_id, callback) # Used to fetch cases from the API # # @param [project_id] The ID of the project # @param [suite_id] The ID of the suite # @param [section_id] The ID of the section # @return [callback] The callback with the case object # getCases: (project_id, suite_id, section_id, callback) -> if section_id? this.getExtraCommand("get_cases/", project_id, "&suite_id=" + suite_id + "&section_id=" + section_id, callback) else this.getExtraCommand("get_cases/", project_id, "&suite_id=" + suite_id , callback) # Used to add cases to the API # # @param [section_id] The ID of the section where to add # @param [title] The title of the case # @param [type_id] The id for the type of case # @param [project_id] The ID of the project # @param [estimate] The estimate of the case # @param [milestone_id] The ID of the milestone to add to # @param [refs] # @return [callback] The callback with the case object # addCase: (section_id, title, type_id, project_id, estimate, milestone_id, refs, callback) -> json = {} json.title = title json.type_id = type_id json.project_id = project_id json.estimate = estimate json.milestone_id = milestone_id json.refs = refs this.addCommand("add_case/", section_id, JSON.stringify(json) , callback) updateCase: (case_id, title, type_id,project_id,estimate,milestone_id,refs, callback) -> json = {} json.title = title json.type_id = type_id json.project_id = project_id json.estimate = estimate json.milestone_id = milestone_id json.refs = refs this.addCommand("update_case/", case_id, JSON.stringify(json) , callback) deleteCase:(case_id, callback) -> this.closeCommand("delete_case/" , case_id, callback) #-------- CASE FIELDS ----------------- getCaseFields: ( callback) -> this.getCommand("get_case_fields/" , callback) #-------- CASE TYPES ------------------ getCaseTypes: ( callback) -> this.getCommand("get_case_types/" , callback) #-------- CONFIGURATIONS ------------------ getConfigs: (project_id, callback) -> this.getIdCommand("get_configs/" , project_id, callback) addConfigGroup: (project_id, name, callback) -> json = {} json.name = name this.addCommand("add_config_group/" , project_id, JSON.stringify(json), callback) addConfig: (config_group_id, name, callback) -> json = {} json.name = name this.addCommand("add_config/" , config_group_id, JSON.stringify(json), callback) updateConfigGroup: (config_group_id, name, callback) -> json = {} json.name = name this.addCommand("update_config_group/" , config_group_id, JSON.stringify(json), callback) updateConfig: (config_id, name, callback) -> json = {} json.name = name this.addCommand("update_config/" , config_id, JSON.stringify(json), callback) deleteConfigGroup: (config_group_id, callback) -> this.closeCommand("delete_config_group/", config_group_id, callback) deleteConfig: (config_id, callback) -> this.closeCommand("delete_config/", config_id, callback) #-------- MILESTONES ------------------ getMilestone: (milestone_id, callback) -> this.getIdCommand("get_milestone/" , milestone_id, callback) getMilestones: (project_id, callback) -> this.getIdCommand("get_milestones/",project_id, callback) addMilestone: (project_id, name, description, due_on, parent_id, start_on, callback) -> json = {} json.name = PI:NAME:<NAME>END_PI json.description = description json.due_on = due_on json.parent_id = parent_id json.start_on = start_on this.addCommand("add_milestone/", project_id, JSON.stringify(json), callback) updateMilestone: (milestone_id, name, description, due_on, start_on, is_completed, is_started, parent_id, callback) -> json = {} json.name = PI:NAME:<NAME>END_PI json.description = description json.due_on = due_on json.parent_id = parent_id json.is_completed = is_completed json.start_on = start_on json.is_started = is_started this.addCommand("update_milestone/", milestone_id, JSON.stringify(json), callback) deleteMilestone: (milestone_id, callback) -> this.closeCommand("delete_milestone/", milestone_id, callback) #-------- PLANS ----------------------- getPlan: (plan_id, callback) -> this.getIdCommand("get_plan/",plan_id, callback) getPlans: (project_id, callback) -> this.getIdCommand("get_plans/",project_id, callback) addPlan: (project_id, name, description, milestone_id, callback) -> json = {} json.name = name json.description = description json.milestone_id = milestone_id this.addCommand("add_plan/", project_id, JSON.stringify(json), callback) #TODO: update to handle extra params addPlanEntry: (plan_id, suite_id, name, assignedto_id,include_all, callback) -> json = {} json.suite_id = suite_id json.name = name json.assignedto_id = assignedto_id json.include_all = include_all this.addCommand("add_plan_entry/", plan_id, JSON.stringify(json), callback) updatePlan: (plan_id, name, description, milestone_id,callback) -> json = {} json.name = name json.description = description json.milestone_id = milestone_id this.addCommand("update_plan/", plan_id, JSON.stringify(json), callback) updatePlanEntry: (plan_id, entry_id, name, assignedto_id,include_all, callback) -> json = {} json.name = name json.assignedto_id = assignedto_id json.include_all = include_all this.addCommand("update_plan_entry/", (plan_id + "/" + entry_id), JSON.stringify(json), callback) closePlan: (plan_id, callback) -> this.closeCommand("close_plan/", plan_id, callback) deletePlan: (plan_id, callback) -> this.closeCommand("delete_plan/", plan_id, callback) deletePlanEntry: (plan_id, entry_id, callback) -> this.closeCommand("delete_plan_entry/", (plan_id + "/" + entry_id), callback) #-------- PRIORITIES ------------------ getPriorities: (callback) -> this.getCommand("get_priorities/", callback) #-------- PROJECTS -------------------- getProject: (project_id, callback) -> this.getIdCommand("get_project/",project_id, callback) getProjects: (callback) -> this.getCommand("get_projects/", callback) addProject: (name,announcement,show_announcement, callback) -> json = {} json.name = name json.announcement = announcement json.show_announcement = show_announcement this.addCommand("add_project/", "", JSON.stringify(json), callback) updateProject: (project_id, name,announcement,show_announcement, is_completed, callback) -> json = {} json.name = name json.announcement = announcement json.show_announcement = show_announcement json.is_completed = is_completed this.addCommand("add_project/", project_id, JSON.stringify(json), callback) deleteProject: (project_id, callback) -> this.closeCommand("delete_project/",project_id, callback) #-------- RESULTS --------------------- getResults: (test_id, callback, limit) -> if not limit? this.getIdCommand("get_results/",test_id, callback) else extra = "&limit=" + limit this.getExtraCommand("get_results/",test_id, extra, callback) getResultsForCase: (run_id, case_id, limit, callback) -> if not limit? extra = "/" + case_id this.getExtraCommand("get_results_for_case/",run_id, extra, callback) else extra = "/" + case_id + "&limit=" + limit this.getExtraCommand("get_results_for_case/",run_id, extra, callback) addResult: (test_id, status_id, comment, version, elapsed, defects, assignedto_id, callback) -> json = {} json.status_id = status_id json.comment = comment json.version = version json.elapsed = elapsed json.defects = defects json.assignedto_id = assignedto_id this.addCommand("add_result/", test_id, JSON.stringify(json), callback) addResults: (run_id, results, callback) -> this.addExtraCommand("add_results/", run_id, JSON.stringify(results), callback) addResultForCase: (run_id, case_id, status_id, comment, version, elapsed, defects, assignedto_id, callback) -> json = {} json.status_id = status_id json.comment = comment json.version = version json.elapsed = elapsed json.defects = defects json.assignedto_id = assignedto_id this.addExtraCommand("add_result_for_case/", run_id, ("/" + case_id), JSON.stringify(json), callback) addResultsForCases: (run_id, results, callback) -> this.addExtraCommand("add_results_for_cases/", run_id, "", JSON.stringify(results), callback) #-------- RESULT FIELDS --------------------- getResultFields: (callback) -> this.getIdCommand("get_result_fields/" , "", callback) #-------- RUNS ------------------------ getRun: (run_id, callback) -> this.getIdCommand("get_run/" , run_id, callback) getRuns: (run_id, callback) -> this.getIdCommand("get_runs/" , run_id, callback) #TODO: Include all switch and case id select addRun: (projectID,suite_id,name,description, milestone_id, callback) -> json = {} json.suite_id = suite_id json.name = name json.description = description json.milestone_id = milestone_id this.addCommand("add_run/", projectID, JSON.stringify(json) , callback) updateRun: (runID,name,description, callback) -> json = {} json.name = PI:NAME:<NAME>END_PI json.description = description this.addCommand("update_run/", runID, JSON.stringify(json) , callback) closeRun: (run_id,callback) -> this.closeCommand("close_run/", run_id, callback) deleteRun: (run_id,callback) -> this.closeCommand("delete_run/", run_id, callback) #-------- STATUSES -------------------- getStatuses: (callback) -> this.getCommand("get_statuses/", callback) #-------- SECTIONS -------------------- getSection: (section_id , callback) -> this.getIdCommand("get_section/" , section_id, callback) getSections: (project_id, suite_id, callback) -> this.getExtraCommand("get_sections/" , project_id, "&suite_id=" + suite_id, callback) addSection: (project_id, suite_id, parent_id, name, callback) -> json = {} json.suite_id = suite_id json.parent_id = parent_id json.name = name this.addCommand("add_section/", project_id, JSON.stringify(json) , callback) updateSection: (section_id, name, callback) -> json = {} json.name = name this.addCommand("update_Section/", section_id, JSON.stringify(json) , callback) deleteSection: (section_id, callback) -> this.closeCommand("delete_section/", section_id, callback) #-------- SUITES ----------- getSuite: (suite_id, callback) -> this.getIdCommand("get_suite/" , suite_id, callback) getSuites: (project_id, callback) -> this.getIdCommand("get_suites/" , project_id, callback) addSuite: (project_id,name, description, callback) -> json = {} json.name = name json.description = description this.addCommand("add_suite/", project_id, JSON.stringify(json) , callback) updateSuite: (suite_id,name, description, callback) -> json = {} json.name = name json.description = description this.addCommand("update_suite/", suite_id, JSON.stringify(json) , callback) deleteSuite: (suite_id, callback) -> this.closeCommand("delete_suite/", suite_id, callback) #-------- TESTS ----------------------- getTest: (test_id, callback) -> this.getIdCommand("get_test/" , test_id, callback) getTests: (run_id, callback) -> this.getIdCommand("get_tests/" , run_id, callback) #-------- USERS ----------------------- getUser: (user_id, callback) -> this.getIdCommand("get_user/" , user_id, callback) getUserByEmail: (email, callback) -> this.getExtraCommand("" , "", "get_user_by_email&email=" + email, callback) getUsers: (callback) -> this.getCommand("get_users/" , callback) module.exports = TestRail
[ { "context": " list: ['1', '2', '3']\n person:\n name: 'Alexander Schilling'\n job: 'Developer'\n cdata: 'i\\'m not esca", "end": 405, "score": 0.9998220205307007, "start": 386, "tag": "NAME", "value": "Alexander Schilling" } ]
test/mocha/xml.coffee
alinex/node-formatter
0
chai = require 'chai' expect = chai.expect ### eslint-env node, mocha ### fs = require 'fs' debug = require('debug') 'test' chalk = require 'chalk' formatter = require '../../src/index' describe "XML", -> file = __dirname + '/../data/format.xml' format = 'xml' example = fs.readFileSync file, 'UTF8' data = name: 'test' list: ['1', '2', '3'] person: name: 'Alexander Schilling' job: 'Developer' cdata: 'i\'m not escaped: <xml>!' attributes: _: 'Hello all together' type: 'detail' sub: 'And specially you!' describe "parse preset file", -> it "should get object", (cb) -> formatter.parse example, format, (err, obj) -> expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() it "should work with autodetect", (cb) -> formatter.parse example, (err, obj) -> expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() it "should work with filename", (cb) -> formatter.parse example, file, (err, obj) -> expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() describe "format and parse", -> it "should reread object", (cb) -> formatter.stringify data, format, (err, text) -> expect(err, 'error').to.not.exist expect(typeof text, 'type of result').to.equal 'string' debug "result", chalk.grey text formatter.parse text, format, (err, obj) -> expect(obj, 'reread object').to.deep.equal data cb()
191641
chai = require 'chai' expect = chai.expect ### eslint-env node, mocha ### fs = require 'fs' debug = require('debug') 'test' chalk = require 'chalk' formatter = require '../../src/index' describe "XML", -> file = __dirname + '/../data/format.xml' format = 'xml' example = fs.readFileSync file, 'UTF8' data = name: 'test' list: ['1', '2', '3'] person: name: '<NAME>' job: 'Developer' cdata: 'i\'m not escaped: <xml>!' attributes: _: 'Hello all together' type: 'detail' sub: 'And specially you!' describe "parse preset file", -> it "should get object", (cb) -> formatter.parse example, format, (err, obj) -> expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() it "should work with autodetect", (cb) -> formatter.parse example, (err, obj) -> expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() it "should work with filename", (cb) -> formatter.parse example, file, (err, obj) -> expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() describe "format and parse", -> it "should reread object", (cb) -> formatter.stringify data, format, (err, text) -> expect(err, 'error').to.not.exist expect(typeof text, 'type of result').to.equal 'string' debug "result", chalk.grey text formatter.parse text, format, (err, obj) -> expect(obj, 'reread object').to.deep.equal data cb()
true
chai = require 'chai' expect = chai.expect ### eslint-env node, mocha ### fs = require 'fs' debug = require('debug') 'test' chalk = require 'chalk' formatter = require '../../src/index' describe "XML", -> file = __dirname + '/../data/format.xml' format = 'xml' example = fs.readFileSync file, 'UTF8' data = name: 'test' list: ['1', '2', '3'] person: name: 'PI:NAME:<NAME>END_PI' job: 'Developer' cdata: 'i\'m not escaped: <xml>!' attributes: _: 'Hello all together' type: 'detail' sub: 'And specially you!' describe "parse preset file", -> it "should get object", (cb) -> formatter.parse example, format, (err, obj) -> expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() it "should work with autodetect", (cb) -> formatter.parse example, (err, obj) -> expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() it "should work with filename", (cb) -> formatter.parse example, file, (err, obj) -> expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() describe "format and parse", -> it "should reread object", (cb) -> formatter.stringify data, format, (err, text) -> expect(err, 'error').to.not.exist expect(typeof text, 'type of result').to.equal 'string' debug "result", chalk.grey text formatter.parse text, format, (err, obj) -> expect(obj, 'reread object').to.deep.equal data cb()
[ { "context": "=============\n# IndexedDB wrapper class\n# Coded by Hajime Oh-yake\n# 2021.01.24 ver0.0.1\n#==========================", "end": 90, "score": 0.9998955726623535, "start": 76, "tag": "NAME", "value": "Hajime Oh-yake" } ]
src/indexStorage.coffee
digitarhythm/indexStorage
0
#===================================== # IndexedDB wrapper class # Coded by Hajime Oh-yake # 2021.01.24 ver0.0.1 #===================================== class indexStorage constructor:(param) -> # define IndexdDB name if (param?) @node_env = param.NODE_ENV || "" else @node_env = "" # Database version @version = 1 # IndexedDB object initialize @__indexDBObj = undefined @__IDBTransactionObj = undefined @__IDBKeyRangeObj = undefined @__database = undefined if (window.indexedDB) @__indexDBObj = window.indexedDB @__IDBTransactionObj = window.IDBTransaction @__IDBKeyRangeObj = window.IDBKeyRange else # Initialize failure return # Define database name if (@node_env == "develop") # developer environment @__dbname = "__indexstorage_db_develop__" else # Production environment @__dbname = "__indexstorage_db_production__" #=========================================================================== # Private method #=========================================================================== #===================================== # Database initialize #===================================== __connectDB: -> return new Promise (resolve, reject) => # DB接続 reqObj = @__indexDBObj.open(@__dbname, @version) # Update database version reqObj.onupgradeneeded = (event) => db = event.target.result objstore = db.createObjectStore("indexStorage", {keyPath : 'key'}) objstore.createIndex "primary_key", "key", unique:true multiEntry:false objstore = db.createObjectStore("preference", {keyPath : 'key'}) objstore.createIndex "primary_key", "key", unique:true multiEntry:false keylist = [] objstore.put({key: "keylist", val: keylist}) reqObj.onsuccess = (event) => @__database = event.target.result resolve(true) reqObj.onerror = (event) => reject(false) #===================================== # Add new kye to keylist #===================================== __addKeylist:(key) -> return new Promise (resolve, reject) => keylist = await @getItem("keylist", "preference") || [] if (keylist.indexOf(key) < 0) keylist.push(key) @setItem("keylist", keylist, "preference").then => resolve(keylist) else resolve(keylist) #===================================== # Remove key from keylist #===================================== __removeKeylist:(key) -> return new Promise (resolve, reject) => keylist = await @getItem("keylist", "preference") || [] index = keylist.indexOf(key) if (index >= 0) keylist.splice(index, 1) await @setItem("keylist", keylist, "preference") resolve(keylist) #=========================================================================== # Global methoc #=========================================================================== #===================================== # Return number of values #===================================== length: -> return new Promise (resolve, reject) => try await @__connectDB() transaction = @__database.transaction(["indexStorage"], "readonly") objectStore = transaction.objectStore("indexStorage") request = objectStore.count() request.onerror = (event) => @__database.close() reject(undefined) request.onsuccess = (event) => len = request.result resolve(len) #===================================== # Return key at index #===================================== key:(index) -> return new Promise (resolve, reject) => try keylist = await @getItem("keylist", "preference") || [] key = keylist[parseInt(index)] resolve(key) catch e reject(undefined) #===================================== # Return value for key #===================================== getItem:(key, storename="indexStorage") -> return new Promise (resolve, reject) => await @__connectDB() transaction = @__database.transaction([storename], "readonly") objectStore = transaction.objectStore(storename) request = objectStore.get(key) request.onerror = (event) => @__database.close() reject(undefined) request.onsuccess = (event) => val = undefined if (request.result? && request.result["key"] == key) val = request.result.val @__database.close() resolve(val) #===================================== # Set value into objectstore #===================================== setItem:(key, val, storename="indexStorage") -> return new Promise (resolve, reject) => await @__connectDB() transaction = @__database.transaction([storename], "readwrite") objectStore = transaction.objectStore(storename) objectStore.put({key: key, val: val}) transaction.onerror = (event) => @__database.close() reject(false) transaction.oncomplete = (event) => if (storename == "indexStorage") ret = await @__addKeylist(key) @__database.close() resolve(true) #===================================== # Remove key from objectstore #===================================== removeItem:(key, storename="indexStorage") -> return new Promise (resolve, reject) => await @__connectDB() transaction = @__database.transaction([storename], "readwrite") objectStore = transaction.objectStore(storename) request = objectStore.delete(key) request.onerror = (event) => @__database.close() reject(false) request.onsuccess = (event) => await @__removeKeylist(key) @__database.close() resolve(true) #===================================== # clear all data #===================================== clear: -> return new Promise (resolve, reject) => ret = await @__clearObjectStore("indexStorage") ret |= await @__clearObjectStore("preference") resolve(ret) #===================================== # database delete #===================================== delete:(database=@__dbname) -> @__indexDBObj.deleteDatabase(database) #===================================== # clear all data in object store #===================================== __clearObjectStore:(storename="indexStorage") -> return new Promise (resolve, reject) => await @__connectDB() transaction = @__database.transaction([storename], "readwrite") objectStore = transaction.objectStore(storename) request = objectStore.clear() request.onerror = (event) => @__database.close() reject(false) request.onsuccess = (event) => @__database.close() resolve(true)
15657
#===================================== # IndexedDB wrapper class # Coded by <NAME> # 2021.01.24 ver0.0.1 #===================================== class indexStorage constructor:(param) -> # define IndexdDB name if (param?) @node_env = param.NODE_ENV || "" else @node_env = "" # Database version @version = 1 # IndexedDB object initialize @__indexDBObj = undefined @__IDBTransactionObj = undefined @__IDBKeyRangeObj = undefined @__database = undefined if (window.indexedDB) @__indexDBObj = window.indexedDB @__IDBTransactionObj = window.IDBTransaction @__IDBKeyRangeObj = window.IDBKeyRange else # Initialize failure return # Define database name if (@node_env == "develop") # developer environment @__dbname = "__indexstorage_db_develop__" else # Production environment @__dbname = "__indexstorage_db_production__" #=========================================================================== # Private method #=========================================================================== #===================================== # Database initialize #===================================== __connectDB: -> return new Promise (resolve, reject) => # DB接続 reqObj = @__indexDBObj.open(@__dbname, @version) # Update database version reqObj.onupgradeneeded = (event) => db = event.target.result objstore = db.createObjectStore("indexStorage", {keyPath : 'key'}) objstore.createIndex "primary_key", "key", unique:true multiEntry:false objstore = db.createObjectStore("preference", {keyPath : 'key'}) objstore.createIndex "primary_key", "key", unique:true multiEntry:false keylist = [] objstore.put({key: "keylist", val: keylist}) reqObj.onsuccess = (event) => @__database = event.target.result resolve(true) reqObj.onerror = (event) => reject(false) #===================================== # Add new kye to keylist #===================================== __addKeylist:(key) -> return new Promise (resolve, reject) => keylist = await @getItem("keylist", "preference") || [] if (keylist.indexOf(key) < 0) keylist.push(key) @setItem("keylist", keylist, "preference").then => resolve(keylist) else resolve(keylist) #===================================== # Remove key from keylist #===================================== __removeKeylist:(key) -> return new Promise (resolve, reject) => keylist = await @getItem("keylist", "preference") || [] index = keylist.indexOf(key) if (index >= 0) keylist.splice(index, 1) await @setItem("keylist", keylist, "preference") resolve(keylist) #=========================================================================== # Global methoc #=========================================================================== #===================================== # Return number of values #===================================== length: -> return new Promise (resolve, reject) => try await @__connectDB() transaction = @__database.transaction(["indexStorage"], "readonly") objectStore = transaction.objectStore("indexStorage") request = objectStore.count() request.onerror = (event) => @__database.close() reject(undefined) request.onsuccess = (event) => len = request.result resolve(len) #===================================== # Return key at index #===================================== key:(index) -> return new Promise (resolve, reject) => try keylist = await @getItem("keylist", "preference") || [] key = keylist[parseInt(index)] resolve(key) catch e reject(undefined) #===================================== # Return value for key #===================================== getItem:(key, storename="indexStorage") -> return new Promise (resolve, reject) => await @__connectDB() transaction = @__database.transaction([storename], "readonly") objectStore = transaction.objectStore(storename) request = objectStore.get(key) request.onerror = (event) => @__database.close() reject(undefined) request.onsuccess = (event) => val = undefined if (request.result? && request.result["key"] == key) val = request.result.val @__database.close() resolve(val) #===================================== # Set value into objectstore #===================================== setItem:(key, val, storename="indexStorage") -> return new Promise (resolve, reject) => await @__connectDB() transaction = @__database.transaction([storename], "readwrite") objectStore = transaction.objectStore(storename) objectStore.put({key: key, val: val}) transaction.onerror = (event) => @__database.close() reject(false) transaction.oncomplete = (event) => if (storename == "indexStorage") ret = await @__addKeylist(key) @__database.close() resolve(true) #===================================== # Remove key from objectstore #===================================== removeItem:(key, storename="indexStorage") -> return new Promise (resolve, reject) => await @__connectDB() transaction = @__database.transaction([storename], "readwrite") objectStore = transaction.objectStore(storename) request = objectStore.delete(key) request.onerror = (event) => @__database.close() reject(false) request.onsuccess = (event) => await @__removeKeylist(key) @__database.close() resolve(true) #===================================== # clear all data #===================================== clear: -> return new Promise (resolve, reject) => ret = await @__clearObjectStore("indexStorage") ret |= await @__clearObjectStore("preference") resolve(ret) #===================================== # database delete #===================================== delete:(database=@__dbname) -> @__indexDBObj.deleteDatabase(database) #===================================== # clear all data in object store #===================================== __clearObjectStore:(storename="indexStorage") -> return new Promise (resolve, reject) => await @__connectDB() transaction = @__database.transaction([storename], "readwrite") objectStore = transaction.objectStore(storename) request = objectStore.clear() request.onerror = (event) => @__database.close() reject(false) request.onsuccess = (event) => @__database.close() resolve(true)
true
#===================================== # IndexedDB wrapper class # Coded by PI:NAME:<NAME>END_PI # 2021.01.24 ver0.0.1 #===================================== class indexStorage constructor:(param) -> # define IndexdDB name if (param?) @node_env = param.NODE_ENV || "" else @node_env = "" # Database version @version = 1 # IndexedDB object initialize @__indexDBObj = undefined @__IDBTransactionObj = undefined @__IDBKeyRangeObj = undefined @__database = undefined if (window.indexedDB) @__indexDBObj = window.indexedDB @__IDBTransactionObj = window.IDBTransaction @__IDBKeyRangeObj = window.IDBKeyRange else # Initialize failure return # Define database name if (@node_env == "develop") # developer environment @__dbname = "__indexstorage_db_develop__" else # Production environment @__dbname = "__indexstorage_db_production__" #=========================================================================== # Private method #=========================================================================== #===================================== # Database initialize #===================================== __connectDB: -> return new Promise (resolve, reject) => # DB接続 reqObj = @__indexDBObj.open(@__dbname, @version) # Update database version reqObj.onupgradeneeded = (event) => db = event.target.result objstore = db.createObjectStore("indexStorage", {keyPath : 'key'}) objstore.createIndex "primary_key", "key", unique:true multiEntry:false objstore = db.createObjectStore("preference", {keyPath : 'key'}) objstore.createIndex "primary_key", "key", unique:true multiEntry:false keylist = [] objstore.put({key: "keylist", val: keylist}) reqObj.onsuccess = (event) => @__database = event.target.result resolve(true) reqObj.onerror = (event) => reject(false) #===================================== # Add new kye to keylist #===================================== __addKeylist:(key) -> return new Promise (resolve, reject) => keylist = await @getItem("keylist", "preference") || [] if (keylist.indexOf(key) < 0) keylist.push(key) @setItem("keylist", keylist, "preference").then => resolve(keylist) else resolve(keylist) #===================================== # Remove key from keylist #===================================== __removeKeylist:(key) -> return new Promise (resolve, reject) => keylist = await @getItem("keylist", "preference") || [] index = keylist.indexOf(key) if (index >= 0) keylist.splice(index, 1) await @setItem("keylist", keylist, "preference") resolve(keylist) #=========================================================================== # Global methoc #=========================================================================== #===================================== # Return number of values #===================================== length: -> return new Promise (resolve, reject) => try await @__connectDB() transaction = @__database.transaction(["indexStorage"], "readonly") objectStore = transaction.objectStore("indexStorage") request = objectStore.count() request.onerror = (event) => @__database.close() reject(undefined) request.onsuccess = (event) => len = request.result resolve(len) #===================================== # Return key at index #===================================== key:(index) -> return new Promise (resolve, reject) => try keylist = await @getItem("keylist", "preference") || [] key = keylist[parseInt(index)] resolve(key) catch e reject(undefined) #===================================== # Return value for key #===================================== getItem:(key, storename="indexStorage") -> return new Promise (resolve, reject) => await @__connectDB() transaction = @__database.transaction([storename], "readonly") objectStore = transaction.objectStore(storename) request = objectStore.get(key) request.onerror = (event) => @__database.close() reject(undefined) request.onsuccess = (event) => val = undefined if (request.result? && request.result["key"] == key) val = request.result.val @__database.close() resolve(val) #===================================== # Set value into objectstore #===================================== setItem:(key, val, storename="indexStorage") -> return new Promise (resolve, reject) => await @__connectDB() transaction = @__database.transaction([storename], "readwrite") objectStore = transaction.objectStore(storename) objectStore.put({key: key, val: val}) transaction.onerror = (event) => @__database.close() reject(false) transaction.oncomplete = (event) => if (storename == "indexStorage") ret = await @__addKeylist(key) @__database.close() resolve(true) #===================================== # Remove key from objectstore #===================================== removeItem:(key, storename="indexStorage") -> return new Promise (resolve, reject) => await @__connectDB() transaction = @__database.transaction([storename], "readwrite") objectStore = transaction.objectStore(storename) request = objectStore.delete(key) request.onerror = (event) => @__database.close() reject(false) request.onsuccess = (event) => await @__removeKeylist(key) @__database.close() resolve(true) #===================================== # clear all data #===================================== clear: -> return new Promise (resolve, reject) => ret = await @__clearObjectStore("indexStorage") ret |= await @__clearObjectStore("preference") resolve(ret) #===================================== # database delete #===================================== delete:(database=@__dbname) -> @__indexDBObj.deleteDatabase(database) #===================================== # clear all data in object store #===================================== __clearObjectStore:(storename="indexStorage") -> return new Promise (resolve, reject) => await @__connectDB() transaction = @__database.transaction([storename], "readwrite") objectStore = transaction.objectStore(storename) request = objectStore.clear() request.onerror = (event) => @__database.close() reject(false) request.onsuccess = (event) => @__database.close() resolve(true)
[ { "context": "\n\n constructor: ->\n super()\n\n for key in ['w', 'a', 's', 'd']\n $.on key, => @check key, '", "end": 98, "score": 0.6262040138244629, "start": 97, "tag": "KEY", "value": "w" }, { "context": "onstructor: ->\n super()\n\n for key in ['w', 'a', 's', 'd']\n $.on key, => @check key, 'down'", "end": 103, "score": 0.7971695065498352, "start": 102, "tag": "KEY", "value": "a" }, { "context": "uctor: ->\n super()\n\n for key in ['w', 'a', 's', 'd']\n $.on key, => @check key, 'down'\n ", "end": 108, "score": 0.6244467496871948, "start": 107, "tag": "KEY", "value": "s" }, { "context": "\n checkMove: ->\n\n count = 0\n\n for key in ['w', 'a', 's', 'd']\n\n if $.getState key\n\n ", "end": 776, "score": 0.5375195741653442, "start": 775, "tag": "KEY", "value": "w" }, { "context": "eckMove: ->\n\n count = 0\n\n for key in ['w', 'a', 's', 'd']\n\n if $.getState key\n\n cou", "end": 781, "score": 0.7098792195320129, "start": 780, "tag": "KEY", "value": "a" }, { "context": "ve: ->\n\n count = 0\n\n for key in ['w', 'a', 's', 'd']\n\n if $.getState key\n\n count = ", "end": 786, "score": 0.5377432703971863, "start": 785, "tag": "KEY", "value": "s" } ]
source/module/movement.coffee
notsanchez/genshin-impact-script
0
class MovementX extends KeyBindingX count: 0 constructor: -> super() for key in ['w', 'a', 's', 'd'] $.on key, => @check key, 'down' $.on "#{key}:up", => @check key, 'up' player .on 'move:start', -> if player.isMoving return player.isMoving = true .on 'move:end', -> unless player.isMoving return player.isMoving = false check: (key, action) -> if action == 'down' and @isPressed[key] return else if action == 'up' and !@isPressed[key] return count = @checkMove() if count and !@count player.emit 'move:start' else if !count and @count player.emit 'move:end' @count = count checkMove: -> count = 0 for key in ['w', 'a', 's', 'd'] if $.getState key count = count + 1 if @isPressed[key] continue @isPressed[key] = true recorder.record "#{key}:down" $.press "#{key}:down" else unless @isPressed[key] continue @isPressed[key] = false recorder.record "#{key}:up" $.press "#{key}:up" return count # execute movement = new MovementX()
89662
class MovementX extends KeyBindingX count: 0 constructor: -> super() for key in ['<KEY>', '<KEY>', '<KEY>', 'd'] $.on key, => @check key, 'down' $.on "#{key}:up", => @check key, 'up' player .on 'move:start', -> if player.isMoving return player.isMoving = true .on 'move:end', -> unless player.isMoving return player.isMoving = false check: (key, action) -> if action == 'down' and @isPressed[key] return else if action == 'up' and !@isPressed[key] return count = @checkMove() if count and !@count player.emit 'move:start' else if !count and @count player.emit 'move:end' @count = count checkMove: -> count = 0 for key in ['<KEY>', '<KEY>', '<KEY>', 'd'] if $.getState key count = count + 1 if @isPressed[key] continue @isPressed[key] = true recorder.record "#{key}:down" $.press "#{key}:down" else unless @isPressed[key] continue @isPressed[key] = false recorder.record "#{key}:up" $.press "#{key}:up" return count # execute movement = new MovementX()
true
class MovementX extends KeyBindingX count: 0 constructor: -> super() for key in ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'd'] $.on key, => @check key, 'down' $.on "#{key}:up", => @check key, 'up' player .on 'move:start', -> if player.isMoving return player.isMoving = true .on 'move:end', -> unless player.isMoving return player.isMoving = false check: (key, action) -> if action == 'down' and @isPressed[key] return else if action == 'up' and !@isPressed[key] return count = @checkMove() if count and !@count player.emit 'move:start' else if !count and @count player.emit 'move:end' @count = count checkMove: -> count = 0 for key in ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'd'] if $.getState key count = count + 1 if @isPressed[key] continue @isPressed[key] = true recorder.record "#{key}:down" $.press "#{key}:down" else unless @isPressed[key] continue @isPressed[key] = false recorder.record "#{key}:up" $.press "#{key}:up" return count # execute movement = new MovementX()
[ { "context": "# jQuery Minical Plugin\n# http://github.com/camerond/jquery-minical\n# version 0.9.4\n#\n# Copyright (c) ", "end": 52, "score": 0.9989273548126221, "start": 44, "tag": "USERNAME", "value": "camerond" }, { "context": "ery-minical\n# version 0.9.4\n#\n# Copyright (c) 2014 Cameron Daigle, http://camerondaigle.com\n#\n# Permission is hereb", "end": 121, "score": 0.9998946785926819, "start": 107, "tag": "NAME", "value": "Cameron Daigle" } ]
wilbur/coffee/minical.coffee
thomasmeagher/Casper
0
# jQuery Minical Plugin # http://github.com/camerond/jquery-minical # version 0.9.4 # # Copyright (c) 2014 Cameron Daigle, http://camerondaigle.com # # 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. date_tools = getMonthName: (date) -> months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] months[date.getMonth()] getDayClass: (date) -> return if !date return "minical_day_" + [date.getMonth() + 1, date.getDate(), date.getFullYear()].join("_") getStartOfCalendarBlock: (date) -> firstOfMonth = new Date(date) firstOfMonth.setDate(1) new Date(firstOfMonth.setDate(1 - firstOfMonth.getDay())) templates = clear_link: -> $("<p />", { class: "minical_clear pull-left" }) .append $("<a />", { href: "#", text: "Clear Date" }) today_link: -> $("<p />", { class: "minical_today pull-right" }) .append $("<a />", { href: "#", text: "Today" }) day: (date) -> $("<td />") .data("minical_date", new Date(date)) .addClass(date_tools.getDayClass(date)) .append($("<a />", {"href": "#"}).text(date.getDate())) dayHeader: -> days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] $tr = $("<tr />") $("<th />").text(day).appendTo($tr) for day in days $tr month: (date) -> $li = $("<li />", class: "minical_#{date_tools.getMonthName(date).toLowerCase()}") $li.html(" <article> <header> <h1>#{date_tools.getMonthName(date)} #{date.getFullYear()}</h1> <a href='#' class='minical_prev'>&lsaquo;</a> <a href='#' class='minical_next'>&rsaquo;</a> </header> <section> <table> <thead> <tr> </tr> </thead> <tbody> </tbody> </table> </section> </article> ") $li.find('thead').append(@dayHeader()) $li minical = offset: x: 0 y: 2 inline: false trigger: null align_to_trigger: true initialize_with_date: true move_on_resize: true read_only: true show_clear_link: false show_today_link: false add_timezone_offset: true appendCalendarTo: -> $('body') date_format: (date) -> [date.getMonth()+1, date.getDate(), date.getFullYear()].join("/") from: null to: null date_changed: $.noop month_drawn: $.noop fireCallback: (name) -> @[name] && @[name].apply(@$el) buildCalendarContainer: -> $cal = $("<ul />", { id: "minical_calendar_#{@id}", class: "minical" }) .data("minical", @) if @inline $cal.addClass('minical-inline').insertAfter(@$el) else $cal.appendTo(@appendCalendarTo.apply(@$el)) render: (date) -> date ?= @selected_day $li = templates.month(date) if @show_clear_link || !@initialize_with_date templates.clear_link().insertAfter($li.find("table")) if @show_today_link || !@initialize_with_date templates.today_link().insertAfter($li.find("table")) current_date = date_tools.getStartOfCalendarBlock(date) $li.find(".minical_prev").detach() if @from and @from > current_date for w in [1..6] $tr = $("<tr />") for d in [1..7] $tr.append(@renderDay(current_date, date)) current_date.setDate(current_date.getDate() + 1) $tr.appendTo($li.find('tbody')) if $tr.find('.minical_day').length $li.find(".#{date_tools.getDayClass(new Date())}").addClass("minical_today_date") $li.find(".minical_next").detach() if @to and @to <= new Date($li.find("td").last().data("minical_date")) @$cal.empty().append($li) @markSelectedDay() @fireCallback('month_drawn') @$cal renderDay: (d, base_date) -> $td = templates.day(d) current_month = d.getMonth() month = base_date.getMonth() $td.addClass("minical_disabled") if (@from and d < @from) or (@to and d > @to) if current_month > month || current_month == 0 and month == 11 $td.addClass("minical_future_month") else if current_month < month $td.addClass("minical_past_month") else $td.addClass("minical_day") highlightDay: (date) -> $td = @$cal.find(".#{date_tools.getDayClass(date)}") return if $td.hasClass("minical_disabled") return if @to and date > @to return if @from and date < @from if !$td.length @render(date) @highlightDay(date) return klass = "minical_highlighted" @$cal.find(".#{klass}").removeClass(klass) $td.addClass(klass) selectDay: (date, external) -> event_name = if external then 'change.minical_external' else 'change.minical' @selected_day = date @markSelectedDay() @$el.val(if date then @date_format(@selected_day) else '').trigger(event_name) @fireCallback('date_changed') markSelectedDay: -> klass = 'minical_selected' @$cal.find('td').removeClass(klass) @$cal.find(".#{date_tools.getDayClass(@selected_day)}").addClass(klass) moveToDay: (x, y) -> $selected = @$cal.find(".minical_highlighted") if !$selected.length then $selected = @$cal.find(".minical_day").eq(0) move_from = $selected.data("minical_date") move_to = new Date(move_from) move_to.setDate(move_from.getDate() + x + y * 7) @highlightDay(move_to) false positionCalendar: -> if @inline then return @$cal offset = if @align_to_trigger then @$trigger[@offset_method]() else @$el[@offset_method]() height = if @align_to_trigger then @$trigger.outerHeight() else @$el.outerHeight() position = left: "#{offset.left + @offset.x}px", top: "#{height + offset.top + @offset.y}px" @$cal.css(position) overlap = @$cal.width() + @$cal[@offset_method]().left - $(window).width() if overlap > 0 @$cal.css("left", offset.left - overlap - 10) @$cal clickDay: (e) -> $td = $(e.target).closest('td') return false if $td.hasClass("minical_disabled") @selectDay($td.data('minical_date')) @$cal.trigger('hide.minical') false hoverDay: (e) -> @highlightDay($(e.target).closest("td").data('minical_date')) hoverOutDay: (e) -> @$cal.find('.minical_highlighted').removeClass('minical_highlighted') nextMonth: (e) -> next = new Date(@$cal.find(".minical_day").eq(0).data("minical_date")) next.setMonth(next.getMonth() + 1) @render(next) false prevMonth: (e) -> prev = new Date(@$cal.find(".minical_day").eq(0).data("minical_date")) prev.setMonth(prev.getMonth() - 1) @render(prev) false showCalendar: (e) -> $(".minical").not(@$cal).trigger('hide.minical') return if @$cal.is(":visible") or @$el.is(":disabled") @highlightDay(@selected_day || @detectInitialDate()) @positionCalendar().show() @attachCalendarEvents() e && e.preventDefault() hideCalendar: (e) -> return if @inline @$cal.hide() @detachCalendarEvents() false attachCalendarEvents: -> return if @inline @detachCalendarEvents() $(document) .on("keydown.minical_#{@id}", $.proxy(@keydown, @)) .on("click.minical_#{@id} touchend.minical_#{@id}", $.proxy(@outsideClick, @)) if @move_on_resize $(window).on("resize.minical_#{@id}", $.proxy(@positionCalendar, @)) detachCalendarEvents: -> $(document) .off("keydown.minical_#{@id}") .off("click.minical_#{@id} touchend.minical_#{@id}") $(window).off("resize.minical_#{@id}") keydown: (e) -> key = e.which mc = @ keys = 9: -> true # tab 13: -> # enter mc.$cal.find(".minical_highlighted a").click() false 37: -> mc.moveToDay(-1, 0) # left 38: -> mc.moveToDay(0, -1) # up 39: -> mc.moveToDay(1, 0) # right 40: -> mc.moveToDay(0, 1) # down @checkToHideCalendar() if keys[key] keys[key]() else if !e.metaKey and !e.ctrlKey !mc.read_only outsideClick: (e) -> $t = $(e.target) @$last_clicked = $t if $t.parent().is(".minical_clear") @$el.minical('clear') return false if $t.parent().is(".minical_today") @$el.minical('today') return false return true if $t.is(@$el) or $t.is(@$trigger) or $t.closest(".minical").length @$cal.trigger('hide.minical') checkToHideCalendar: -> mc = @ setTimeout( -> if !mc.$el.add(mc.$trigger).is(":focus") then mc.$cal.trigger("hide.minical") , 50) initTrigger: -> if $.isFunction(@trigger) @$trigger = $.proxy(@trigger, @$el)() else @$trigger = @$el.find(@trigger) @$trigger = @$el.parent().find(@trigger) if !@$trigger.length if @$trigger.length @$trigger .data("minical", @) .on("focus.minical click.minical", => @$cal.trigger('show.minical')) else @$trigger = $.noop @align_to_trigger = false detectDataAttributeOptions: -> for range in ['from', 'to'] attr = @$el.attr("data-minical-#{range}") if attr and /^\d+$/.test(attr) then @[range] = new Date(+attr) detectInitialDate: -> initial_date = @$el.attr("data-minical-initial") || @$el.val() millis = if /^\d+$/.test(initial_date) initial_date else if initial_date Date.parse(initial_date) else @add_timezone_offset = false new Date().getTime() millis = parseInt(millis) + if @add_timezone_offset then (new Date().getTimezoneOffset() * 60 * 1000) else 0 new Date(millis) external: clear: -> mc = @data('minical') @trigger('hide.minical') mc.selectDay(false) destroy: -> mc = @data('minical') @trigger('hide.minical') mc.$cal.remove() mc.$el .removeClass('minical_input') .removeData('minical') select: (date) -> @data('minical').selectDay(date, true) today: -> mc = @data('minical') today = new Date @trigger('hide.minical') mc.selectDay(today, true) init: -> @id = $(".minical").length mc = @ @detectDataAttributeOptions() @$cal = @buildCalendarContainer() @selectDay(@detectInitialDate()) unless !@$el.val() && !@initialize_with_date @offset_method = if @$cal.parent().is("body") then "offset" else "position" @initTrigger() @$el.addClass("minical_input") @$cal .on("click.minical", "td a", $.proxy(@clickDay, @)) .on("mouseenter.minical", "td a", $.proxy(@hoverDay, @)) .on("mouseleave.minical", $.proxy(@hoverOutDay, @)) .on("click.minical", "a.minical_next", $.proxy(@nextMonth, @)) .on("click.minical", "a.minical_prev", $.proxy(@prevMonth, @)) if @inline @showCalendar() else @$el .on("focus.minical click.minical", => @$cal.trigger('show.minical')) .on("hide.minical", $.proxy(@hideCalendar, @)) @$cal .on("hide.minical", $.proxy(@hideCalendar, @)) .on("show.minical", $.proxy(@showCalendar, @)) $.fn.minical = (opts) -> $els = @ if opts and minical.external[opts] minical.external[opts].apply($els, Array.prototype.slice.call(arguments, 1)) else $els.each -> $e = $(@) mc = $.extend(true, { $el: $e }, minical, opts) $e.data("minical", mc) mc.init()
151984
# jQuery Minical Plugin # http://github.com/camerond/jquery-minical # version 0.9.4 # # Copyright (c) 2014 <NAME>, http://camerondaigle.com # # 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. date_tools = getMonthName: (date) -> months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] months[date.getMonth()] getDayClass: (date) -> return if !date return "minical_day_" + [date.getMonth() + 1, date.getDate(), date.getFullYear()].join("_") getStartOfCalendarBlock: (date) -> firstOfMonth = new Date(date) firstOfMonth.setDate(1) new Date(firstOfMonth.setDate(1 - firstOfMonth.getDay())) templates = clear_link: -> $("<p />", { class: "minical_clear pull-left" }) .append $("<a />", { href: "#", text: "Clear Date" }) today_link: -> $("<p />", { class: "minical_today pull-right" }) .append $("<a />", { href: "#", text: "Today" }) day: (date) -> $("<td />") .data("minical_date", new Date(date)) .addClass(date_tools.getDayClass(date)) .append($("<a />", {"href": "#"}).text(date.getDate())) dayHeader: -> days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] $tr = $("<tr />") $("<th />").text(day).appendTo($tr) for day in days $tr month: (date) -> $li = $("<li />", class: "minical_#{date_tools.getMonthName(date).toLowerCase()}") $li.html(" <article> <header> <h1>#{date_tools.getMonthName(date)} #{date.getFullYear()}</h1> <a href='#' class='minical_prev'>&lsaquo;</a> <a href='#' class='minical_next'>&rsaquo;</a> </header> <section> <table> <thead> <tr> </tr> </thead> <tbody> </tbody> </table> </section> </article> ") $li.find('thead').append(@dayHeader()) $li minical = offset: x: 0 y: 2 inline: false trigger: null align_to_trigger: true initialize_with_date: true move_on_resize: true read_only: true show_clear_link: false show_today_link: false add_timezone_offset: true appendCalendarTo: -> $('body') date_format: (date) -> [date.getMonth()+1, date.getDate(), date.getFullYear()].join("/") from: null to: null date_changed: $.noop month_drawn: $.noop fireCallback: (name) -> @[name] && @[name].apply(@$el) buildCalendarContainer: -> $cal = $("<ul />", { id: "minical_calendar_#{@id}", class: "minical" }) .data("minical", @) if @inline $cal.addClass('minical-inline').insertAfter(@$el) else $cal.appendTo(@appendCalendarTo.apply(@$el)) render: (date) -> date ?= @selected_day $li = templates.month(date) if @show_clear_link || !@initialize_with_date templates.clear_link().insertAfter($li.find("table")) if @show_today_link || !@initialize_with_date templates.today_link().insertAfter($li.find("table")) current_date = date_tools.getStartOfCalendarBlock(date) $li.find(".minical_prev").detach() if @from and @from > current_date for w in [1..6] $tr = $("<tr />") for d in [1..7] $tr.append(@renderDay(current_date, date)) current_date.setDate(current_date.getDate() + 1) $tr.appendTo($li.find('tbody')) if $tr.find('.minical_day').length $li.find(".#{date_tools.getDayClass(new Date())}").addClass("minical_today_date") $li.find(".minical_next").detach() if @to and @to <= new Date($li.find("td").last().data("minical_date")) @$cal.empty().append($li) @markSelectedDay() @fireCallback('month_drawn') @$cal renderDay: (d, base_date) -> $td = templates.day(d) current_month = d.getMonth() month = base_date.getMonth() $td.addClass("minical_disabled") if (@from and d < @from) or (@to and d > @to) if current_month > month || current_month == 0 and month == 11 $td.addClass("minical_future_month") else if current_month < month $td.addClass("minical_past_month") else $td.addClass("minical_day") highlightDay: (date) -> $td = @$cal.find(".#{date_tools.getDayClass(date)}") return if $td.hasClass("minical_disabled") return if @to and date > @to return if @from and date < @from if !$td.length @render(date) @highlightDay(date) return klass = "minical_highlighted" @$cal.find(".#{klass}").removeClass(klass) $td.addClass(klass) selectDay: (date, external) -> event_name = if external then 'change.minical_external' else 'change.minical' @selected_day = date @markSelectedDay() @$el.val(if date then @date_format(@selected_day) else '').trigger(event_name) @fireCallback('date_changed') markSelectedDay: -> klass = 'minical_selected' @$cal.find('td').removeClass(klass) @$cal.find(".#{date_tools.getDayClass(@selected_day)}").addClass(klass) moveToDay: (x, y) -> $selected = @$cal.find(".minical_highlighted") if !$selected.length then $selected = @$cal.find(".minical_day").eq(0) move_from = $selected.data("minical_date") move_to = new Date(move_from) move_to.setDate(move_from.getDate() + x + y * 7) @highlightDay(move_to) false positionCalendar: -> if @inline then return @$cal offset = if @align_to_trigger then @$trigger[@offset_method]() else @$el[@offset_method]() height = if @align_to_trigger then @$trigger.outerHeight() else @$el.outerHeight() position = left: "#{offset.left + @offset.x}px", top: "#{height + offset.top + @offset.y}px" @$cal.css(position) overlap = @$cal.width() + @$cal[@offset_method]().left - $(window).width() if overlap > 0 @$cal.css("left", offset.left - overlap - 10) @$cal clickDay: (e) -> $td = $(e.target).closest('td') return false if $td.hasClass("minical_disabled") @selectDay($td.data('minical_date')) @$cal.trigger('hide.minical') false hoverDay: (e) -> @highlightDay($(e.target).closest("td").data('minical_date')) hoverOutDay: (e) -> @$cal.find('.minical_highlighted').removeClass('minical_highlighted') nextMonth: (e) -> next = new Date(@$cal.find(".minical_day").eq(0).data("minical_date")) next.setMonth(next.getMonth() + 1) @render(next) false prevMonth: (e) -> prev = new Date(@$cal.find(".minical_day").eq(0).data("minical_date")) prev.setMonth(prev.getMonth() - 1) @render(prev) false showCalendar: (e) -> $(".minical").not(@$cal).trigger('hide.minical') return if @$cal.is(":visible") or @$el.is(":disabled") @highlightDay(@selected_day || @detectInitialDate()) @positionCalendar().show() @attachCalendarEvents() e && e.preventDefault() hideCalendar: (e) -> return if @inline @$cal.hide() @detachCalendarEvents() false attachCalendarEvents: -> return if @inline @detachCalendarEvents() $(document) .on("keydown.minical_#{@id}", $.proxy(@keydown, @)) .on("click.minical_#{@id} touchend.minical_#{@id}", $.proxy(@outsideClick, @)) if @move_on_resize $(window).on("resize.minical_#{@id}", $.proxy(@positionCalendar, @)) detachCalendarEvents: -> $(document) .off("keydown.minical_#{@id}") .off("click.minical_#{@id} touchend.minical_#{@id}") $(window).off("resize.minical_#{@id}") keydown: (e) -> key = e.which mc = @ keys = 9: -> true # tab 13: -> # enter mc.$cal.find(".minical_highlighted a").click() false 37: -> mc.moveToDay(-1, 0) # left 38: -> mc.moveToDay(0, -1) # up 39: -> mc.moveToDay(1, 0) # right 40: -> mc.moveToDay(0, 1) # down @checkToHideCalendar() if keys[key] keys[key]() else if !e.metaKey and !e.ctrlKey !mc.read_only outsideClick: (e) -> $t = $(e.target) @$last_clicked = $t if $t.parent().is(".minical_clear") @$el.minical('clear') return false if $t.parent().is(".minical_today") @$el.minical('today') return false return true if $t.is(@$el) or $t.is(@$trigger) or $t.closest(".minical").length @$cal.trigger('hide.minical') checkToHideCalendar: -> mc = @ setTimeout( -> if !mc.$el.add(mc.$trigger).is(":focus") then mc.$cal.trigger("hide.minical") , 50) initTrigger: -> if $.isFunction(@trigger) @$trigger = $.proxy(@trigger, @$el)() else @$trigger = @$el.find(@trigger) @$trigger = @$el.parent().find(@trigger) if !@$trigger.length if @$trigger.length @$trigger .data("minical", @) .on("focus.minical click.minical", => @$cal.trigger('show.minical')) else @$trigger = $.noop @align_to_trigger = false detectDataAttributeOptions: -> for range in ['from', 'to'] attr = @$el.attr("data-minical-#{range}") if attr and /^\d+$/.test(attr) then @[range] = new Date(+attr) detectInitialDate: -> initial_date = @$el.attr("data-minical-initial") || @$el.val() millis = if /^\d+$/.test(initial_date) initial_date else if initial_date Date.parse(initial_date) else @add_timezone_offset = false new Date().getTime() millis = parseInt(millis) + if @add_timezone_offset then (new Date().getTimezoneOffset() * 60 * 1000) else 0 new Date(millis) external: clear: -> mc = @data('minical') @trigger('hide.minical') mc.selectDay(false) destroy: -> mc = @data('minical') @trigger('hide.minical') mc.$cal.remove() mc.$el .removeClass('minical_input') .removeData('minical') select: (date) -> @data('minical').selectDay(date, true) today: -> mc = @data('minical') today = new Date @trigger('hide.minical') mc.selectDay(today, true) init: -> @id = $(".minical").length mc = @ @detectDataAttributeOptions() @$cal = @buildCalendarContainer() @selectDay(@detectInitialDate()) unless !@$el.val() && !@initialize_with_date @offset_method = if @$cal.parent().is("body") then "offset" else "position" @initTrigger() @$el.addClass("minical_input") @$cal .on("click.minical", "td a", $.proxy(@clickDay, @)) .on("mouseenter.minical", "td a", $.proxy(@hoverDay, @)) .on("mouseleave.minical", $.proxy(@hoverOutDay, @)) .on("click.minical", "a.minical_next", $.proxy(@nextMonth, @)) .on("click.minical", "a.minical_prev", $.proxy(@prevMonth, @)) if @inline @showCalendar() else @$el .on("focus.minical click.minical", => @$cal.trigger('show.minical')) .on("hide.minical", $.proxy(@hideCalendar, @)) @$cal .on("hide.minical", $.proxy(@hideCalendar, @)) .on("show.minical", $.proxy(@showCalendar, @)) $.fn.minical = (opts) -> $els = @ if opts and minical.external[opts] minical.external[opts].apply($els, Array.prototype.slice.call(arguments, 1)) else $els.each -> $e = $(@) mc = $.extend(true, { $el: $e }, minical, opts) $e.data("minical", mc) mc.init()
true
# jQuery Minical Plugin # http://github.com/camerond/jquery-minical # version 0.9.4 # # Copyright (c) 2014 PI:NAME:<NAME>END_PI, http://camerondaigle.com # # 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. date_tools = getMonthName: (date) -> months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] months[date.getMonth()] getDayClass: (date) -> return if !date return "minical_day_" + [date.getMonth() + 1, date.getDate(), date.getFullYear()].join("_") getStartOfCalendarBlock: (date) -> firstOfMonth = new Date(date) firstOfMonth.setDate(1) new Date(firstOfMonth.setDate(1 - firstOfMonth.getDay())) templates = clear_link: -> $("<p />", { class: "minical_clear pull-left" }) .append $("<a />", { href: "#", text: "Clear Date" }) today_link: -> $("<p />", { class: "minical_today pull-right" }) .append $("<a />", { href: "#", text: "Today" }) day: (date) -> $("<td />") .data("minical_date", new Date(date)) .addClass(date_tools.getDayClass(date)) .append($("<a />", {"href": "#"}).text(date.getDate())) dayHeader: -> days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] $tr = $("<tr />") $("<th />").text(day).appendTo($tr) for day in days $tr month: (date) -> $li = $("<li />", class: "minical_#{date_tools.getMonthName(date).toLowerCase()}") $li.html(" <article> <header> <h1>#{date_tools.getMonthName(date)} #{date.getFullYear()}</h1> <a href='#' class='minical_prev'>&lsaquo;</a> <a href='#' class='minical_next'>&rsaquo;</a> </header> <section> <table> <thead> <tr> </tr> </thead> <tbody> </tbody> </table> </section> </article> ") $li.find('thead').append(@dayHeader()) $li minical = offset: x: 0 y: 2 inline: false trigger: null align_to_trigger: true initialize_with_date: true move_on_resize: true read_only: true show_clear_link: false show_today_link: false add_timezone_offset: true appendCalendarTo: -> $('body') date_format: (date) -> [date.getMonth()+1, date.getDate(), date.getFullYear()].join("/") from: null to: null date_changed: $.noop month_drawn: $.noop fireCallback: (name) -> @[name] && @[name].apply(@$el) buildCalendarContainer: -> $cal = $("<ul />", { id: "minical_calendar_#{@id}", class: "minical" }) .data("minical", @) if @inline $cal.addClass('minical-inline').insertAfter(@$el) else $cal.appendTo(@appendCalendarTo.apply(@$el)) render: (date) -> date ?= @selected_day $li = templates.month(date) if @show_clear_link || !@initialize_with_date templates.clear_link().insertAfter($li.find("table")) if @show_today_link || !@initialize_with_date templates.today_link().insertAfter($li.find("table")) current_date = date_tools.getStartOfCalendarBlock(date) $li.find(".minical_prev").detach() if @from and @from > current_date for w in [1..6] $tr = $("<tr />") for d in [1..7] $tr.append(@renderDay(current_date, date)) current_date.setDate(current_date.getDate() + 1) $tr.appendTo($li.find('tbody')) if $tr.find('.minical_day').length $li.find(".#{date_tools.getDayClass(new Date())}").addClass("minical_today_date") $li.find(".minical_next").detach() if @to and @to <= new Date($li.find("td").last().data("minical_date")) @$cal.empty().append($li) @markSelectedDay() @fireCallback('month_drawn') @$cal renderDay: (d, base_date) -> $td = templates.day(d) current_month = d.getMonth() month = base_date.getMonth() $td.addClass("minical_disabled") if (@from and d < @from) or (@to and d > @to) if current_month > month || current_month == 0 and month == 11 $td.addClass("minical_future_month") else if current_month < month $td.addClass("minical_past_month") else $td.addClass("minical_day") highlightDay: (date) -> $td = @$cal.find(".#{date_tools.getDayClass(date)}") return if $td.hasClass("minical_disabled") return if @to and date > @to return if @from and date < @from if !$td.length @render(date) @highlightDay(date) return klass = "minical_highlighted" @$cal.find(".#{klass}").removeClass(klass) $td.addClass(klass) selectDay: (date, external) -> event_name = if external then 'change.minical_external' else 'change.minical' @selected_day = date @markSelectedDay() @$el.val(if date then @date_format(@selected_day) else '').trigger(event_name) @fireCallback('date_changed') markSelectedDay: -> klass = 'minical_selected' @$cal.find('td').removeClass(klass) @$cal.find(".#{date_tools.getDayClass(@selected_day)}").addClass(klass) moveToDay: (x, y) -> $selected = @$cal.find(".minical_highlighted") if !$selected.length then $selected = @$cal.find(".minical_day").eq(0) move_from = $selected.data("minical_date") move_to = new Date(move_from) move_to.setDate(move_from.getDate() + x + y * 7) @highlightDay(move_to) false positionCalendar: -> if @inline then return @$cal offset = if @align_to_trigger then @$trigger[@offset_method]() else @$el[@offset_method]() height = if @align_to_trigger then @$trigger.outerHeight() else @$el.outerHeight() position = left: "#{offset.left + @offset.x}px", top: "#{height + offset.top + @offset.y}px" @$cal.css(position) overlap = @$cal.width() + @$cal[@offset_method]().left - $(window).width() if overlap > 0 @$cal.css("left", offset.left - overlap - 10) @$cal clickDay: (e) -> $td = $(e.target).closest('td') return false if $td.hasClass("minical_disabled") @selectDay($td.data('minical_date')) @$cal.trigger('hide.minical') false hoverDay: (e) -> @highlightDay($(e.target).closest("td").data('minical_date')) hoverOutDay: (e) -> @$cal.find('.minical_highlighted').removeClass('minical_highlighted') nextMonth: (e) -> next = new Date(@$cal.find(".minical_day").eq(0).data("minical_date")) next.setMonth(next.getMonth() + 1) @render(next) false prevMonth: (e) -> prev = new Date(@$cal.find(".minical_day").eq(0).data("minical_date")) prev.setMonth(prev.getMonth() - 1) @render(prev) false showCalendar: (e) -> $(".minical").not(@$cal).trigger('hide.minical') return if @$cal.is(":visible") or @$el.is(":disabled") @highlightDay(@selected_day || @detectInitialDate()) @positionCalendar().show() @attachCalendarEvents() e && e.preventDefault() hideCalendar: (e) -> return if @inline @$cal.hide() @detachCalendarEvents() false attachCalendarEvents: -> return if @inline @detachCalendarEvents() $(document) .on("keydown.minical_#{@id}", $.proxy(@keydown, @)) .on("click.minical_#{@id} touchend.minical_#{@id}", $.proxy(@outsideClick, @)) if @move_on_resize $(window).on("resize.minical_#{@id}", $.proxy(@positionCalendar, @)) detachCalendarEvents: -> $(document) .off("keydown.minical_#{@id}") .off("click.minical_#{@id} touchend.minical_#{@id}") $(window).off("resize.minical_#{@id}") keydown: (e) -> key = e.which mc = @ keys = 9: -> true # tab 13: -> # enter mc.$cal.find(".minical_highlighted a").click() false 37: -> mc.moveToDay(-1, 0) # left 38: -> mc.moveToDay(0, -1) # up 39: -> mc.moveToDay(1, 0) # right 40: -> mc.moveToDay(0, 1) # down @checkToHideCalendar() if keys[key] keys[key]() else if !e.metaKey and !e.ctrlKey !mc.read_only outsideClick: (e) -> $t = $(e.target) @$last_clicked = $t if $t.parent().is(".minical_clear") @$el.minical('clear') return false if $t.parent().is(".minical_today") @$el.minical('today') return false return true if $t.is(@$el) or $t.is(@$trigger) or $t.closest(".minical").length @$cal.trigger('hide.minical') checkToHideCalendar: -> mc = @ setTimeout( -> if !mc.$el.add(mc.$trigger).is(":focus") then mc.$cal.trigger("hide.minical") , 50) initTrigger: -> if $.isFunction(@trigger) @$trigger = $.proxy(@trigger, @$el)() else @$trigger = @$el.find(@trigger) @$trigger = @$el.parent().find(@trigger) if !@$trigger.length if @$trigger.length @$trigger .data("minical", @) .on("focus.minical click.minical", => @$cal.trigger('show.minical')) else @$trigger = $.noop @align_to_trigger = false detectDataAttributeOptions: -> for range in ['from', 'to'] attr = @$el.attr("data-minical-#{range}") if attr and /^\d+$/.test(attr) then @[range] = new Date(+attr) detectInitialDate: -> initial_date = @$el.attr("data-minical-initial") || @$el.val() millis = if /^\d+$/.test(initial_date) initial_date else if initial_date Date.parse(initial_date) else @add_timezone_offset = false new Date().getTime() millis = parseInt(millis) + if @add_timezone_offset then (new Date().getTimezoneOffset() * 60 * 1000) else 0 new Date(millis) external: clear: -> mc = @data('minical') @trigger('hide.minical') mc.selectDay(false) destroy: -> mc = @data('minical') @trigger('hide.minical') mc.$cal.remove() mc.$el .removeClass('minical_input') .removeData('minical') select: (date) -> @data('minical').selectDay(date, true) today: -> mc = @data('minical') today = new Date @trigger('hide.minical') mc.selectDay(today, true) init: -> @id = $(".minical").length mc = @ @detectDataAttributeOptions() @$cal = @buildCalendarContainer() @selectDay(@detectInitialDate()) unless !@$el.val() && !@initialize_with_date @offset_method = if @$cal.parent().is("body") then "offset" else "position" @initTrigger() @$el.addClass("minical_input") @$cal .on("click.minical", "td a", $.proxy(@clickDay, @)) .on("mouseenter.minical", "td a", $.proxy(@hoverDay, @)) .on("mouseleave.minical", $.proxy(@hoverOutDay, @)) .on("click.minical", "a.minical_next", $.proxy(@nextMonth, @)) .on("click.minical", "a.minical_prev", $.proxy(@prevMonth, @)) if @inline @showCalendar() else @$el .on("focus.minical click.minical", => @$cal.trigger('show.minical')) .on("hide.minical", $.proxy(@hideCalendar, @)) @$cal .on("hide.minical", $.proxy(@hideCalendar, @)) .on("show.minical", $.proxy(@showCalendar, @)) $.fn.minical = (opts) -> $els = @ if opts and minical.external[opts] minical.external[opts].apply($els, Array.prototype.slice.call(arguments, 1)) else $els.each -> $e = $(@) mc = $.extend(true, { $el: $e }, minical, opts) $e.data("minical", mc) mc.init()
[ { "context": "ispatch('websocket_rails.channel_token', {token: 'abc123'})\n expect(@channel._token).toEqual 'abc123'", "end": 3102, "score": 0.8223152756690979, "start": 3096, "tag": "KEY", "value": "abc123" }, { "context": "'abc123'})\n expect(@channel._token).toEqual 'abc123'\n\n it \"should refresh channel's connection_i", "end": 3149, "score": 0.8504019975662231, "start": 3145, "tag": "KEY", "value": "abc1" }, { "context": "123'})\n expect(@channel._token).toEqual 'abc123'\n\n it \"should refresh channel's connection_id", "end": 3150, "score": 0.4945102334022522, "start": 3149, "tag": "PASSWORD", "value": "2" }, { "context": "23'})\n expect(@channel._token).toEqual 'abc123'\n\n it \"should refresh channel's connection_id ", "end": 3151, "score": 0.6222734451293945, "start": 3150, "tag": "KEY", "value": "3" }, { "context": "ispatch('websocket_rails.channel_token', {token: 'abc123'})\n expect(@channel.connection_id).toEqual @", "end": 3476, "score": 0.8056324124336243, "start": 3470, "tag": "KEY", "value": "abc123" }, { "context": "ispatch('websocket_rails.channel_token', {token: 'abc123'})\n expect(@channel._queue.length).toEqual(0", "end": 3739, "score": 0.8802766799926758, "start": 3733, "tag": "KEY", "value": "abc123" } ]
spec/javascripts/websocket_rails/channel_spec.coffee
ryanoboril/websocket-rails
943
describe 'WebSocketRails.Channel:', -> beforeEach -> @dispatcher = new class WebSocketRailsStub new_message: -> true dispatch: -> true trigger_event: (event) -> true state: 'connected' _conn: connection_id: 12345 @channel = new WebSocketRails.Channel('public', @dispatcher) sinon.spy @dispatcher, 'trigger_event' afterEach -> @dispatcher.trigger_event.restore() describe '.bind', -> it 'should add a function to the callbacks collection', -> test_func = -> @channel.bind 'event_name', test_func expect(@channel._callbacks['event_name'].length).toBe 1 expect(@channel._callbacks['event_name']).toContain test_func describe '.unbind', -> it 'should remove the callbacks of an event', -> callback = -> @channel.bind 'event', callback @channel.unbind 'event' expect(@channel._callbacks['event']).toBeUndefined() describe '.trigger', -> describe 'before the channel token is set', -> it 'queues the events', -> @channel.trigger 'someEvent', 'someData' queue = @channel._queue expect(queue[0].name).toEqual 'someEvent' expect(queue[0].data).toEqual 'someData' describe 'when channel token is set', -> it 'adds token to event metadata and dispatches event', -> @channel._token = 'valid token' @channel.trigger 'someEvent', 'someData' expect(@dispatcher.trigger_event.calledWith(['someEvent',{token: 'valid token', data: 'someData'}])) describe '.destroy', -> it 'should destroy all callbacks', -> event_callback = -> true @channel.bind('new_message', @event_callback) @channel.destroy() expect(@channel._callbacks).toEqual {} describe 'when this channel\'s connection is still active', -> it 'should send unsubscribe event', -> @channel.destroy() expect(@dispatcher.trigger_event.args[0][0].name).toEqual 'websocket_rails.unsubscribe' describe 'when this channel\'s connection is no more active', -> beforeEach -> @dispatcher._conn.connection_id++ it 'should not send unsubscribe event', -> @channel.destroy() expect(@dispatcher.trigger_event.notCalled).toEqual true describe 'public channels', -> beforeEach -> @channel = new WebSocketRails.Channel('forchan', @dispatcher, false) @event = @dispatcher.trigger_event.lastCall.args[0] it 'should trigger an event containing the channel name', -> expect(@event.data.channel).toEqual 'forchan' it 'should trigger an event containing the correct connection_id', -> expect(@event.connection_id).toEqual 12345 it 'should initialize an empty callbacks property', -> expect(@channel._callbacks).toBeDefined() expect(@channel._callbacks).toEqual {} it 'should be public', -> expect(@channel.is_private).toBeFalsy describe 'channel tokens', -> it 'should set token when event_name is websocket_rails.channel_token', -> @channel.dispatch('websocket_rails.channel_token', {token: 'abc123'}) expect(@channel._token).toEqual 'abc123' it "should refresh channel's connection_id after channel_token has been received", -> # this is needed in case we would init the channel connection # just before the connection has been established @channel.connection_id = null @channel.dispatch('websocket_rails.channel_token', {token: 'abc123'}) expect(@channel.connection_id).toEqual @dispatcher._conn.connection_id it 'should flush the event queue after setting token', -> @channel.trigger 'someEvent', 'someData' @channel.dispatch('websocket_rails.channel_token', {token: 'abc123'}) expect(@channel._queue.length).toEqual(0) describe 'private channels', -> beforeEach -> @channel = new WebSocketRails.Channel('forchan', @dispatcher, true) @event = @dispatcher.trigger_event.lastCall.args[0] it 'should trigger a subscribe_private event when created', -> expect(@event.name).toEqual 'websocket_rails.subscribe_private' it 'should be private', -> expect(@channel.is_private).toBeTruthy
8548
describe 'WebSocketRails.Channel:', -> beforeEach -> @dispatcher = new class WebSocketRailsStub new_message: -> true dispatch: -> true trigger_event: (event) -> true state: 'connected' _conn: connection_id: 12345 @channel = new WebSocketRails.Channel('public', @dispatcher) sinon.spy @dispatcher, 'trigger_event' afterEach -> @dispatcher.trigger_event.restore() describe '.bind', -> it 'should add a function to the callbacks collection', -> test_func = -> @channel.bind 'event_name', test_func expect(@channel._callbacks['event_name'].length).toBe 1 expect(@channel._callbacks['event_name']).toContain test_func describe '.unbind', -> it 'should remove the callbacks of an event', -> callback = -> @channel.bind 'event', callback @channel.unbind 'event' expect(@channel._callbacks['event']).toBeUndefined() describe '.trigger', -> describe 'before the channel token is set', -> it 'queues the events', -> @channel.trigger 'someEvent', 'someData' queue = @channel._queue expect(queue[0].name).toEqual 'someEvent' expect(queue[0].data).toEqual 'someData' describe 'when channel token is set', -> it 'adds token to event metadata and dispatches event', -> @channel._token = 'valid token' @channel.trigger 'someEvent', 'someData' expect(@dispatcher.trigger_event.calledWith(['someEvent',{token: 'valid token', data: 'someData'}])) describe '.destroy', -> it 'should destroy all callbacks', -> event_callback = -> true @channel.bind('new_message', @event_callback) @channel.destroy() expect(@channel._callbacks).toEqual {} describe 'when this channel\'s connection is still active', -> it 'should send unsubscribe event', -> @channel.destroy() expect(@dispatcher.trigger_event.args[0][0].name).toEqual 'websocket_rails.unsubscribe' describe 'when this channel\'s connection is no more active', -> beforeEach -> @dispatcher._conn.connection_id++ it 'should not send unsubscribe event', -> @channel.destroy() expect(@dispatcher.trigger_event.notCalled).toEqual true describe 'public channels', -> beforeEach -> @channel = new WebSocketRails.Channel('forchan', @dispatcher, false) @event = @dispatcher.trigger_event.lastCall.args[0] it 'should trigger an event containing the channel name', -> expect(@event.data.channel).toEqual 'forchan' it 'should trigger an event containing the correct connection_id', -> expect(@event.connection_id).toEqual 12345 it 'should initialize an empty callbacks property', -> expect(@channel._callbacks).toBeDefined() expect(@channel._callbacks).toEqual {} it 'should be public', -> expect(@channel.is_private).toBeFalsy describe 'channel tokens', -> it 'should set token when event_name is websocket_rails.channel_token', -> @channel.dispatch('websocket_rails.channel_token', {token: '<KEY>'}) expect(@channel._token).toEqual '<KEY> <PASSWORD> <KEY>' it "should refresh channel's connection_id after channel_token has been received", -> # this is needed in case we would init the channel connection # just before the connection has been established @channel.connection_id = null @channel.dispatch('websocket_rails.channel_token', {token: '<KEY>'}) expect(@channel.connection_id).toEqual @dispatcher._conn.connection_id it 'should flush the event queue after setting token', -> @channel.trigger 'someEvent', 'someData' @channel.dispatch('websocket_rails.channel_token', {token: '<KEY>'}) expect(@channel._queue.length).toEqual(0) describe 'private channels', -> beforeEach -> @channel = new WebSocketRails.Channel('forchan', @dispatcher, true) @event = @dispatcher.trigger_event.lastCall.args[0] it 'should trigger a subscribe_private event when created', -> expect(@event.name).toEqual 'websocket_rails.subscribe_private' it 'should be private', -> expect(@channel.is_private).toBeTruthy
true
describe 'WebSocketRails.Channel:', -> beforeEach -> @dispatcher = new class WebSocketRailsStub new_message: -> true dispatch: -> true trigger_event: (event) -> true state: 'connected' _conn: connection_id: 12345 @channel = new WebSocketRails.Channel('public', @dispatcher) sinon.spy @dispatcher, 'trigger_event' afterEach -> @dispatcher.trigger_event.restore() describe '.bind', -> it 'should add a function to the callbacks collection', -> test_func = -> @channel.bind 'event_name', test_func expect(@channel._callbacks['event_name'].length).toBe 1 expect(@channel._callbacks['event_name']).toContain test_func describe '.unbind', -> it 'should remove the callbacks of an event', -> callback = -> @channel.bind 'event', callback @channel.unbind 'event' expect(@channel._callbacks['event']).toBeUndefined() describe '.trigger', -> describe 'before the channel token is set', -> it 'queues the events', -> @channel.trigger 'someEvent', 'someData' queue = @channel._queue expect(queue[0].name).toEqual 'someEvent' expect(queue[0].data).toEqual 'someData' describe 'when channel token is set', -> it 'adds token to event metadata and dispatches event', -> @channel._token = 'valid token' @channel.trigger 'someEvent', 'someData' expect(@dispatcher.trigger_event.calledWith(['someEvent',{token: 'valid token', data: 'someData'}])) describe '.destroy', -> it 'should destroy all callbacks', -> event_callback = -> true @channel.bind('new_message', @event_callback) @channel.destroy() expect(@channel._callbacks).toEqual {} describe 'when this channel\'s connection is still active', -> it 'should send unsubscribe event', -> @channel.destroy() expect(@dispatcher.trigger_event.args[0][0].name).toEqual 'websocket_rails.unsubscribe' describe 'when this channel\'s connection is no more active', -> beforeEach -> @dispatcher._conn.connection_id++ it 'should not send unsubscribe event', -> @channel.destroy() expect(@dispatcher.trigger_event.notCalled).toEqual true describe 'public channels', -> beforeEach -> @channel = new WebSocketRails.Channel('forchan', @dispatcher, false) @event = @dispatcher.trigger_event.lastCall.args[0] it 'should trigger an event containing the channel name', -> expect(@event.data.channel).toEqual 'forchan' it 'should trigger an event containing the correct connection_id', -> expect(@event.connection_id).toEqual 12345 it 'should initialize an empty callbacks property', -> expect(@channel._callbacks).toBeDefined() expect(@channel._callbacks).toEqual {} it 'should be public', -> expect(@channel.is_private).toBeFalsy describe 'channel tokens', -> it 'should set token when event_name is websocket_rails.channel_token', -> @channel.dispatch('websocket_rails.channel_token', {token: 'PI:KEY:<KEY>END_PI'}) expect(@channel._token).toEqual 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI' it "should refresh channel's connection_id after channel_token has been received", -> # this is needed in case we would init the channel connection # just before the connection has been established @channel.connection_id = null @channel.dispatch('websocket_rails.channel_token', {token: 'PI:KEY:<KEY>END_PI'}) expect(@channel.connection_id).toEqual @dispatcher._conn.connection_id it 'should flush the event queue after setting token', -> @channel.trigger 'someEvent', 'someData' @channel.dispatch('websocket_rails.channel_token', {token: 'PI:KEY:<KEY>END_PI'}) expect(@channel._queue.length).toEqual(0) describe 'private channels', -> beforeEach -> @channel = new WebSocketRails.Channel('forchan', @dispatcher, true) @event = @dispatcher.trigger_event.lastCall.args[0] it 'should trigger a subscribe_private event when created', -> expect(@event.name).toEqual 'websocket_rails.subscribe_private' it 'should be private', -> expect(@channel.is_private).toBeTruthy
[ { "context": "ateTypingIn $inputor\n data = [{id: 1, name: \"one\"}, {id: 2, name: \"two\"}]\n controller.model.s", "end": 538, "score": 0.8807251453399658, "start": 535, "tag": "NAME", "value": "one" }, { "context": " data = [{id: 1, name: \"one\"}, {id: 2, name: \"two\"}]\n controller.model.save(data)\n expect", "end": 560, "score": 0.9271406531333923, "start": 557, "tag": "NAME", "value": "two" }, { "context": "ests.mostRecent()\n response_data = [{\"name\":\"Jacob\"}, {\"name\":\"Joshua\"}, {\"name\":\"Jayden\"}]\n re", "end": 933, "score": 0.9995457530021667, "start": 928, "tag": "NAME", "value": "Jacob" }, { "context": " response_data = [{\"name\":\"Jacob\"}, {\"name\":\"Joshua\"}, {\"name\":\"Jayden\"}]\n request.response\n ", "end": 952, "score": 0.9997889399528503, "start": 946, "tag": "NAME", "value": "Joshua" }, { "context": " = [{\"name\":\"Jacob\"}, {\"name\":\"Joshua\"}, {\"name\":\"Jayden\"}]\n request.response\n status: 200\n ", "end": 971, "score": 0.9998119473457336, "start": 965, "tag": "NAME", "value": "Jayden" } ]
spec/javascripts/apis.spec.coffee
spmjs/At.js
1
$inputor = null app = null describe "api", -> beforeEach -> loadFixtures("inputors.html") $inputor = $("#inputor").atwho at: "@", data: fixtures["names"] app = getAppOf $inputor describe "inner", -> controller = null callbacks = null beforeEach -> controller = app.controller() it "can get current data", -> simulateTypingIn $inputor expect(controller.model.fetch().length).toBe 24 it "can save current data", -> simulateTypingIn $inputor data = [{id: 1, name: "one"}, {id: 2, name: "two"}] controller.model.save(data) expect(controller.model.fetch().length).toBe 2 it "don't change data setting while using remote filter", -> jasmine.Ajax.install() $inputor.atwho at: "@" data: "/atwho.json" simulateTypingIn $inputor request = jasmine.Ajax.requests.mostRecent() response_data = [{"name":"Jacob"}, {"name":"Joshua"}, {"name":"Jayden"}] request.response status: 200 responseText: JSON.stringify(response_data) expect(controller.get_opt("data")).toBe "/atwho.json" expect(controller.model.fetch().length).toBe 3 describe "public", -> controller = null data = [] beforeEach -> controller = app.controller() data = [ {one: 1} {two: 2} {three: 3} ] it "can load data for special flag", -> $inputor.atwho "load", "@", data expect(controller.model.fetch().length).toBe data.length it "can load data with alias", -> $inputor.atwho at: "@", alias: "at" $inputor.atwho "load", "at", data expect(controller.model.fetch().length).toBe data.length it "can run it handly", -> app.set_context_for null $inputor.caret('pos', 31) $inputor.atwho "run" expect(app.controller().view.$el).not.toBeHidden() it 'destroy', -> $inputor.atwho at: "~" view_id = app.controller('~').view.$el.attr('id') $inputor.atwho 'destroy' expect($("##{view_id}").length).toBe 0 expect($inputor.data('atwho')).toBe null expect($inputor.data('~')).toBe null
133314
$inputor = null app = null describe "api", -> beforeEach -> loadFixtures("inputors.html") $inputor = $("#inputor").atwho at: "@", data: fixtures["names"] app = getAppOf $inputor describe "inner", -> controller = null callbacks = null beforeEach -> controller = app.controller() it "can get current data", -> simulateTypingIn $inputor expect(controller.model.fetch().length).toBe 24 it "can save current data", -> simulateTypingIn $inputor data = [{id: 1, name: "<NAME>"}, {id: 2, name: "<NAME>"}] controller.model.save(data) expect(controller.model.fetch().length).toBe 2 it "don't change data setting while using remote filter", -> jasmine.Ajax.install() $inputor.atwho at: "@" data: "/atwho.json" simulateTypingIn $inputor request = jasmine.Ajax.requests.mostRecent() response_data = [{"name":"<NAME>"}, {"name":"<NAME>"}, {"name":"<NAME>"}] request.response status: 200 responseText: JSON.stringify(response_data) expect(controller.get_opt("data")).toBe "/atwho.json" expect(controller.model.fetch().length).toBe 3 describe "public", -> controller = null data = [] beforeEach -> controller = app.controller() data = [ {one: 1} {two: 2} {three: 3} ] it "can load data for special flag", -> $inputor.atwho "load", "@", data expect(controller.model.fetch().length).toBe data.length it "can load data with alias", -> $inputor.atwho at: "@", alias: "at" $inputor.atwho "load", "at", data expect(controller.model.fetch().length).toBe data.length it "can run it handly", -> app.set_context_for null $inputor.caret('pos', 31) $inputor.atwho "run" expect(app.controller().view.$el).not.toBeHidden() it 'destroy', -> $inputor.atwho at: "~" view_id = app.controller('~').view.$el.attr('id') $inputor.atwho 'destroy' expect($("##{view_id}").length).toBe 0 expect($inputor.data('atwho')).toBe null expect($inputor.data('~')).toBe null
true
$inputor = null app = null describe "api", -> beforeEach -> loadFixtures("inputors.html") $inputor = $("#inputor").atwho at: "@", data: fixtures["names"] app = getAppOf $inputor describe "inner", -> controller = null callbacks = null beforeEach -> controller = app.controller() it "can get current data", -> simulateTypingIn $inputor expect(controller.model.fetch().length).toBe 24 it "can save current data", -> simulateTypingIn $inputor data = [{id: 1, name: "PI:NAME:<NAME>END_PI"}, {id: 2, name: "PI:NAME:<NAME>END_PI"}] controller.model.save(data) expect(controller.model.fetch().length).toBe 2 it "don't change data setting while using remote filter", -> jasmine.Ajax.install() $inputor.atwho at: "@" data: "/atwho.json" simulateTypingIn $inputor request = jasmine.Ajax.requests.mostRecent() response_data = [{"name":"PI:NAME:<NAME>END_PI"}, {"name":"PI:NAME:<NAME>END_PI"}, {"name":"PI:NAME:<NAME>END_PI"}] request.response status: 200 responseText: JSON.stringify(response_data) expect(controller.get_opt("data")).toBe "/atwho.json" expect(controller.model.fetch().length).toBe 3 describe "public", -> controller = null data = [] beforeEach -> controller = app.controller() data = [ {one: 1} {two: 2} {three: 3} ] it "can load data for special flag", -> $inputor.atwho "load", "@", data expect(controller.model.fetch().length).toBe data.length it "can load data with alias", -> $inputor.atwho at: "@", alias: "at" $inputor.atwho "load", "at", data expect(controller.model.fetch().length).toBe data.length it "can run it handly", -> app.set_context_for null $inputor.caret('pos', 31) $inputor.atwho "run" expect(app.controller().view.$el).not.toBeHidden() it 'destroy', -> $inputor.atwho at: "~" view_id = app.controller('~').view.$el.attr('id') $inputor.atwho 'destroy' expect($("##{view_id}").length).toBe 0 expect($inputor.data('atwho')).toBe null expect($inputor.data('~')).toBe null
[ { "context": "gramming for microcontrollers\n# Copyright (c) 2013 Jon Nordby <jononor@gmail.com>\n# MicroFlo may be freely dist", "end": 90, "score": 0.9998292922973633, "start": 80, "tag": "NAME", "value": "Jon Nordby" }, { "context": "microcontrollers\n# Copyright (c) 2013 Jon Nordby <jononor@gmail.com>\n# MicroFlo may be freely distributed under the M", "end": 109, "score": 0.9999333024024963, "start": 92, "tag": "EMAIL", "value": "jononor@gmail.com" } ]
test/commandstream.coffee
microflo/microflo
136
### MicroFlo - Flow-Based Programming for microcontrollers # Copyright (c) 2013 Jon Nordby <jononor@gmail.com> # MicroFlo may be freely distributed under the MIT license ### componentlib = null commandstream = null if typeof process != 'undefined' and process.execPath and process.execPath.indexOf('node') != -1 chai = require('chai') commandstream = require('../lib/commandstream') componentlib = require('../lib/componentlib') else commandstream = require('microflo/lib/commandstream') componentlib = require('microflo/lib/componentlib') microflo = require('microflo/lib/microflo') fbp = require('fbp') commandSize = 10 assertStreamsEqual = (actual, expected) -> chai.expect(actual.length).to.equal expected.length chai.expect(actual.length % commandSize).to.equal 0 i = 0 while i < actual.length a = actual.slice(i, i + commandSize).toJSON().toString() e = expected.slice(i, i + commandSize).toJSON().toString() chai.expect(a).to.equal e, 'Command ' + i / commandSize + ' : ' + a + ' != ' + e i += commandSize return describe 'Commandstream generation', -> describe 'from a simple input FBP', -> componentLib = new (componentlib.ComponentLibrary) componentLib.addComponent 'SerialIn', {}, 'SerialIn.hpp' componentLib.addComponent 'Forward', {}, 'Components.hpp' componentLib.addComponent 'SerialOut', {}, 'Components.hpp' input = 'in(SerialIn) OUT -> IN f(Forward) OUT -> IN out(SerialOut)' expect = commandstream.Buffer([ 10,0,0,0,0,0,0,0,0,0, 22,0,0,0,0,0,0,0,0,0, 15,1,0,0,0,0,0,0,0,0, 11,1,0,0,0,0,0,0,0,0, 11,2,0,0,0,0,0,0,0,0, 11,3,0,0,0,0,0,0,0,0, 12,1,2,0,0,0,0,0,0,0, 12,2,3,0,0,0,0,0,0,0, 20,0,0,0,0,0,0,0,0,0, ]) it 'parsing should give known valid output', -> out = commandstream.cmdStreamFromGraph(componentLib, fbp.parse(input)) assertStreamsEqual out, expect
200257
### MicroFlo - Flow-Based Programming for microcontrollers # Copyright (c) 2013 <NAME> <<EMAIL>> # MicroFlo may be freely distributed under the MIT license ### componentlib = null commandstream = null if typeof process != 'undefined' and process.execPath and process.execPath.indexOf('node') != -1 chai = require('chai') commandstream = require('../lib/commandstream') componentlib = require('../lib/componentlib') else commandstream = require('microflo/lib/commandstream') componentlib = require('microflo/lib/componentlib') microflo = require('microflo/lib/microflo') fbp = require('fbp') commandSize = 10 assertStreamsEqual = (actual, expected) -> chai.expect(actual.length).to.equal expected.length chai.expect(actual.length % commandSize).to.equal 0 i = 0 while i < actual.length a = actual.slice(i, i + commandSize).toJSON().toString() e = expected.slice(i, i + commandSize).toJSON().toString() chai.expect(a).to.equal e, 'Command ' + i / commandSize + ' : ' + a + ' != ' + e i += commandSize return describe 'Commandstream generation', -> describe 'from a simple input FBP', -> componentLib = new (componentlib.ComponentLibrary) componentLib.addComponent 'SerialIn', {}, 'SerialIn.hpp' componentLib.addComponent 'Forward', {}, 'Components.hpp' componentLib.addComponent 'SerialOut', {}, 'Components.hpp' input = 'in(SerialIn) OUT -> IN f(Forward) OUT -> IN out(SerialOut)' expect = commandstream.Buffer([ 10,0,0,0,0,0,0,0,0,0, 22,0,0,0,0,0,0,0,0,0, 15,1,0,0,0,0,0,0,0,0, 11,1,0,0,0,0,0,0,0,0, 11,2,0,0,0,0,0,0,0,0, 11,3,0,0,0,0,0,0,0,0, 12,1,2,0,0,0,0,0,0,0, 12,2,3,0,0,0,0,0,0,0, 20,0,0,0,0,0,0,0,0,0, ]) it 'parsing should give known valid output', -> out = commandstream.cmdStreamFromGraph(componentLib, fbp.parse(input)) assertStreamsEqual out, expect
true
### MicroFlo - Flow-Based Programming for microcontrollers # Copyright (c) 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # MicroFlo may be freely distributed under the MIT license ### componentlib = null commandstream = null if typeof process != 'undefined' and process.execPath and process.execPath.indexOf('node') != -1 chai = require('chai') commandstream = require('../lib/commandstream') componentlib = require('../lib/componentlib') else commandstream = require('microflo/lib/commandstream') componentlib = require('microflo/lib/componentlib') microflo = require('microflo/lib/microflo') fbp = require('fbp') commandSize = 10 assertStreamsEqual = (actual, expected) -> chai.expect(actual.length).to.equal expected.length chai.expect(actual.length % commandSize).to.equal 0 i = 0 while i < actual.length a = actual.slice(i, i + commandSize).toJSON().toString() e = expected.slice(i, i + commandSize).toJSON().toString() chai.expect(a).to.equal e, 'Command ' + i / commandSize + ' : ' + a + ' != ' + e i += commandSize return describe 'Commandstream generation', -> describe 'from a simple input FBP', -> componentLib = new (componentlib.ComponentLibrary) componentLib.addComponent 'SerialIn', {}, 'SerialIn.hpp' componentLib.addComponent 'Forward', {}, 'Components.hpp' componentLib.addComponent 'SerialOut', {}, 'Components.hpp' input = 'in(SerialIn) OUT -> IN f(Forward) OUT -> IN out(SerialOut)' expect = commandstream.Buffer([ 10,0,0,0,0,0,0,0,0,0, 22,0,0,0,0,0,0,0,0,0, 15,1,0,0,0,0,0,0,0,0, 11,1,0,0,0,0,0,0,0,0, 11,2,0,0,0,0,0,0,0,0, 11,3,0,0,0,0,0,0,0,0, 12,1,2,0,0,0,0,0,0,0, 12,2,3,0,0,0,0,0,0,0, 20,0,0,0,0,0,0,0,0,0, ]) it 'parsing should give known valid output', -> out = commandstream.cmdStreamFromGraph(componentLib, fbp.parse(input)) assertStreamsEqual out, expect
[ { "context": "me = req.body.user.last_name\n user.password = req.body.user.password\n\n user.save (err, user_updated)->\n re", "end": 2496, "score": 0.9991980791091919, "start": 2474, "tag": "PASSWORD", "value": "req.body.user.password" } ]
express/controllers/users_controller.coffee
denya133/neemb
0
mongoose = require 'mongoose' uuid = require "node-uuid" _ = require 'lodash' roles = require '../config/roles' User = mongoose.model 'User' Apikey = mongoose.model 'Apikey' Role = mongoose.model 'Role' module.exports = (app, passport, config)-> app.post "/rest-api/sessions", (req, res) -> console.log 'to users.exports.session' User.findOne(email: req.body.session.email) .populate("apikey").populate("role").exec (err, user) -> return res.json err if err unless user return res.json 401, message: "Incorrect username or password." User.verifyPassword req.body.session.password, user.password , (err, result) -> if result res.json session: user else res.send 401, "Incorrect username or password." app.get "/rest-api/users", roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.index' params = {} if req.query.ids params = _id: $in: req.query.ids User.find(params).exec (err, users) -> return res.json error: err if err role_ids = [] _.each users, (user)-> role_ids.push user.role Role.find _id: {$in: role_ids}, (err, roles)-> return res.json error: err if err res.json 200, users: users roles: roles app.post "/rest-api/users", roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.create' role = Role.findById req.body.user.role, (err, role)-> new_user = new User(req.body.user) new_user.role = role._id new_user.save (err, saved_user, num_affected) -> new_apikey = new Apikey( userId: saved_user._id key: uuid.v4() ) new_apikey.save (err, saved_apikey, num_affected) -> saved_user.apikey = saved_apikey._id saved_user.save (err, updated_user, num_affected) -> res.json err if err res.json user: updated_user app.put "/rest-api/users/:userId", passport.authenticate("bearer", session: false ), roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.update' User.findById req.params.userId, (err, user)-> res.json 500, {error: err} if err # console.log user user.email = req.body.user.email user.first_name = req.body.user.first_name user.last_name = req.body.user.last_name user.password = req.body.user.password user.save (err, user_updated)-> res.json 500, {error: err} if err res.json 200, {user: user_updated} app.delete "/rest-api/users/:userId", passport.authenticate("bearer", session: false ), roles.middleware("neemb/view"), (req, res)-> console.log 'to users.exports.delete' User.findByIdAndRemove req.params.userId, (err, user)-> res.json 500, {error: err} if err res.send 200, '' app.get "/rest-api/users/me", passport.authenticate("bearer", session: false ), roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.me' res.json req.user or null app.get "/rest-api/users/:userId", roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.user' User.findById req.params.userId, (err, user) -> return res.json err if err Role.findById user.role, (err, role)-> return res.json err if err res.json roles: [role] user: user app.get "/rest-api/authors/:userId", (req, res) -> console.log 'to authors.exports.user' User.findById req.params.userId, (err, user) -> return res.json err if err unless user return res.json 200, author: null user.populate('apikey').populate 'role', (err, user)-> res.json 500, err if err res.json author: user
74305
mongoose = require 'mongoose' uuid = require "node-uuid" _ = require 'lodash' roles = require '../config/roles' User = mongoose.model 'User' Apikey = mongoose.model 'Apikey' Role = mongoose.model 'Role' module.exports = (app, passport, config)-> app.post "/rest-api/sessions", (req, res) -> console.log 'to users.exports.session' User.findOne(email: req.body.session.email) .populate("apikey").populate("role").exec (err, user) -> return res.json err if err unless user return res.json 401, message: "Incorrect username or password." User.verifyPassword req.body.session.password, user.password , (err, result) -> if result res.json session: user else res.send 401, "Incorrect username or password." app.get "/rest-api/users", roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.index' params = {} if req.query.ids params = _id: $in: req.query.ids User.find(params).exec (err, users) -> return res.json error: err if err role_ids = [] _.each users, (user)-> role_ids.push user.role Role.find _id: {$in: role_ids}, (err, roles)-> return res.json error: err if err res.json 200, users: users roles: roles app.post "/rest-api/users", roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.create' role = Role.findById req.body.user.role, (err, role)-> new_user = new User(req.body.user) new_user.role = role._id new_user.save (err, saved_user, num_affected) -> new_apikey = new Apikey( userId: saved_user._id key: uuid.v4() ) new_apikey.save (err, saved_apikey, num_affected) -> saved_user.apikey = saved_apikey._id saved_user.save (err, updated_user, num_affected) -> res.json err if err res.json user: updated_user app.put "/rest-api/users/:userId", passport.authenticate("bearer", session: false ), roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.update' User.findById req.params.userId, (err, user)-> res.json 500, {error: err} if err # console.log user user.email = req.body.user.email user.first_name = req.body.user.first_name user.last_name = req.body.user.last_name user.password = <PASSWORD> user.save (err, user_updated)-> res.json 500, {error: err} if err res.json 200, {user: user_updated} app.delete "/rest-api/users/:userId", passport.authenticate("bearer", session: false ), roles.middleware("neemb/view"), (req, res)-> console.log 'to users.exports.delete' User.findByIdAndRemove req.params.userId, (err, user)-> res.json 500, {error: err} if err res.send 200, '' app.get "/rest-api/users/me", passport.authenticate("bearer", session: false ), roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.me' res.json req.user or null app.get "/rest-api/users/:userId", roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.user' User.findById req.params.userId, (err, user) -> return res.json err if err Role.findById user.role, (err, role)-> return res.json err if err res.json roles: [role] user: user app.get "/rest-api/authors/:userId", (req, res) -> console.log 'to authors.exports.user' User.findById req.params.userId, (err, user) -> return res.json err if err unless user return res.json 200, author: null user.populate('apikey').populate 'role', (err, user)-> res.json 500, err if err res.json author: user
true
mongoose = require 'mongoose' uuid = require "node-uuid" _ = require 'lodash' roles = require '../config/roles' User = mongoose.model 'User' Apikey = mongoose.model 'Apikey' Role = mongoose.model 'Role' module.exports = (app, passport, config)-> app.post "/rest-api/sessions", (req, res) -> console.log 'to users.exports.session' User.findOne(email: req.body.session.email) .populate("apikey").populate("role").exec (err, user) -> return res.json err if err unless user return res.json 401, message: "Incorrect username or password." User.verifyPassword req.body.session.password, user.password , (err, result) -> if result res.json session: user else res.send 401, "Incorrect username or password." app.get "/rest-api/users", roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.index' params = {} if req.query.ids params = _id: $in: req.query.ids User.find(params).exec (err, users) -> return res.json error: err if err role_ids = [] _.each users, (user)-> role_ids.push user.role Role.find _id: {$in: role_ids}, (err, roles)-> return res.json error: err if err res.json 200, users: users roles: roles app.post "/rest-api/users", roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.create' role = Role.findById req.body.user.role, (err, role)-> new_user = new User(req.body.user) new_user.role = role._id new_user.save (err, saved_user, num_affected) -> new_apikey = new Apikey( userId: saved_user._id key: uuid.v4() ) new_apikey.save (err, saved_apikey, num_affected) -> saved_user.apikey = saved_apikey._id saved_user.save (err, updated_user, num_affected) -> res.json err if err res.json user: updated_user app.put "/rest-api/users/:userId", passport.authenticate("bearer", session: false ), roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.update' User.findById req.params.userId, (err, user)-> res.json 500, {error: err} if err # console.log user user.email = req.body.user.email user.first_name = req.body.user.first_name user.last_name = req.body.user.last_name user.password = PI:PASSWORD:<PASSWORD>END_PI user.save (err, user_updated)-> res.json 500, {error: err} if err res.json 200, {user: user_updated} app.delete "/rest-api/users/:userId", passport.authenticate("bearer", session: false ), roles.middleware("neemb/view"), (req, res)-> console.log 'to users.exports.delete' User.findByIdAndRemove req.params.userId, (err, user)-> res.json 500, {error: err} if err res.send 200, '' app.get "/rest-api/users/me", passport.authenticate("bearer", session: false ), roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.me' res.json req.user or null app.get "/rest-api/users/:userId", roles.middleware("neemb/view"), (req, res) -> console.log 'to users.exports.user' User.findById req.params.userId, (err, user) -> return res.json err if err Role.findById user.role, (err, role)-> return res.json err if err res.json roles: [role] user: user app.get "/rest-api/authors/:userId", (req, res) -> console.log 'to authors.exports.user' User.findById req.params.userId, (err, user) -> return res.json err if err unless user return res.json 200, author: null user.populate('apikey').populate 'role', (err, user)-> res.json 500, err if err res.json author: user
[ { "context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n * (c) Marvin Frachet <mar", "end": 74, "score": 0.999890148639679, "start": 61, "tag": "NAME", "value": "Jessym Reziga" }, { "context": "f the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n * (c) Marvin Frachet <marvin@konsserto.com>\n *\n", "end": 96, "score": 0.9999332427978516, "start": 76, "tag": "EMAIL", "value": "jessym@konsserto.com" }, { "context": " * (c) Jessym Reziga <jessym@konsserto.com>\n * (c) Marvin Frachet <marvin@konsserto.com>\n *\n * For the full copyrig", "end": 119, "score": 0.9998917579650879, "start": 105, "tag": "NAME", "value": "Marvin Frachet" }, { "context": "iga <jessym@konsserto.com>\n * (c) Marvin Frachet <marvin@konsserto.com>\n *\n * For the full copyright and license informa", "end": 141, "score": 0.9999349117279053, "start": 121, "tag": "EMAIL", "value": "marvin@konsserto.com" }, { "context": "age boot process and server's requests\n#\n# @author Jessym Reziga <jessym@konsserto.com>\n# @version version 0.1\n#\nc", "end": 734, "score": 0.9998891949653625, "start": 721, "tag": "NAME", "value": "Jessym Reziga" }, { "context": " and server's requests\n#\n# @author Jessym Reziga <jessym@konsserto.com>\n# @version version 0.1\n#\nclass Kernel\n\n # Versi", "end": 756, "score": 0.9999336004257202, "start": 736, "tag": "EMAIL", "value": "jessym@konsserto.com" } ]
node_modules/konsserto/lib/src/Konsserto/Component/HttpKernel/Kernel.coffee
konsserto/konsserto
2
### * This file is part of the Konsserto package. * * (c) Jessym Reziga <jessym@konsserto.com> * (c) Marvin Frachet <marvin@konsserto.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### cc = use('cli-color') wait = use('wait.for') CONFIG = use('/app/config/config') ExceptionHandler = use('@Konsserto/Component/Debug/ExceptionHandler') HttpRequestException = use('@Konsserto/Component/HttpKernel/Exception/HttpRequestException') ServiceContainer = use('@Konsserto/Component/DependencyInjection/ServiceContainer') Tools = use('@Konsserto/Component/Static/Tools') # # Kernel manage boot process and server's requests # # @author Jessym Reziga <jessym@konsserto.com> # @version version 0.1 # class Kernel # Version release number @VERSION = '0.0.46' # Version unique ID @VERSION_ID = 1 # Class constructor # @param environment {String} The environment tag # @param debug {Boolean} The debug mode # @param mode {String} The application/console tag mode constructor: (@environment = 'dev', @debug = true, @mode = 'app') -> global.NODE_ENV = @environment global.env = @environment @booted = false # @return {String} The environment tag getEnvironment: () -> return @environment # @return {String} The debug mode getDebug: () -> return @debug # Start boot sequence, initialize the service container and bundles boot: () -> @checkMode() @initContainer() for name,bundle of @container.get('Application').getBundles() bundle.setContainer(@container) bundle.boot() @booted = true # Shutdown sequence, close the service container and bundles # @param exitCode {Integer} The default exit status code # @return {Integer} The exit state code shutdown: (exitCode = -1) -> console.log('\n' + cc.white.bgRed('[Power OFF]') + ' Shutdown Konsserto') if @booted == false return @booted = false for name,bundle of @container.get('Application').getBundles() bundle.shutdown() bundle.setContainer(undefined) console.log('[Container] Shutdown Service Container\n') @container = null return process.exit(exitCode) # @return {Boolean} kernel state isBooted: () -> return @booted # Instantiate the service container initContainer: () -> @container = new ServiceContainer(this) @requestStack = @container.get('Request_Stack') # Check application/console tag mode and nullify the console log output checkMode: () -> if @mode == 'console' return console.log = () -> # Try to handle an express route # @param route {RouteInstance} The route instance handle: (route) -> try return @handleRaw(route) catch e @finishRequest(route.getRequest()) throw e # Handle an express route and call the controller # @param route {RouteInstance} The route instance handleRaw: (route) -> @requestStack.push(route.getRequest()); definition = route.getDefinition() if !route.methodExists() throw new Error('Method ' + route.getMethod() + ' doesn\'t exists in ' + definition.getControllerName()) if (definition.isAsynchronous()) route.getResponse() else wait.launchFiber(()=> route.getResponse() ) # Pop the request stack for sub-requests # @param route {Request} the express request finishRequest: (req) -> @requestStack.pop(req) # Start konsserto on a specific port with error handler # @param route {Integer} The listening port number start: (port) -> domain = require('domain').create(); domain.on('error', (err) => response = @container.get('Request_Stack').getCurrentRequest().res engine = @container.get('Templating') ExceptionHandler.handle(err, response, engine) ) domain.run(() => @boot() ) KSc = cc.xterm(255).bgXterm(0); console.log(KSc(' _ __ _ ')) console.log(KSc(' | |/ / | | ')) console.log(KSc(' | \' / ___ _ __ ___ ___ ___ _ __| |_ ___ ')) console.log(KSc(' | < / _ \\| \'_ \\/ __/ __|/ _ \\ \'__| __/ _ \\ ')) console.log(KSc(' | . \\ (_) | | | \\__ \\__ \\ __/ | | || (_) |')) console.log(KSc(' |_|\\_\\___/|_| |_|___/___/\\___|_| \\__ \\___/ ')) console.log(KSc('')) app = @container.get('Application').start(port) module.exports = Kernel;
22609
### * This file is part of the Konsserto package. * * (c) <NAME> <<EMAIL>> * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### cc = use('cli-color') wait = use('wait.for') CONFIG = use('/app/config/config') ExceptionHandler = use('@Konsserto/Component/Debug/ExceptionHandler') HttpRequestException = use('@Konsserto/Component/HttpKernel/Exception/HttpRequestException') ServiceContainer = use('@Konsserto/Component/DependencyInjection/ServiceContainer') Tools = use('@Konsserto/Component/Static/Tools') # # Kernel manage boot process and server's requests # # @author <NAME> <<EMAIL>> # @version version 0.1 # class Kernel # Version release number @VERSION = '0.0.46' # Version unique ID @VERSION_ID = 1 # Class constructor # @param environment {String} The environment tag # @param debug {Boolean} The debug mode # @param mode {String} The application/console tag mode constructor: (@environment = 'dev', @debug = true, @mode = 'app') -> global.NODE_ENV = @environment global.env = @environment @booted = false # @return {String} The environment tag getEnvironment: () -> return @environment # @return {String} The debug mode getDebug: () -> return @debug # Start boot sequence, initialize the service container and bundles boot: () -> @checkMode() @initContainer() for name,bundle of @container.get('Application').getBundles() bundle.setContainer(@container) bundle.boot() @booted = true # Shutdown sequence, close the service container and bundles # @param exitCode {Integer} The default exit status code # @return {Integer} The exit state code shutdown: (exitCode = -1) -> console.log('\n' + cc.white.bgRed('[Power OFF]') + ' Shutdown Konsserto') if @booted == false return @booted = false for name,bundle of @container.get('Application').getBundles() bundle.shutdown() bundle.setContainer(undefined) console.log('[Container] Shutdown Service Container\n') @container = null return process.exit(exitCode) # @return {Boolean} kernel state isBooted: () -> return @booted # Instantiate the service container initContainer: () -> @container = new ServiceContainer(this) @requestStack = @container.get('Request_Stack') # Check application/console tag mode and nullify the console log output checkMode: () -> if @mode == 'console' return console.log = () -> # Try to handle an express route # @param route {RouteInstance} The route instance handle: (route) -> try return @handleRaw(route) catch e @finishRequest(route.getRequest()) throw e # Handle an express route and call the controller # @param route {RouteInstance} The route instance handleRaw: (route) -> @requestStack.push(route.getRequest()); definition = route.getDefinition() if !route.methodExists() throw new Error('Method ' + route.getMethod() + ' doesn\'t exists in ' + definition.getControllerName()) if (definition.isAsynchronous()) route.getResponse() else wait.launchFiber(()=> route.getResponse() ) # Pop the request stack for sub-requests # @param route {Request} the express request finishRequest: (req) -> @requestStack.pop(req) # Start konsserto on a specific port with error handler # @param route {Integer} The listening port number start: (port) -> domain = require('domain').create(); domain.on('error', (err) => response = @container.get('Request_Stack').getCurrentRequest().res engine = @container.get('Templating') ExceptionHandler.handle(err, response, engine) ) domain.run(() => @boot() ) KSc = cc.xterm(255).bgXterm(0); console.log(KSc(' _ __ _ ')) console.log(KSc(' | |/ / | | ')) console.log(KSc(' | \' / ___ _ __ ___ ___ ___ _ __| |_ ___ ')) console.log(KSc(' | < / _ \\| \'_ \\/ __/ __|/ _ \\ \'__| __/ _ \\ ')) console.log(KSc(' | . \\ (_) | | | \\__ \\__ \\ __/ | | || (_) |')) console.log(KSc(' |_|\\_\\___/|_| |_|___/___/\\___|_| \\__ \\___/ ')) console.log(KSc('')) app = @container.get('Application').start(port) module.exports = Kernel;
true
### * This file is part of the Konsserto package. * * (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### cc = use('cli-color') wait = use('wait.for') CONFIG = use('/app/config/config') ExceptionHandler = use('@Konsserto/Component/Debug/ExceptionHandler') HttpRequestException = use('@Konsserto/Component/HttpKernel/Exception/HttpRequestException') ServiceContainer = use('@Konsserto/Component/DependencyInjection/ServiceContainer') Tools = use('@Konsserto/Component/Static/Tools') # # Kernel manage boot process and server's requests # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # @version version 0.1 # class Kernel # Version release number @VERSION = '0.0.46' # Version unique ID @VERSION_ID = 1 # Class constructor # @param environment {String} The environment tag # @param debug {Boolean} The debug mode # @param mode {String} The application/console tag mode constructor: (@environment = 'dev', @debug = true, @mode = 'app') -> global.NODE_ENV = @environment global.env = @environment @booted = false # @return {String} The environment tag getEnvironment: () -> return @environment # @return {String} The debug mode getDebug: () -> return @debug # Start boot sequence, initialize the service container and bundles boot: () -> @checkMode() @initContainer() for name,bundle of @container.get('Application').getBundles() bundle.setContainer(@container) bundle.boot() @booted = true # Shutdown sequence, close the service container and bundles # @param exitCode {Integer} The default exit status code # @return {Integer} The exit state code shutdown: (exitCode = -1) -> console.log('\n' + cc.white.bgRed('[Power OFF]') + ' Shutdown Konsserto') if @booted == false return @booted = false for name,bundle of @container.get('Application').getBundles() bundle.shutdown() bundle.setContainer(undefined) console.log('[Container] Shutdown Service Container\n') @container = null return process.exit(exitCode) # @return {Boolean} kernel state isBooted: () -> return @booted # Instantiate the service container initContainer: () -> @container = new ServiceContainer(this) @requestStack = @container.get('Request_Stack') # Check application/console tag mode and nullify the console log output checkMode: () -> if @mode == 'console' return console.log = () -> # Try to handle an express route # @param route {RouteInstance} The route instance handle: (route) -> try return @handleRaw(route) catch e @finishRequest(route.getRequest()) throw e # Handle an express route and call the controller # @param route {RouteInstance} The route instance handleRaw: (route) -> @requestStack.push(route.getRequest()); definition = route.getDefinition() if !route.methodExists() throw new Error('Method ' + route.getMethod() + ' doesn\'t exists in ' + definition.getControllerName()) if (definition.isAsynchronous()) route.getResponse() else wait.launchFiber(()=> route.getResponse() ) # Pop the request stack for sub-requests # @param route {Request} the express request finishRequest: (req) -> @requestStack.pop(req) # Start konsserto on a specific port with error handler # @param route {Integer} The listening port number start: (port) -> domain = require('domain').create(); domain.on('error', (err) => response = @container.get('Request_Stack').getCurrentRequest().res engine = @container.get('Templating') ExceptionHandler.handle(err, response, engine) ) domain.run(() => @boot() ) KSc = cc.xterm(255).bgXterm(0); console.log(KSc(' _ __ _ ')) console.log(KSc(' | |/ / | | ')) console.log(KSc(' | \' / ___ _ __ ___ ___ ___ _ __| |_ ___ ')) console.log(KSc(' | < / _ \\| \'_ \\/ __/ __|/ _ \\ \'__| __/ _ \\ ')) console.log(KSc(' | . \\ (_) | | | \\__ \\__ \\ __/ | | || (_) |')) console.log(KSc(' |_|\\_\\___/|_| |_|___/___/\\___|_| \\__ \\___/ ')) console.log(KSc('')) app = @container.get('Application').start(port) module.exports = Kernel;
[ { "context": "# Copyright (c) 2008-2013 Michael Dvorkin and contributors.\n#\n# Fat Free CRM is freely dist", "end": 41, "score": 0.9998599886894226, "start": 26, "tag": "NAME", "value": "Michael Dvorkin" } ]
app/assets/javascripts/lists.js.coffee
ramses-lopez/re-crm
1
# Copyright (c) 2008-2013 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 #------------------------------------------------------------------------------ (($) -> class @Lists constructor: (@templates = {}) -> show_save_form: -> $(".save_list").show() $('.save_list #list_name').focus() hide_save_form: -> $(".save_list").hide() $(document).ready -> lists = new Lists() $(".show_lists_save_form").live "click", -> lists.show_save_form() $(".show_lists_save_form").hide() false $(".hide_lists_save_form").live "click", -> lists.hide_save_form() $(".show_lists_save_form").show() false $("input#save_list").live "click", -> # Set value of hidden list_url field to serialized search form $("#list_url").val(window.location.pathname + '?' + $('form.ransack_search').serialize()) true # When mouseover on li, change asset icons to delete buttons $("#lists li").live "mouseover", -> img_el = $(this).find('.delete_on_hover img') img_el.attr('src', "/assets/delete.png") $("#lists li").live "mouseout", -> img_el = $(this).find('.delete_on_hover img') img_el.attr('src', "/assets/tab_icons/" + img_el.data('controller') + "_active.png") ) jQuery
157027
# Copyright (c) 2008-2013 <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 #------------------------------------------------------------------------------ (($) -> class @Lists constructor: (@templates = {}) -> show_save_form: -> $(".save_list").show() $('.save_list #list_name').focus() hide_save_form: -> $(".save_list").hide() $(document).ready -> lists = new Lists() $(".show_lists_save_form").live "click", -> lists.show_save_form() $(".show_lists_save_form").hide() false $(".hide_lists_save_form").live "click", -> lists.hide_save_form() $(".show_lists_save_form").show() false $("input#save_list").live "click", -> # Set value of hidden list_url field to serialized search form $("#list_url").val(window.location.pathname + '?' + $('form.ransack_search').serialize()) true # When mouseover on li, change asset icons to delete buttons $("#lists li").live "mouseover", -> img_el = $(this).find('.delete_on_hover img') img_el.attr('src', "/assets/delete.png") $("#lists li").live "mouseout", -> img_el = $(this).find('.delete_on_hover img') img_el.attr('src', "/assets/tab_icons/" + img_el.data('controller') + "_active.png") ) jQuery
true
# Copyright (c) 2008-2013 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 #------------------------------------------------------------------------------ (($) -> class @Lists constructor: (@templates = {}) -> show_save_form: -> $(".save_list").show() $('.save_list #list_name').focus() hide_save_form: -> $(".save_list").hide() $(document).ready -> lists = new Lists() $(".show_lists_save_form").live "click", -> lists.show_save_form() $(".show_lists_save_form").hide() false $(".hide_lists_save_form").live "click", -> lists.hide_save_form() $(".show_lists_save_form").show() false $("input#save_list").live "click", -> # Set value of hidden list_url field to serialized search form $("#list_url").val(window.location.pathname + '?' + $('form.ransack_search').serialize()) true # When mouseover on li, change asset icons to delete buttons $("#lists li").live "mouseover", -> img_el = $(this).find('.delete_on_hover img') img_el.attr('src', "/assets/delete.png") $("#lists li").live "mouseout", -> img_el = $(this).find('.delete_on_hover img') img_el.attr('src', "/assets/tab_icons/" + img_el.data('controller') + "_active.png") ) jQuery
[ { "context": " context: context,\n user_name: 'Niels Wonderweblabs'\n user_name_href: '#/test'\n }", "end": 1647, "score": 0.9997636079788208, "start": 1628, "tag": "NAME", "value": "Niels Wonderweblabs" } ]
build/index.coffee
wonderweblabs/wwl-js-backend
0
require('webcomponentsjs/webcomponents') global.$ = require('jquery') global.jquery = global.jQuery = global.$ global._ = require 'underscore' global.underscore = global._ global.Backbone = require 'backbone' global.backbone = global.Backbone global.Backbone.$ = $ domready = require 'domready' wwlContext = require 'wwl-js-app-context' domready -> context = new (wwlContext)({ root: true }) tester = new (require('wwl-js-vm')).Tester({ domElementId: 'wwl-js-vm-tester-container' config: getDefaultVMConfig: -> context: context navigation_items_collection: new (require('../lib/collections/navigation_items_collection'))([{ id: 'dashboard' title: 'Dashboard' icon: 'mdi mdi-view-dashboard' href: '#/dashboard' active: true },{ id: 'home' title: 'Home' href: '#/home' icon: 'mdi mdi-view-home' active: false }]) vmConfig: _.extend({ beforeStart: (vm, moduleConfig) -> vm.getView().triggerMethod 'attach' vm.getView().triggerMethod 'show' afterStart: (vm, moduleConfig) -> window.vm = vm Backbone.listenTo vm, 'click', (event, model, vm)=> console.log 'click', model.id vm.setActiveNavigationItem(model.id) vm.setHeaderVM( new (require('../lib/vms/header/vm'))({ context: context, user_name: 'Niels Wonderweblabs' user_name_href: '#/test' }) ) vmPrototype: require('../lib/vms/main/vm') }, require('./vm_config')) }).run()
54144
require('webcomponentsjs/webcomponents') global.$ = require('jquery') global.jquery = global.jQuery = global.$ global._ = require 'underscore' global.underscore = global._ global.Backbone = require 'backbone' global.backbone = global.Backbone global.Backbone.$ = $ domready = require 'domready' wwlContext = require 'wwl-js-app-context' domready -> context = new (wwlContext)({ root: true }) tester = new (require('wwl-js-vm')).Tester({ domElementId: 'wwl-js-vm-tester-container' config: getDefaultVMConfig: -> context: context navigation_items_collection: new (require('../lib/collections/navigation_items_collection'))([{ id: 'dashboard' title: 'Dashboard' icon: 'mdi mdi-view-dashboard' href: '#/dashboard' active: true },{ id: 'home' title: 'Home' href: '#/home' icon: 'mdi mdi-view-home' active: false }]) vmConfig: _.extend({ beforeStart: (vm, moduleConfig) -> vm.getView().triggerMethod 'attach' vm.getView().triggerMethod 'show' afterStart: (vm, moduleConfig) -> window.vm = vm Backbone.listenTo vm, 'click', (event, model, vm)=> console.log 'click', model.id vm.setActiveNavigationItem(model.id) vm.setHeaderVM( new (require('../lib/vms/header/vm'))({ context: context, user_name: '<NAME>' user_name_href: '#/test' }) ) vmPrototype: require('../lib/vms/main/vm') }, require('./vm_config')) }).run()
true
require('webcomponentsjs/webcomponents') global.$ = require('jquery') global.jquery = global.jQuery = global.$ global._ = require 'underscore' global.underscore = global._ global.Backbone = require 'backbone' global.backbone = global.Backbone global.Backbone.$ = $ domready = require 'domready' wwlContext = require 'wwl-js-app-context' domready -> context = new (wwlContext)({ root: true }) tester = new (require('wwl-js-vm')).Tester({ domElementId: 'wwl-js-vm-tester-container' config: getDefaultVMConfig: -> context: context navigation_items_collection: new (require('../lib/collections/navigation_items_collection'))([{ id: 'dashboard' title: 'Dashboard' icon: 'mdi mdi-view-dashboard' href: '#/dashboard' active: true },{ id: 'home' title: 'Home' href: '#/home' icon: 'mdi mdi-view-home' active: false }]) vmConfig: _.extend({ beforeStart: (vm, moduleConfig) -> vm.getView().triggerMethod 'attach' vm.getView().triggerMethod 'show' afterStart: (vm, moduleConfig) -> window.vm = vm Backbone.listenTo vm, 'click', (event, model, vm)=> console.log 'click', model.id vm.setActiveNavigationItem(model.id) vm.setHeaderVM( new (require('../lib/vms/header/vm'))({ context: context, user_name: 'PI:NAME:<NAME>END_PI' user_name_href: '#/test' }) ) vmPrototype: require('../lib/vms/main/vm') }, require('./vm_config')) }).run()
[ { "context": "# @author Gianluigi Mango\n# Image API\nImageHandler = require './handler/ima", "end": 25, "score": 0.9998661875724792, "start": 10, "tag": "NAME", "value": "Gianluigi Mango" } ]
dev/server/api/imageApi.coffee
knickatheart/mean-api
0
# @author Gianluigi Mango # Image API ImageHandler = require './handler/imageHandler' module.exports = class ImageApi constructor: (@action, @path, @req, @res) -> @imageHandler = new ImageHandler @req console.info '[Query]', action switch @action when 'getProfileImage' then @imageHandler.getProfileImage @path, @res else res.send Error: 'No method found'
44073
# @author <NAME> # Image API ImageHandler = require './handler/imageHandler' module.exports = class ImageApi constructor: (@action, @path, @req, @res) -> @imageHandler = new ImageHandler @req console.info '[Query]', action switch @action when 'getProfileImage' then @imageHandler.getProfileImage @path, @res else res.send Error: 'No method found'
true
# @author PI:NAME:<NAME>END_PI # Image API ImageHandler = require './handler/imageHandler' module.exports = class ImageApi constructor: (@action, @path, @req, @res) -> @imageHandler = new ImageHandler @req console.info '[Query]', action switch @action when 'getProfileImage' then @imageHandler.getProfileImage @path, @res else res.send Error: 'No method found'
[ { "context": "4-06-01T00:00:00.000-03:00\"\n description: \"Sueldo\"\n type: \"income\"\n value: 4000\n ", "end": 623, "score": 0.6014218330383301, "start": 617, "tag": "NAME", "value": "Sueldo" }, { "context": "4-06-02T00:00:00.000-03:00\"\n description: \"Activesap\"\n type: \"income\"\n value: 500\n", "end": 777, "score": 0.5055229663848877, "start": 774, "tag": "NAME", "value": "Act" }, { "context": "4-06-03T00:00:00.000-03:00\"\n description: \"Matias\"\n type: \"expense\"\n value: 1100\n ", "end": 939, "score": 0.9660218954086304, "start": 933, "tag": "NAME", "value": "Matias" }, { "context": "4-07-01T00:00:00.000-03:00\"\n description: \"Sueldo\"\n type: \"income\"\n value: 4000\n", "end": 1092, "score": 0.7213468551635742, "start": 1091, "tag": "NAME", "value": "S" }, { "context": "7-01T00:00:00.000-03:00\"\n description: \"Sueldo\"\n type: \"income\"\n value: 4000\n ", "end": 1097, "score": 0.5510455965995789, "start": 1094, "tag": "NAME", "value": "ldo" }, { "context": "4-07-02T00:00:00.000-03:00\"\n description: \"Gomitas\"\n type: \"expense\"\n value: 8500\n ", "end": 1255, "score": 0.768456220626831, "start": 1248, "tag": "NAME", "value": "Gomitas" }, { "context": "4-08-01T00:00:00.000-03:00\"\n description: \"Sueldo\"\n type: \"income\"\n value: 4000\n", "end": 1408, "score": 0.6890110969543457, "start": 1407, "tag": "NAME", "value": "S" } ]
js/mycoins.coffee
sanchan/my-coins
1
fakeData = -> # Transaction Categories if not MyCoins.transactionCategoriesCollection.length transactionCategories = ["Bills", "Car", "Clothing", "Health", "Housing", "Others", "Restaurants", "Taxes", "Transport", "Travels"] for t in transactionCategories MyCoins.transactionCategoriesCollection.create name: t # Accounts and Transactions if not MyCoins.accountsCollection.length MyCoins.accountsCollection.create name: "Cuenta Personal" type: "cash" transactions = [ { accountId: 1 date: "2014-06-01T00:00:00.000-03:00" description: "Sueldo" type: "income" value: 4000 }, { accountId: 1 date: "2014-06-02T00:00:00.000-03:00" description: "Activesap" type: "income" value: 500 }, { accountId: 1 date: "2014-06-03T00:00:00.000-03:00" description: "Matias" type: "expense" value: 1100 }, { accountId: 1 date: "2014-07-01T00:00:00.000-03:00" description: "Sueldo" type: "income" value: 4000 }, { accountId: 1 date: "2014-07-02T00:00:00.000-03:00" description: "Gomitas" type: "expense" value: 8500 }, { accountId: 1 date: "2014-08-01T00:00:00.000-03:00" description: "Sueldo" type: "income" value: 4000 }, { accountId: 1 date: "2014-08-01T00:00:00.000-03:00" description: "Venta riñon" type: "income" value: 200 } ] for t in transactions MyCoins.transactionsCollection.create t $(document).ready -> window.MyCoins = {} MyCoins.setCurrentModalView = (view)-> if MyCoins.currentModalView MyCoins.currentModalView.remove() MyCoins.currentModalView.off() $("#app-modal").append view.render().el MyCoins.currentModalView = view MyCoins.setCurrentContentView = (view) -> if MyCoins.currentContentView MyCoins.currentContentView.remove() MyCoins.currentContentView.off() $("#app-content").append view.render().el MyCoins.currentContentView = view MyCoins.accountsCollection = new MyCoins.Collections.Accounts MyCoins.transactionCategoriesCollection = new MyCoins.Collections.TransactionCategories MyCoins.transactionsCollection = new MyCoins.Collections.Transactions MyCoins.budgetsCollection = new MyCoins.Collections.Budgets MyCoins.accountsCollection.fetch(reset: true) MyCoins.transactionCategoriesCollection.fetch(reset: true) MyCoins.transactionsCollection.fetch(reset: true) MyCoins.budgetsCollection.fetch(reset: true) # Lets create some fake data... just for fun ;) fakeData() sidebarView = new MyCoins.Views.Sidebar.ShowView $("#app-sidebar").append sidebarView.render().el $sidebarAccountWrapper = $("#sidebar-accounts-nav-wrapper") $sidebarAccountWrapper.width($sidebarAccountWrapper.width()).height($sidebarAccountWrapper.height()).perfectScrollbar() MyCoins.accountsRounter = new MyCoins.Routers.Accounts # Go! Backbone.history.start({pushState: true, root: "/#/"}) $(document).on 'click', 'a:not([data-bypass])', (evt)-> href = $(this).attr('href') protocol = this.protocol + '//' if (href.slice(protocol.length) != protocol) evt.preventDefault() Backbone.history.navigate(href, true) if MyCoins.accountsCollection.length > 0 Backbone.history.navigate("account/1/show", true) #MyCoins.accountsRounter.show MyCoins.accountsCollection.first().get("id") else newAccountView = new MyCoins.Views.Accounts.NewView collection: MyCoins.accountsCollection MyCoins.setCurrentContentView newAccountView
156760
fakeData = -> # Transaction Categories if not MyCoins.transactionCategoriesCollection.length transactionCategories = ["Bills", "Car", "Clothing", "Health", "Housing", "Others", "Restaurants", "Taxes", "Transport", "Travels"] for t in transactionCategories MyCoins.transactionCategoriesCollection.create name: t # Accounts and Transactions if not MyCoins.accountsCollection.length MyCoins.accountsCollection.create name: "Cuenta Personal" type: "cash" transactions = [ { accountId: 1 date: "2014-06-01T00:00:00.000-03:00" description: "<NAME>" type: "income" value: 4000 }, { accountId: 1 date: "2014-06-02T00:00:00.000-03:00" description: "<NAME>ivesap" type: "income" value: 500 }, { accountId: 1 date: "2014-06-03T00:00:00.000-03:00" description: "<NAME>" type: "expense" value: 1100 }, { accountId: 1 date: "2014-07-01T00:00:00.000-03:00" description: "<NAME>ue<NAME>" type: "income" value: 4000 }, { accountId: 1 date: "2014-07-02T00:00:00.000-03:00" description: "<NAME>" type: "expense" value: 8500 }, { accountId: 1 date: "2014-08-01T00:00:00.000-03:00" description: "<NAME>ueldo" type: "income" value: 4000 }, { accountId: 1 date: "2014-08-01T00:00:00.000-03:00" description: "Venta riñon" type: "income" value: 200 } ] for t in transactions MyCoins.transactionsCollection.create t $(document).ready -> window.MyCoins = {} MyCoins.setCurrentModalView = (view)-> if MyCoins.currentModalView MyCoins.currentModalView.remove() MyCoins.currentModalView.off() $("#app-modal").append view.render().el MyCoins.currentModalView = view MyCoins.setCurrentContentView = (view) -> if MyCoins.currentContentView MyCoins.currentContentView.remove() MyCoins.currentContentView.off() $("#app-content").append view.render().el MyCoins.currentContentView = view MyCoins.accountsCollection = new MyCoins.Collections.Accounts MyCoins.transactionCategoriesCollection = new MyCoins.Collections.TransactionCategories MyCoins.transactionsCollection = new MyCoins.Collections.Transactions MyCoins.budgetsCollection = new MyCoins.Collections.Budgets MyCoins.accountsCollection.fetch(reset: true) MyCoins.transactionCategoriesCollection.fetch(reset: true) MyCoins.transactionsCollection.fetch(reset: true) MyCoins.budgetsCollection.fetch(reset: true) # Lets create some fake data... just for fun ;) fakeData() sidebarView = new MyCoins.Views.Sidebar.ShowView $("#app-sidebar").append sidebarView.render().el $sidebarAccountWrapper = $("#sidebar-accounts-nav-wrapper") $sidebarAccountWrapper.width($sidebarAccountWrapper.width()).height($sidebarAccountWrapper.height()).perfectScrollbar() MyCoins.accountsRounter = new MyCoins.Routers.Accounts # Go! Backbone.history.start({pushState: true, root: "/#/"}) $(document).on 'click', 'a:not([data-bypass])', (evt)-> href = $(this).attr('href') protocol = this.protocol + '//' if (href.slice(protocol.length) != protocol) evt.preventDefault() Backbone.history.navigate(href, true) if MyCoins.accountsCollection.length > 0 Backbone.history.navigate("account/1/show", true) #MyCoins.accountsRounter.show MyCoins.accountsCollection.first().get("id") else newAccountView = new MyCoins.Views.Accounts.NewView collection: MyCoins.accountsCollection MyCoins.setCurrentContentView newAccountView
true
fakeData = -> # Transaction Categories if not MyCoins.transactionCategoriesCollection.length transactionCategories = ["Bills", "Car", "Clothing", "Health", "Housing", "Others", "Restaurants", "Taxes", "Transport", "Travels"] for t in transactionCategories MyCoins.transactionCategoriesCollection.create name: t # Accounts and Transactions if not MyCoins.accountsCollection.length MyCoins.accountsCollection.create name: "Cuenta Personal" type: "cash" transactions = [ { accountId: 1 date: "2014-06-01T00:00:00.000-03:00" description: "PI:NAME:<NAME>END_PI" type: "income" value: 4000 }, { accountId: 1 date: "2014-06-02T00:00:00.000-03:00" description: "PI:NAME:<NAME>END_PIivesap" type: "income" value: 500 }, { accountId: 1 date: "2014-06-03T00:00:00.000-03:00" description: "PI:NAME:<NAME>END_PI" type: "expense" value: 1100 }, { accountId: 1 date: "2014-07-01T00:00:00.000-03:00" description: "PI:NAME:<NAME>END_PIuePI:NAME:<NAME>END_PI" type: "income" value: 4000 }, { accountId: 1 date: "2014-07-02T00:00:00.000-03:00" description: "PI:NAME:<NAME>END_PI" type: "expense" value: 8500 }, { accountId: 1 date: "2014-08-01T00:00:00.000-03:00" description: "PI:NAME:<NAME>END_PIueldo" type: "income" value: 4000 }, { accountId: 1 date: "2014-08-01T00:00:00.000-03:00" description: "Venta riñon" type: "income" value: 200 } ] for t in transactions MyCoins.transactionsCollection.create t $(document).ready -> window.MyCoins = {} MyCoins.setCurrentModalView = (view)-> if MyCoins.currentModalView MyCoins.currentModalView.remove() MyCoins.currentModalView.off() $("#app-modal").append view.render().el MyCoins.currentModalView = view MyCoins.setCurrentContentView = (view) -> if MyCoins.currentContentView MyCoins.currentContentView.remove() MyCoins.currentContentView.off() $("#app-content").append view.render().el MyCoins.currentContentView = view MyCoins.accountsCollection = new MyCoins.Collections.Accounts MyCoins.transactionCategoriesCollection = new MyCoins.Collections.TransactionCategories MyCoins.transactionsCollection = new MyCoins.Collections.Transactions MyCoins.budgetsCollection = new MyCoins.Collections.Budgets MyCoins.accountsCollection.fetch(reset: true) MyCoins.transactionCategoriesCollection.fetch(reset: true) MyCoins.transactionsCollection.fetch(reset: true) MyCoins.budgetsCollection.fetch(reset: true) # Lets create some fake data... just for fun ;) fakeData() sidebarView = new MyCoins.Views.Sidebar.ShowView $("#app-sidebar").append sidebarView.render().el $sidebarAccountWrapper = $("#sidebar-accounts-nav-wrapper") $sidebarAccountWrapper.width($sidebarAccountWrapper.width()).height($sidebarAccountWrapper.height()).perfectScrollbar() MyCoins.accountsRounter = new MyCoins.Routers.Accounts # Go! Backbone.history.start({pushState: true, root: "/#/"}) $(document).on 'click', 'a:not([data-bypass])', (evt)-> href = $(this).attr('href') protocol = this.protocol + '//' if (href.slice(protocol.length) != protocol) evt.preventDefault() Backbone.history.navigate(href, true) if MyCoins.accountsCollection.length > 0 Backbone.history.navigate("account/1/show", true) #MyCoins.accountsRounter.show MyCoins.accountsCollection.first().get("id") else newAccountView = new MyCoins.Views.Accounts.NewView collection: MyCoins.accountsCollection MyCoins.setCurrentContentView newAccountView
[ { "context": " @$input = $('input[name=\"email\"]')\n .val 'barbaz@example.com'\n\n alertable { $input: @$input, message: \"Pl", "end": 472, "score": 0.9999257922172546, "start": 454, "tag": "EMAIL", "value": "barbaz@example.com" }, { "context": "ange your email.\" }, (value) ->\n value is 'foobar@example.com'\n\n it 'does nothing', ->\n $('.alertable-i", "end": 597, "score": 0.999925971031189, "start": 579, "tag": "EMAIL", "value": "foobar@example.com" }, { "context": " @$input = $('input[name=\"email\"]')\n .val 'foobar@example.com'\n\n alertable { $input: @$input, message: \"Pl", "end": 988, "score": 0.9999243021011353, "start": 970, "tag": "EMAIL", "value": "foobar@example.com" }, { "context": "ange your email.\" }, (value) ->\n value is 'foobar@example.com'\n\n it 'alerts you if the predicate passes, by ", "end": 1113, "score": 0.9999221563339233, "start": 1095, "tag": "EMAIL", "value": "foobar@example.com" }, { "context": " $input = $('input[name=\"email\"]')\n .val 'foobar@example.com'\n\n $submit = $('button')\n\n $submit.text", "end": 1686, "score": 0.9999244809150696, "start": 1668, "tag": "EMAIL", "value": "foobar@example.com" }, { "context": " you sure?'\n }, (value) ->\n value is 'foobar@example.com'\n\n $submit.text().should.equal 'Are you sure", "end": 1960, "score": 0.9998245239257812, "start": 1942, "tag": "EMAIL", "value": "foobar@example.com" } ]
src/desktop/components/alertable_input/test/index.coffee
kanaabe/force
1
benv = require 'benv' alertable = require '../index' describe 'alertable', -> before (done) -> benv.setup -> benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') done() after -> benv.teardown() beforeEach -> $('body').html ' <input name="email"> <button>Submit</button> ' describe 'not triggering alertable', -> beforeEach -> @$input = $('input[name="email"]') .val 'barbaz@example.com' alertable { $input: @$input, message: "Please change your email." }, (value) -> value is 'foobar@example.com' it 'does nothing', -> $('.alertable-input') .should.have.lengthOf 0 $('body').html() .should.not.containEql ' <div class="alertable-input" data-alert="Please change your email."><input name="email"></div> ' describe 'triggering alertable', -> beforeEach -> @$input = $('input[name="email"]') .val 'foobar@example.com' alertable { $input: @$input, message: "Please change your email." }, (value) -> value is 'foobar@example.com' it 'alerts you if the predicate passes, by wrapping the input and inserting the message', -> $('body').html() .should.containEql ' <div class="alertable-input" data-alert="Please change your email."><input name="email"></div> ' xit 'unwraps (and dismisses) the alert when the input is subsequently focused', -> console.log 'JSDOM + focus/blur is annoying. It works, trust me.' describe 'with submit button', -> it 'alters the button label', -> $input = $('input[name="email"]') .val 'foobar@example.com' $submit = $('button') $submit.text().should.equal 'Submit' alertable { $input: $input message: "Please change your email." $submit: $submit label: 'Are you sure?' }, (value) -> value is 'foobar@example.com' $submit.text().should.equal 'Are you sure?'
24649
benv = require 'benv' alertable = require '../index' describe 'alertable', -> before (done) -> benv.setup -> benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') done() after -> benv.teardown() beforeEach -> $('body').html ' <input name="email"> <button>Submit</button> ' describe 'not triggering alertable', -> beforeEach -> @$input = $('input[name="email"]') .val '<EMAIL>' alertable { $input: @$input, message: "Please change your email." }, (value) -> value is '<EMAIL>' it 'does nothing', -> $('.alertable-input') .should.have.lengthOf 0 $('body').html() .should.not.containEql ' <div class="alertable-input" data-alert="Please change your email."><input name="email"></div> ' describe 'triggering alertable', -> beforeEach -> @$input = $('input[name="email"]') .val '<EMAIL>' alertable { $input: @$input, message: "Please change your email." }, (value) -> value is '<EMAIL>' it 'alerts you if the predicate passes, by wrapping the input and inserting the message', -> $('body').html() .should.containEql ' <div class="alertable-input" data-alert="Please change your email."><input name="email"></div> ' xit 'unwraps (and dismisses) the alert when the input is subsequently focused', -> console.log 'JSDOM + focus/blur is annoying. It works, trust me.' describe 'with submit button', -> it 'alters the button label', -> $input = $('input[name="email"]') .val '<EMAIL>' $submit = $('button') $submit.text().should.equal 'Submit' alertable { $input: $input message: "Please change your email." $submit: $submit label: 'Are you sure?' }, (value) -> value is '<EMAIL>' $submit.text().should.equal 'Are you sure?'
true
benv = require 'benv' alertable = require '../index' describe 'alertable', -> before (done) -> benv.setup -> benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') done() after -> benv.teardown() beforeEach -> $('body').html ' <input name="email"> <button>Submit</button> ' describe 'not triggering alertable', -> beforeEach -> @$input = $('input[name="email"]') .val 'PI:EMAIL:<EMAIL>END_PI' alertable { $input: @$input, message: "Please change your email." }, (value) -> value is 'PI:EMAIL:<EMAIL>END_PI' it 'does nothing', -> $('.alertable-input') .should.have.lengthOf 0 $('body').html() .should.not.containEql ' <div class="alertable-input" data-alert="Please change your email."><input name="email"></div> ' describe 'triggering alertable', -> beforeEach -> @$input = $('input[name="email"]') .val 'PI:EMAIL:<EMAIL>END_PI' alertable { $input: @$input, message: "Please change your email." }, (value) -> value is 'PI:EMAIL:<EMAIL>END_PI' it 'alerts you if the predicate passes, by wrapping the input and inserting the message', -> $('body').html() .should.containEql ' <div class="alertable-input" data-alert="Please change your email."><input name="email"></div> ' xit 'unwraps (and dismisses) the alert when the input is subsequently focused', -> console.log 'JSDOM + focus/blur is annoying. It works, trust me.' describe 'with submit button', -> it 'alters the button label', -> $input = $('input[name="email"]') .val 'PI:EMAIL:<EMAIL>END_PI' $submit = $('button') $submit.text().should.equal 'Submit' alertable { $input: $input message: "Please change your email." $submit: $submit label: 'Are you sure?' }, (value) -> value is 'PI:EMAIL:<EMAIL>END_PI' $submit.text().should.equal 'Are you sure?'
[ { "context": "metadata.primaryKey}\": @config.model::attributes[@config.model.metadata.primaryKey].attributes.schema.required()\n\n plugins:\n ", "end": 18851, "score": 0.7329272031784058, "start": 18819, "tag": "EMAIL", "value": "config.model.metadata.primaryKey" } ]
src/views/modelView.coffee
BlackBalloon/hapi-simple-orm
2
'use strict' _ = require 'underscore' Joi = require 'joi' Boom = require 'boom' BaseView = require './baseView' moduleKeywords = ['extended', 'included'] require 'datejs' class ModelView extends BaseView @applyConfiguration: (obj) -> @::['config'] = {} for key, value of obj when key not in moduleKeywords @::['config'][key] = value obj.included?.apply(@) this # every 'ModelView' instance must obtain two params # @param [Object] server current server's instance # @param [Object] options options of current routing module constructor: (@server, @defaultOptions) -> # check if Model was specified in configuration attribute of the ModelView if @config? and not @config.model? throw new Error 'You must specify \'config.model\' class attribute of ModelView!' # server and options are required parameters if not @server? throw new Error 'You need to pass \'server\' instance to ModelView constructor!' # set default errorMessages attribute of configuration to empty object {} @config.errorMessages ?= {} # if the pluralName of Model was not specified, we simply append 's' to Model's name @config.pluralName ?= "#{@config.model.metadata.model}s" # if serializer was not specified in the configuration, set it to undefined @config.serializer ?= undefined super # extend defaultOptions with extraOptions # works recursively # @params [Object] defaultOptions defaultOptions of this ModelView # @params [Object] extraOptions additional options passed to route method __extendProperties: (defaultOptions, extraOptions) -> _.each extraOptions, (val, key) => if val? and val.constructor? and val.constructor.name is 'Object' and not (_.isEmpty val) defaultOptions[key] = defaultOptions[key] or {} @__extendProperties defaultOptions[key], val else defaultOptions[key] = val defaultOptions # method which is used to extend (or overwrite) current routing object # @param [Object] routeObject current route object and it's attributes # @param [Object] options options that will be used to extend/overwrite existing routeObject _extendRouteObject: (routeObject, options) -> if options? and _.isObject(options) # separately assign method and path attributes of the route, if they were passed routeObject.method = options.method or routeObject.method routeObject.path = options.path or routeObject.path # if 'options.config' passed to routing method is undefined, set it to empty object options.config ?= {} if (rejectedOptions = _.difference _.keys(options.config), @constructor.getAcceptableRouteOptions()).length > 0 throw new Error "Options #{rejectedOptions} are not accepted in route object!" # here we extend current route object with combination of 'defaultOptions' and 'options' # passed directly to the current routing method # result is full route configuration object # but first we need to create copy of 'defaultOptions' in order to omit reference problems defaultOptionsCopy = @__extendProperties {}, @defaultOptions @__extendProperties routeObject.config, (@__extendProperties(defaultOptionsCopy, _.clone(options.config))) # last check if the route object has config.handler method assigned if not (typeof routeObject.config.handler is 'function') # if not, throw an error throw new Error "The 'config.handler' attribute of route should be a function." # return extended/overwritten route object routeObject # validate if array of fields passed to the request include timestampAttributes and if they are not allowed # reply 400 bad request with appropriate message # @param [Array] fields array of fields passed as query params _validateReturningFields: (fields, reply) -> returningArray = _.clone fields if not @config.allowTimestampAttributes returningArray = _.difference(fields, _.keys(@config.model::timestampAttributes)) return returningArray # GET - return single instance of Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on the instance # @param [Object] options additional options which will extend/overwrite current route object get: (ifSerialize, serializer, options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'GET' path: "/#{@config.model.metadata.tableName}/{#{@config.model.metadata.primaryKey}}" config: description: "Return #{@config.model.metadata.model} with specified id" tags: @config.tags id: "return#{@config.model.metadata.model}" validate: params: "#{@config.model.metadata.primaryKey}": @config.model::attributes[@config.model.metadata.primaryKey].attributes.schema.required() query: fields: Joi.array().items(Joi.string()).single() plugins: 'hapi-swagger': responses: '200': 'description': 'Success' 'schema': Joi.object(@config.model.getSchema()).label(@config.model.metadata.model) '400': 'description': 'Bad request' '401': 'description': 'Unauthorized' '404': 'description': 'Not found' handler: (request, reply) => returning = if request.query.fields? then @_validateReturningFields(request.query.fields) else undefined @config.model.objects().getById({ pk: request.params.id, returning: returning }).then (result) => # if query returned any result and the 'ifSerialize' is set to true # use Serializer to return results if result? and ifSerialize serializerClass = if serializer then serializer else @config.serializer if not serializerClass? throw new Error "There is no serializer specified for #{@constructor.name}" serializerInstance = new serializerClass data: result serializerInstance.getData().then (serializerData) -> reply serializerData # otherwise if result was returned and 'ifSerialize' is false, simply return result else if result? and not ifSerialize reply result # if there is no result, return 404 not found error else if not result? reply Boom.notFound(@config.errorMessages['notFound'] or "#{@config.model.metadata.model} does not exist") .catch (error) -> reply Boom.badRequest error if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject # GET - return all instances of current Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on the instances # @param [Object] options additional options which will extend/overwrite current route object list: (ifSerialize, serializer, options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'GET' path: "/#{@config.model.metadata.tableName}" config: description: "Return all #{@config.pluralName}" tags: @config.tags id: "returnAll#{@config.pluralName}" validate: query: fields: Joi.array().items(Joi.string()).single() orderBy: Joi.string() limit: Joi.number().integer().positive() page: Joi.number().integer().positive() plugins: 'hapi-swagger': responses: '200': 'description': 'Success' 'schema': Joi.object({ items: Joi.array().items(@config.model.getSchema()) }).label(@config.pluralName) '400': 'description': 'Bad request' '401': 'description': 'Unauthorized' handler: (request, reply) => returning = if request.query.fields? then @_validateReturningFields(request.query.fields) else undefined # if query params include both 'limit' and 'page', then we use 'filterPaged' DAO operation if request.query.limit? and request.query.page? daoOperation = @config.model.objects().filterPaged({ returning: returning orderBy: request.query.orderBy limit: request.query.limit page: request.query.page }) # otherwise we simply perform 'all()' else daoOperation = @config.model.objects().all({ returning: returning }) daoOperation.then (objects) => if ifSerialize serializerClass = if serializer then serializer else @config.serializer if not serializerClass? throw new Error "There is no serializer specified for #{@constructor.name}" serializerInstance = new serializerClass data: objects, many: true serializerInstance.getData().then (serializerData) -> reply serializerData else if not ifSerialize reply objects .catch (error) -> reply Boom.badRequest error if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject # POST - create new instance of current Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on created instance # @param [Object] options additional options which will extend/overwrite current route object create: (ifSerialize, serializer, options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'POST' path: "/#{@config.model.metadata.tableName}" config: description: "Create new #{@config.model.metadata.model}" tags: @config.tags id: "addNew#{@config.model.metadata.model}" validate: payload: @config.model.getSchema() plugins: 'hapi-swagger': responses: '201': 'description': 'Created' 'schema': Joi.object(@config.model.getSchema()).label(@config.model.metadata.model) '400': 'description': 'Bad request/validation error' '401': 'description': 'Unauthorized' handler: (request, reply) => if request.auth.credentials? _.extend request.payload, { whoCreated: request.auth.credentials.user.id } @config.model.objects().create({ data: request.payload }).then (result) => if @config.mongoConf? and @config.mongoConf.mongoInstance? insertData = { model: @config.model.metadata.model module: @config.mongoConf.module || 'undefined' whoPerformed: if request.auth.credentials? then request.auth.credentials.user else 'undefined' action: 'create' payload: request.payload actionDate: new Date() userAgent: request.orig.headers['user-agent'] } currentModelCollection = @config.mongoConf.mongoInstance.db().collection(@config.model.metadata.collectionName) currentModelCollection.insert insertData, (error, value) => if error and @config.model.objects().errorLogger? @config.model.objects().errorLogger.error error if ifSerialize serializerClass = if serializer then serializer else @config.serializer if not serializerClass? throw new Error "There is no serializer specified for #{@constructor.name}" serializerInstance = new serializerClass data: result serializerInstance.getData().then (serializerData) -> reply(serializerData).code(201) else # publishObj = # action: 'add' # obj: result # @server.publish "/#{@config.model.metadata.tableName}", publishObj reply(result).code(201) .catch (error) => if error.error is 'ValidationError' return reply(error.fields).code(400) reply Boom.badRequest(error) if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject # PUT - update specified instance of current Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on updated instance # @param [Object] options additional options which will extend/overwrite current route object update: (ifSerialize, serializer, options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'PUT' path: "/#{@config.model.metadata.tableName}/{#{@config.model.metadata.primaryKey}}" config: description: "Update #{@config.model.metadata.model} with specified id" tags: @config.tags id: "update#{@config.model.metadata.model}" validate: params: "#{@config.model.metadata.primaryKey}": @config.model::attributes[@config.model.metadata.primaryKey].attributes.schema.required() payload: @config.model.getSchema() plugins: 'hapi-swagger': responses: '200': 'description': 'Updated' 'schema': Joi.object(@config.model.getSchema()).label(@config.model.metadata.model) '400': 'description': 'Bad request/validation error' '401': 'description': 'Unauthorized' '404': 'description': 'Not found' handler: (request, reply) => @config.model.objects().getById({ pk: request.params.id }).then (instance) => if instance? previousData = instance.toJSON { attributes: @config.model::fields } instance.set request.payload instance.save().then (result) => if @config.mongoConf? and @config.mongoConf.mongoInstance? insertData = { model: @config.model.metadata.model module: @config.mongoConf.module || 'undefined' whoPerformed: if request.auth.credentials? then request.auth.credentials.user else 'undefined' action: if request.route.method is 'put' then 'update' else 'partialUpdate' payload: request.payload previousData: previousData actionDate: new Date().addHours(2) userAgent: request.orig.headers['user-agent'] } currentModelCollection = @config.mongoConf.mongoInstance.db().collection(@config.model.metadata.collectionName) currentModelCollection.insert insertData, (error, value) => if error and @config.model.objects().config.errorLogger? @config.model.objects().config.errorLogger.error error if ifSerialize serializerClass = if serializer then serializer else @config.serializer if not serializerClass? throw new Error "There is no serializer specified for #{@constructor.name}" serializerInstance = new serializerClass data: result serializerInstance.getData().then (serializerData) -> reply serializerData else reply result .catch (error) => # if the error from DAO is of ValidationError class, then we simply return fields attribute of error if error.error is 'ValidationError' return reply(error.fields).code(400) return reply(Boom.badRequest(error)) else return reply Boom.notFound @config.errorMessages.notFound || "#{@config.model.metadata.model} does not exist" if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject # PATCH - perform partial update of specified instance of current Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on updated instance # @param [Object] options additional options which will extend/overwrite current route object partialUpdate: (ifSerialize, serializer, options) => routeObject = @update ifSerialize, serializer, options # it is necessary to change method to PATCH and both description and id of this route method # to prevent situation in which it overlaps with '.update()' method routeObject.method = 'PATCH' routeObject.config.description = "Partial update of #{@config.model.metadata.model}" routeObject.config.id = "partialUpdate#{@config.model.metadata.model}" # we set the 'partial' parameter of 'getSchema()' method to true # in order to return the schema without 'required' attribute for required fields # because PATCH allows to update only part of object (model's instance) routeObject.config.validate.payload = @config.model.getSchema(undefined, true) routeObject # DELETE - delete specified instance of current Model, returns 1 if DELETE was successfull # @param [Object] options additional options which will extend/overwrite current route object delete: (options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'DELETE' path: "/#{@config.model.metadata.tableName}/{#{@config.model.metadata.primaryKey}}" config: description: "Delete #{@config.model.metadata.model} with specified id" tags: @config.tags id: "delete#{@config.model.metadata.model}" validate: params: "#{@config.model.metadata.primaryKey}": @config.model::attributes[@config.model.metadata.primaryKey].attributes.schema.required() plugins: 'hapi-swagger': responses: '200': 'description': 'Deleted' '400': 'description': 'Bad request' '401': 'description': 'Unauthorized' '404': 'description': 'Not found' handler: (request, reply) => whoDeleted = if request.auth.credentials? then request.auth.credentials.user.id else undefined @config.model.objects().delete(request.params.id, whoDeleted).then (result) => if result is 1 if @config.mongoConf? and @config.mongoConf.mongoInstance? deleteDataSpecifics = {} deleteDataSpecifics[@config.model.metadata.primaryKey] = request.params.id deleteData = { model: @config.model.metadata.model module: @config.mongoConf.module || 'undefined' whoPerformed: if request.auth.credentials? then request.auth.credentials.user else 'undefined' action: 'delete' payload: request.params actionDate: new Date().addHours(2) userAgent: request.orig.headers['user-agent'] } currentModelCollection = @config.mongoConf.mongoInstance.db().collection(@config.model.metadata.collectionName) currentModelCollection.insert deleteData, (error, value) => if error and @config.model.objects().config.errorLogger? @config.model.objects().config.errorLogger.error error publishObj = action: 'delete' id: request.params.id @server.publish "/#{@config.model.metadata.tableName}", publishObj return reply result return reply Boom.notFound @config.errorMessages.notFound || "#{@config.model.metadata.model} does not exist!" .catch (error) => reply Boom.badRequest error if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject module.exports = ModelView
149361
'use strict' _ = require 'underscore' Joi = require 'joi' Boom = require 'boom' BaseView = require './baseView' moduleKeywords = ['extended', 'included'] require 'datejs' class ModelView extends BaseView @applyConfiguration: (obj) -> @::['config'] = {} for key, value of obj when key not in moduleKeywords @::['config'][key] = value obj.included?.apply(@) this # every 'ModelView' instance must obtain two params # @param [Object] server current server's instance # @param [Object] options options of current routing module constructor: (@server, @defaultOptions) -> # check if Model was specified in configuration attribute of the ModelView if @config? and not @config.model? throw new Error 'You must specify \'config.model\' class attribute of ModelView!' # server and options are required parameters if not @server? throw new Error 'You need to pass \'server\' instance to ModelView constructor!' # set default errorMessages attribute of configuration to empty object {} @config.errorMessages ?= {} # if the pluralName of Model was not specified, we simply append 's' to Model's name @config.pluralName ?= "#{@config.model.metadata.model}s" # if serializer was not specified in the configuration, set it to undefined @config.serializer ?= undefined super # extend defaultOptions with extraOptions # works recursively # @params [Object] defaultOptions defaultOptions of this ModelView # @params [Object] extraOptions additional options passed to route method __extendProperties: (defaultOptions, extraOptions) -> _.each extraOptions, (val, key) => if val? and val.constructor? and val.constructor.name is 'Object' and not (_.isEmpty val) defaultOptions[key] = defaultOptions[key] or {} @__extendProperties defaultOptions[key], val else defaultOptions[key] = val defaultOptions # method which is used to extend (or overwrite) current routing object # @param [Object] routeObject current route object and it's attributes # @param [Object] options options that will be used to extend/overwrite existing routeObject _extendRouteObject: (routeObject, options) -> if options? and _.isObject(options) # separately assign method and path attributes of the route, if they were passed routeObject.method = options.method or routeObject.method routeObject.path = options.path or routeObject.path # if 'options.config' passed to routing method is undefined, set it to empty object options.config ?= {} if (rejectedOptions = _.difference _.keys(options.config), @constructor.getAcceptableRouteOptions()).length > 0 throw new Error "Options #{rejectedOptions} are not accepted in route object!" # here we extend current route object with combination of 'defaultOptions' and 'options' # passed directly to the current routing method # result is full route configuration object # but first we need to create copy of 'defaultOptions' in order to omit reference problems defaultOptionsCopy = @__extendProperties {}, @defaultOptions @__extendProperties routeObject.config, (@__extendProperties(defaultOptionsCopy, _.clone(options.config))) # last check if the route object has config.handler method assigned if not (typeof routeObject.config.handler is 'function') # if not, throw an error throw new Error "The 'config.handler' attribute of route should be a function." # return extended/overwritten route object routeObject # validate if array of fields passed to the request include timestampAttributes and if they are not allowed # reply 400 bad request with appropriate message # @param [Array] fields array of fields passed as query params _validateReturningFields: (fields, reply) -> returningArray = _.clone fields if not @config.allowTimestampAttributes returningArray = _.difference(fields, _.keys(@config.model::timestampAttributes)) return returningArray # GET - return single instance of Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on the instance # @param [Object] options additional options which will extend/overwrite current route object get: (ifSerialize, serializer, options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'GET' path: "/#{@config.model.metadata.tableName}/{#{@config.model.metadata.primaryKey}}" config: description: "Return #{@config.model.metadata.model} with specified id" tags: @config.tags id: "return#{@config.model.metadata.model}" validate: params: "#{@config.model.metadata.primaryKey}": @config.model::attributes[@config.model.metadata.primaryKey].attributes.schema.required() query: fields: Joi.array().items(Joi.string()).single() plugins: 'hapi-swagger': responses: '200': 'description': 'Success' 'schema': Joi.object(@config.model.getSchema()).label(@config.model.metadata.model) '400': 'description': 'Bad request' '401': 'description': 'Unauthorized' '404': 'description': 'Not found' handler: (request, reply) => returning = if request.query.fields? then @_validateReturningFields(request.query.fields) else undefined @config.model.objects().getById({ pk: request.params.id, returning: returning }).then (result) => # if query returned any result and the 'ifSerialize' is set to true # use Serializer to return results if result? and ifSerialize serializerClass = if serializer then serializer else @config.serializer if not serializerClass? throw new Error "There is no serializer specified for #{@constructor.name}" serializerInstance = new serializerClass data: result serializerInstance.getData().then (serializerData) -> reply serializerData # otherwise if result was returned and 'ifSerialize' is false, simply return result else if result? and not ifSerialize reply result # if there is no result, return 404 not found error else if not result? reply Boom.notFound(@config.errorMessages['notFound'] or "#{@config.model.metadata.model} does not exist") .catch (error) -> reply Boom.badRequest error if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject # GET - return all instances of current Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on the instances # @param [Object] options additional options which will extend/overwrite current route object list: (ifSerialize, serializer, options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'GET' path: "/#{@config.model.metadata.tableName}" config: description: "Return all #{@config.pluralName}" tags: @config.tags id: "returnAll#{@config.pluralName}" validate: query: fields: Joi.array().items(Joi.string()).single() orderBy: Joi.string() limit: Joi.number().integer().positive() page: Joi.number().integer().positive() plugins: 'hapi-swagger': responses: '200': 'description': 'Success' 'schema': Joi.object({ items: Joi.array().items(@config.model.getSchema()) }).label(@config.pluralName) '400': 'description': 'Bad request' '401': 'description': 'Unauthorized' handler: (request, reply) => returning = if request.query.fields? then @_validateReturningFields(request.query.fields) else undefined # if query params include both 'limit' and 'page', then we use 'filterPaged' DAO operation if request.query.limit? and request.query.page? daoOperation = @config.model.objects().filterPaged({ returning: returning orderBy: request.query.orderBy limit: request.query.limit page: request.query.page }) # otherwise we simply perform 'all()' else daoOperation = @config.model.objects().all({ returning: returning }) daoOperation.then (objects) => if ifSerialize serializerClass = if serializer then serializer else @config.serializer if not serializerClass? throw new Error "There is no serializer specified for #{@constructor.name}" serializerInstance = new serializerClass data: objects, many: true serializerInstance.getData().then (serializerData) -> reply serializerData else if not ifSerialize reply objects .catch (error) -> reply Boom.badRequest error if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject # POST - create new instance of current Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on created instance # @param [Object] options additional options which will extend/overwrite current route object create: (ifSerialize, serializer, options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'POST' path: "/#{@config.model.metadata.tableName}" config: description: "Create new #{@config.model.metadata.model}" tags: @config.tags id: "addNew#{@config.model.metadata.model}" validate: payload: @config.model.getSchema() plugins: 'hapi-swagger': responses: '201': 'description': 'Created' 'schema': Joi.object(@config.model.getSchema()).label(@config.model.metadata.model) '400': 'description': 'Bad request/validation error' '401': 'description': 'Unauthorized' handler: (request, reply) => if request.auth.credentials? _.extend request.payload, { whoCreated: request.auth.credentials.user.id } @config.model.objects().create({ data: request.payload }).then (result) => if @config.mongoConf? and @config.mongoConf.mongoInstance? insertData = { model: @config.model.metadata.model module: @config.mongoConf.module || 'undefined' whoPerformed: if request.auth.credentials? then request.auth.credentials.user else 'undefined' action: 'create' payload: request.payload actionDate: new Date() userAgent: request.orig.headers['user-agent'] } currentModelCollection = @config.mongoConf.mongoInstance.db().collection(@config.model.metadata.collectionName) currentModelCollection.insert insertData, (error, value) => if error and @config.model.objects().errorLogger? @config.model.objects().errorLogger.error error if ifSerialize serializerClass = if serializer then serializer else @config.serializer if not serializerClass? throw new Error "There is no serializer specified for #{@constructor.name}" serializerInstance = new serializerClass data: result serializerInstance.getData().then (serializerData) -> reply(serializerData).code(201) else # publishObj = # action: 'add' # obj: result # @server.publish "/#{@config.model.metadata.tableName}", publishObj reply(result).code(201) .catch (error) => if error.error is 'ValidationError' return reply(error.fields).code(400) reply Boom.badRequest(error) if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject # PUT - update specified instance of current Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on updated instance # @param [Object] options additional options which will extend/overwrite current route object update: (ifSerialize, serializer, options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'PUT' path: "/#{@config.model.metadata.tableName}/{#{@config.model.metadata.primaryKey}}" config: description: "Update #{@config.model.metadata.model} with specified id" tags: @config.tags id: "update#{@config.model.metadata.model}" validate: params: "#{@config.model.metadata.primaryKey}": @config.model::attributes[@config.model.metadata.primaryKey].attributes.schema.required() payload: @config.model.getSchema() plugins: 'hapi-swagger': responses: '200': 'description': 'Updated' 'schema': Joi.object(@config.model.getSchema()).label(@config.model.metadata.model) '400': 'description': 'Bad request/validation error' '401': 'description': 'Unauthorized' '404': 'description': 'Not found' handler: (request, reply) => @config.model.objects().getById({ pk: request.params.id }).then (instance) => if instance? previousData = instance.toJSON { attributes: @config.model::fields } instance.set request.payload instance.save().then (result) => if @config.mongoConf? and @config.mongoConf.mongoInstance? insertData = { model: @config.model.metadata.model module: @config.mongoConf.module || 'undefined' whoPerformed: if request.auth.credentials? then request.auth.credentials.user else 'undefined' action: if request.route.method is 'put' then 'update' else 'partialUpdate' payload: request.payload previousData: previousData actionDate: new Date().addHours(2) userAgent: request.orig.headers['user-agent'] } currentModelCollection = @config.mongoConf.mongoInstance.db().collection(@config.model.metadata.collectionName) currentModelCollection.insert insertData, (error, value) => if error and @config.model.objects().config.errorLogger? @config.model.objects().config.errorLogger.error error if ifSerialize serializerClass = if serializer then serializer else @config.serializer if not serializerClass? throw new Error "There is no serializer specified for #{@constructor.name}" serializerInstance = new serializerClass data: result serializerInstance.getData().then (serializerData) -> reply serializerData else reply result .catch (error) => # if the error from DAO is of ValidationError class, then we simply return fields attribute of error if error.error is 'ValidationError' return reply(error.fields).code(400) return reply(Boom.badRequest(error)) else return reply Boom.notFound @config.errorMessages.notFound || "#{@config.model.metadata.model} does not exist" if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject # PATCH - perform partial update of specified instance of current Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on updated instance # @param [Object] options additional options which will extend/overwrite current route object partialUpdate: (ifSerialize, serializer, options) => routeObject = @update ifSerialize, serializer, options # it is necessary to change method to PATCH and both description and id of this route method # to prevent situation in which it overlaps with '.update()' method routeObject.method = 'PATCH' routeObject.config.description = "Partial update of #{@config.model.metadata.model}" routeObject.config.id = "partialUpdate#{@config.model.metadata.model}" # we set the 'partial' parameter of 'getSchema()' method to true # in order to return the schema without 'required' attribute for required fields # because PATCH allows to update only part of object (model's instance) routeObject.config.validate.payload = @config.model.getSchema(undefined, true) routeObject # DELETE - delete specified instance of current Model, returns 1 if DELETE was successfull # @param [Object] options additional options which will extend/overwrite current route object delete: (options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'DELETE' path: "/#{@config.model.metadata.tableName}/{#{@config.model.metadata.primaryKey}}" config: description: "Delete #{@config.model.metadata.model} with specified id" tags: @config.tags id: "delete#{@config.model.metadata.model}" validate: params: "#{@config.model.metadata.primaryKey}": @config.model::attributes[@<EMAIL>].attributes.schema.required() plugins: 'hapi-swagger': responses: '200': 'description': 'Deleted' '400': 'description': 'Bad request' '401': 'description': 'Unauthorized' '404': 'description': 'Not found' handler: (request, reply) => whoDeleted = if request.auth.credentials? then request.auth.credentials.user.id else undefined @config.model.objects().delete(request.params.id, whoDeleted).then (result) => if result is 1 if @config.mongoConf? and @config.mongoConf.mongoInstance? deleteDataSpecifics = {} deleteDataSpecifics[@config.model.metadata.primaryKey] = request.params.id deleteData = { model: @config.model.metadata.model module: @config.mongoConf.module || 'undefined' whoPerformed: if request.auth.credentials? then request.auth.credentials.user else 'undefined' action: 'delete' payload: request.params actionDate: new Date().addHours(2) userAgent: request.orig.headers['user-agent'] } currentModelCollection = @config.mongoConf.mongoInstance.db().collection(@config.model.metadata.collectionName) currentModelCollection.insert deleteData, (error, value) => if error and @config.model.objects().config.errorLogger? @config.model.objects().config.errorLogger.error error publishObj = action: 'delete' id: request.params.id @server.publish "/#{@config.model.metadata.tableName}", publishObj return reply result return reply Boom.notFound @config.errorMessages.notFound || "#{@config.model.metadata.model} does not exist!" .catch (error) => reply Boom.badRequest error if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject module.exports = ModelView
true
'use strict' _ = require 'underscore' Joi = require 'joi' Boom = require 'boom' BaseView = require './baseView' moduleKeywords = ['extended', 'included'] require 'datejs' class ModelView extends BaseView @applyConfiguration: (obj) -> @::['config'] = {} for key, value of obj when key not in moduleKeywords @::['config'][key] = value obj.included?.apply(@) this # every 'ModelView' instance must obtain two params # @param [Object] server current server's instance # @param [Object] options options of current routing module constructor: (@server, @defaultOptions) -> # check if Model was specified in configuration attribute of the ModelView if @config? and not @config.model? throw new Error 'You must specify \'config.model\' class attribute of ModelView!' # server and options are required parameters if not @server? throw new Error 'You need to pass \'server\' instance to ModelView constructor!' # set default errorMessages attribute of configuration to empty object {} @config.errorMessages ?= {} # if the pluralName of Model was not specified, we simply append 's' to Model's name @config.pluralName ?= "#{@config.model.metadata.model}s" # if serializer was not specified in the configuration, set it to undefined @config.serializer ?= undefined super # extend defaultOptions with extraOptions # works recursively # @params [Object] defaultOptions defaultOptions of this ModelView # @params [Object] extraOptions additional options passed to route method __extendProperties: (defaultOptions, extraOptions) -> _.each extraOptions, (val, key) => if val? and val.constructor? and val.constructor.name is 'Object' and not (_.isEmpty val) defaultOptions[key] = defaultOptions[key] or {} @__extendProperties defaultOptions[key], val else defaultOptions[key] = val defaultOptions # method which is used to extend (or overwrite) current routing object # @param [Object] routeObject current route object and it's attributes # @param [Object] options options that will be used to extend/overwrite existing routeObject _extendRouteObject: (routeObject, options) -> if options? and _.isObject(options) # separately assign method and path attributes of the route, if they were passed routeObject.method = options.method or routeObject.method routeObject.path = options.path or routeObject.path # if 'options.config' passed to routing method is undefined, set it to empty object options.config ?= {} if (rejectedOptions = _.difference _.keys(options.config), @constructor.getAcceptableRouteOptions()).length > 0 throw new Error "Options #{rejectedOptions} are not accepted in route object!" # here we extend current route object with combination of 'defaultOptions' and 'options' # passed directly to the current routing method # result is full route configuration object # but first we need to create copy of 'defaultOptions' in order to omit reference problems defaultOptionsCopy = @__extendProperties {}, @defaultOptions @__extendProperties routeObject.config, (@__extendProperties(defaultOptionsCopy, _.clone(options.config))) # last check if the route object has config.handler method assigned if not (typeof routeObject.config.handler is 'function') # if not, throw an error throw new Error "The 'config.handler' attribute of route should be a function." # return extended/overwritten route object routeObject # validate if array of fields passed to the request include timestampAttributes and if they are not allowed # reply 400 bad request with appropriate message # @param [Array] fields array of fields passed as query params _validateReturningFields: (fields, reply) -> returningArray = _.clone fields if not @config.allowTimestampAttributes returningArray = _.difference(fields, _.keys(@config.model::timestampAttributes)) return returningArray # GET - return single instance of Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on the instance # @param [Object] options additional options which will extend/overwrite current route object get: (ifSerialize, serializer, options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'GET' path: "/#{@config.model.metadata.tableName}/{#{@config.model.metadata.primaryKey}}" config: description: "Return #{@config.model.metadata.model} with specified id" tags: @config.tags id: "return#{@config.model.metadata.model}" validate: params: "#{@config.model.metadata.primaryKey}": @config.model::attributes[@config.model.metadata.primaryKey].attributes.schema.required() query: fields: Joi.array().items(Joi.string()).single() plugins: 'hapi-swagger': responses: '200': 'description': 'Success' 'schema': Joi.object(@config.model.getSchema()).label(@config.model.metadata.model) '400': 'description': 'Bad request' '401': 'description': 'Unauthorized' '404': 'description': 'Not found' handler: (request, reply) => returning = if request.query.fields? then @_validateReturningFields(request.query.fields) else undefined @config.model.objects().getById({ pk: request.params.id, returning: returning }).then (result) => # if query returned any result and the 'ifSerialize' is set to true # use Serializer to return results if result? and ifSerialize serializerClass = if serializer then serializer else @config.serializer if not serializerClass? throw new Error "There is no serializer specified for #{@constructor.name}" serializerInstance = new serializerClass data: result serializerInstance.getData().then (serializerData) -> reply serializerData # otherwise if result was returned and 'ifSerialize' is false, simply return result else if result? and not ifSerialize reply result # if there is no result, return 404 not found error else if not result? reply Boom.notFound(@config.errorMessages['notFound'] or "#{@config.model.metadata.model} does not exist") .catch (error) -> reply Boom.badRequest error if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject # GET - return all instances of current Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on the instances # @param [Object] options additional options which will extend/overwrite current route object list: (ifSerialize, serializer, options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'GET' path: "/#{@config.model.metadata.tableName}" config: description: "Return all #{@config.pluralName}" tags: @config.tags id: "returnAll#{@config.pluralName}" validate: query: fields: Joi.array().items(Joi.string()).single() orderBy: Joi.string() limit: Joi.number().integer().positive() page: Joi.number().integer().positive() plugins: 'hapi-swagger': responses: '200': 'description': 'Success' 'schema': Joi.object({ items: Joi.array().items(@config.model.getSchema()) }).label(@config.pluralName) '400': 'description': 'Bad request' '401': 'description': 'Unauthorized' handler: (request, reply) => returning = if request.query.fields? then @_validateReturningFields(request.query.fields) else undefined # if query params include both 'limit' and 'page', then we use 'filterPaged' DAO operation if request.query.limit? and request.query.page? daoOperation = @config.model.objects().filterPaged({ returning: returning orderBy: request.query.orderBy limit: request.query.limit page: request.query.page }) # otherwise we simply perform 'all()' else daoOperation = @config.model.objects().all({ returning: returning }) daoOperation.then (objects) => if ifSerialize serializerClass = if serializer then serializer else @config.serializer if not serializerClass? throw new Error "There is no serializer specified for #{@constructor.name}" serializerInstance = new serializerClass data: objects, many: true serializerInstance.getData().then (serializerData) -> reply serializerData else if not ifSerialize reply objects .catch (error) -> reply Boom.badRequest error if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject # POST - create new instance of current Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on created instance # @param [Object] options additional options which will extend/overwrite current route object create: (ifSerialize, serializer, options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'POST' path: "/#{@config.model.metadata.tableName}" config: description: "Create new #{@config.model.metadata.model}" tags: @config.tags id: "addNew#{@config.model.metadata.model}" validate: payload: @config.model.getSchema() plugins: 'hapi-swagger': responses: '201': 'description': 'Created' 'schema': Joi.object(@config.model.getSchema()).label(@config.model.metadata.model) '400': 'description': 'Bad request/validation error' '401': 'description': 'Unauthorized' handler: (request, reply) => if request.auth.credentials? _.extend request.payload, { whoCreated: request.auth.credentials.user.id } @config.model.objects().create({ data: request.payload }).then (result) => if @config.mongoConf? and @config.mongoConf.mongoInstance? insertData = { model: @config.model.metadata.model module: @config.mongoConf.module || 'undefined' whoPerformed: if request.auth.credentials? then request.auth.credentials.user else 'undefined' action: 'create' payload: request.payload actionDate: new Date() userAgent: request.orig.headers['user-agent'] } currentModelCollection = @config.mongoConf.mongoInstance.db().collection(@config.model.metadata.collectionName) currentModelCollection.insert insertData, (error, value) => if error and @config.model.objects().errorLogger? @config.model.objects().errorLogger.error error if ifSerialize serializerClass = if serializer then serializer else @config.serializer if not serializerClass? throw new Error "There is no serializer specified for #{@constructor.name}" serializerInstance = new serializerClass data: result serializerInstance.getData().then (serializerData) -> reply(serializerData).code(201) else # publishObj = # action: 'add' # obj: result # @server.publish "/#{@config.model.metadata.tableName}", publishObj reply(result).code(201) .catch (error) => if error.error is 'ValidationError' return reply(error.fields).code(400) reply Boom.badRequest(error) if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject # PUT - update specified instance of current Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on updated instance # @param [Object] options additional options which will extend/overwrite current route object update: (ifSerialize, serializer, options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'PUT' path: "/#{@config.model.metadata.tableName}/{#{@config.model.metadata.primaryKey}}" config: description: "Update #{@config.model.metadata.model} with specified id" tags: @config.tags id: "update#{@config.model.metadata.model}" validate: params: "#{@config.model.metadata.primaryKey}": @config.model::attributes[@config.model.metadata.primaryKey].attributes.schema.required() payload: @config.model.getSchema() plugins: 'hapi-swagger': responses: '200': 'description': 'Updated' 'schema': Joi.object(@config.model.getSchema()).label(@config.model.metadata.model) '400': 'description': 'Bad request/validation error' '401': 'description': 'Unauthorized' '404': 'description': 'Not found' handler: (request, reply) => @config.model.objects().getById({ pk: request.params.id }).then (instance) => if instance? previousData = instance.toJSON { attributes: @config.model::fields } instance.set request.payload instance.save().then (result) => if @config.mongoConf? and @config.mongoConf.mongoInstance? insertData = { model: @config.model.metadata.model module: @config.mongoConf.module || 'undefined' whoPerformed: if request.auth.credentials? then request.auth.credentials.user else 'undefined' action: if request.route.method is 'put' then 'update' else 'partialUpdate' payload: request.payload previousData: previousData actionDate: new Date().addHours(2) userAgent: request.orig.headers['user-agent'] } currentModelCollection = @config.mongoConf.mongoInstance.db().collection(@config.model.metadata.collectionName) currentModelCollection.insert insertData, (error, value) => if error and @config.model.objects().config.errorLogger? @config.model.objects().config.errorLogger.error error if ifSerialize serializerClass = if serializer then serializer else @config.serializer if not serializerClass? throw new Error "There is no serializer specified for #{@constructor.name}" serializerInstance = new serializerClass data: result serializerInstance.getData().then (serializerData) -> reply serializerData else reply result .catch (error) => # if the error from DAO is of ValidationError class, then we simply return fields attribute of error if error.error is 'ValidationError' return reply(error.fields).code(400) return reply(Boom.badRequest(error)) else return reply Boom.notFound @config.errorMessages.notFound || "#{@config.model.metadata.model} does not exist" if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject # PATCH - perform partial update of specified instance of current Model # @param [Boolean] ifSerialize boolean which defines if result should be serialized # @param [Object] serializer serializer's Class to be used on updated instance # @param [Object] options additional options which will extend/overwrite current route object partialUpdate: (ifSerialize, serializer, options) => routeObject = @update ifSerialize, serializer, options # it is necessary to change method to PATCH and both description and id of this route method # to prevent situation in which it overlaps with '.update()' method routeObject.method = 'PATCH' routeObject.config.description = "Partial update of #{@config.model.metadata.model}" routeObject.config.id = "partialUpdate#{@config.model.metadata.model}" # we set the 'partial' parameter of 'getSchema()' method to true # in order to return the schema without 'required' attribute for required fields # because PATCH allows to update only part of object (model's instance) routeObject.config.validate.payload = @config.model.getSchema(undefined, true) routeObject # DELETE - delete specified instance of current Model, returns 1 if DELETE was successfull # @param [Object] options additional options which will extend/overwrite current route object delete: (options) => if options? and not (_.isObject options) throw new Error "'options' parameter of routing method should be an object" options ?= { config: {} } routeObject = method: 'DELETE' path: "/#{@config.model.metadata.tableName}/{#{@config.model.metadata.primaryKey}}" config: description: "Delete #{@config.model.metadata.model} with specified id" tags: @config.tags id: "delete#{@config.model.metadata.model}" validate: params: "#{@config.model.metadata.primaryKey}": @config.model::attributes[@PI:EMAIL:<EMAIL>END_PI].attributes.schema.required() plugins: 'hapi-swagger': responses: '200': 'description': 'Deleted' '400': 'description': 'Bad request' '401': 'description': 'Unauthorized' '404': 'description': 'Not found' handler: (request, reply) => whoDeleted = if request.auth.credentials? then request.auth.credentials.user.id else undefined @config.model.objects().delete(request.params.id, whoDeleted).then (result) => if result is 1 if @config.mongoConf? and @config.mongoConf.mongoInstance? deleteDataSpecifics = {} deleteDataSpecifics[@config.model.metadata.primaryKey] = request.params.id deleteData = { model: @config.model.metadata.model module: @config.mongoConf.module || 'undefined' whoPerformed: if request.auth.credentials? then request.auth.credentials.user else 'undefined' action: 'delete' payload: request.params actionDate: new Date().addHours(2) userAgent: request.orig.headers['user-agent'] } currentModelCollection = @config.mongoConf.mongoInstance.db().collection(@config.model.metadata.collectionName) currentModelCollection.insert deleteData, (error, value) => if error and @config.model.objects().config.errorLogger? @config.model.objects().config.errorLogger.error error publishObj = action: 'delete' id: request.params.id @server.publish "/#{@config.model.metadata.tableName}", publishObj return reply result return reply Boom.notFound @config.errorMessages.notFound || "#{@config.model.metadata.model} does not exist!" .catch (error) => reply Boom.badRequest error if options? and _.isObject(options) @_extendRouteObject routeObject, options routeObject module.exports = ModelView
[ { "context": " port: process.env.REDIS_PORT\n pass: process.env.REDIS_PASSWORD\n db: process.env.REDIS_DBID", "end": 633, "score": 0.807610809803009, "start": 622, "tag": "PASSWORD", "value": "process.env" } ]
player/src/app.coffee
setpixel/storyboard-fountain
148
util = require('util') module.exports = { app: null initialize: (next) -> express = require('express') logfmt = require('logfmt') flash = require('connect-flash') app = express() busboy = require('connect-busboy') session = require('express-session') RedisStore = require('connect-redis')(session) helpers = require('./req_helpers') #app.use(helpers.startTimer) app.use(logfmt.requestLogger()) app.use(require('cookie-parser')()) app.use(session({ store: new RedisStore({ host: process.env.REDIS_HOST port: process.env.REDIS_PORT pass: process.env.REDIS_PASSWORD db: process.env.REDIS_DBID ttl: 30 * 24 * 60 * 60 # 30 days }) secret: process.env.SESSION_SECRET })) app.use(flash()) app.use (req, res, next) -> req.current ?= {} req.current.url = req.url res.locals.current = req.current next() app.set('views', "#{__dirname}/../views") app.set('view engine', 'jade') app.use(express.static("#{__dirname}/../public")) app.use(busboy()) app.get '/', (req, res) -> res.send 'storyboard-fountain player' require('./controllers').initialize(app) module.exports.app = app next(app) }
83139
util = require('util') module.exports = { app: null initialize: (next) -> express = require('express') logfmt = require('logfmt') flash = require('connect-flash') app = express() busboy = require('connect-busboy') session = require('express-session') RedisStore = require('connect-redis')(session) helpers = require('./req_helpers') #app.use(helpers.startTimer) app.use(logfmt.requestLogger()) app.use(require('cookie-parser')()) app.use(session({ store: new RedisStore({ host: process.env.REDIS_HOST port: process.env.REDIS_PORT pass: <PASSWORD>.REDIS_PASSWORD db: process.env.REDIS_DBID ttl: 30 * 24 * 60 * 60 # 30 days }) secret: process.env.SESSION_SECRET })) app.use(flash()) app.use (req, res, next) -> req.current ?= {} req.current.url = req.url res.locals.current = req.current next() app.set('views', "#{__dirname}/../views") app.set('view engine', 'jade') app.use(express.static("#{__dirname}/../public")) app.use(busboy()) app.get '/', (req, res) -> res.send 'storyboard-fountain player' require('./controllers').initialize(app) module.exports.app = app next(app) }
true
util = require('util') module.exports = { app: null initialize: (next) -> express = require('express') logfmt = require('logfmt') flash = require('connect-flash') app = express() busboy = require('connect-busboy') session = require('express-session') RedisStore = require('connect-redis')(session) helpers = require('./req_helpers') #app.use(helpers.startTimer) app.use(logfmt.requestLogger()) app.use(require('cookie-parser')()) app.use(session({ store: new RedisStore({ host: process.env.REDIS_HOST port: process.env.REDIS_PORT pass: PI:PASSWORD:<PASSWORD>END_PI.REDIS_PASSWORD db: process.env.REDIS_DBID ttl: 30 * 24 * 60 * 60 # 30 days }) secret: process.env.SESSION_SECRET })) app.use(flash()) app.use (req, res, next) -> req.current ?= {} req.current.url = req.url res.locals.current = req.current next() app.set('views', "#{__dirname}/../views") app.set('view engine', 'jade') app.use(express.static("#{__dirname}/../public")) app.use(busboy()) app.get '/', (req, res) -> res.send 'storyboard-fountain player' require('./controllers').initialize(app) module.exports.app = app next(app) }
[ { "context": "alues, callback) ->\n callback(200, id: 'token123')\n\n browser.payment = browser.window.jQuery('p", "end": 348, "score": 0.5188608765602112, "start": 345, "tag": "PASSWORD", "value": "123" } ]
test/index.coffee
stripe-archive/payment-tag
5
zombie = require 'zombie' path = require 'path' vows = require 'vows' assert = require 'assert' browser = (callback) -> zombie.visit "file://#{__dirname}/index.html", (err, browser) => throw err if err browser.window.console.error = -> browser.window.Stripe.createToken = (values, callback) -> callback(200, id: 'token123') browser.payment = browser.window.jQuery('payment') (callback or @callback).call(this, null, browser) undefined browserContext = (test) -> context = {} context.topic = browser context['browser'] = test context vows.describe('PaymentTag').addBatch( 'should be present': browserContext (browser) -> assert browser.window.PaymentTag? 'should add inputs to payment': browserContext (browser) -> assert.equal browser.payment.find('input').length, 4 'should add token input to payment on submit': browserContext (browser) -> browser.payment.find('.number input').val('4242424242424242') browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('2040') browser.payment.find('.cvc input').val('123') form = browser.payment.parents('form') form.submit() assert.equal form.find('input[name=stripeToken]').val(), 'token123' 'should call Stripe.createToken with correct arguments': topic: -> browser (err, browser) => browser.window.Stripe.createToken = (values, _) => @callback(null, values) browser.payment.find('.number input').val('4242424242424242') browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('18') browser.payment.find('.cvc input').val('123') form = browser.payment.parents('form') form.submit() 'number': (values) -> assert.equal values.number, '4242424242424242' 'expiry': (values) -> assert.equal values.exp_month, '05' assert.equal values.exp_year, '2018' 'cvc': (values) -> assert.equal values.cvc, '123' 'should disable inputs on submit': browserContext (browser) -> browser.window.Stripe.createToken = -> browser.payment.find('.number input').val('4242424242424242') browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('2040') browser.payment.find('.cvc input').val('123') form = browser.payment.parents('form') form.submit() assert.equal form.find(':input:disabled').length, 5 'should validate CC number': topic: browser 'presence': (browser) -> browser.payment.find('.number input').val('4242424242424243') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.number input').hasClass('invalid') 'luhn': (browser) -> browser.payment.find('.number input').val('4242424242424243') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.number input').hasClass('invalid') 'valid': (browser) -> browser.payment.find('.number input').val('4242424242424242') form = browser.payment.parents('form') form.submit() assert not browser.payment.find('.number').hasClass('invalid') 'should validate expiry': topic: browser 'presence': (browser) -> browser.payment.find('.number input').val('ddd') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.number input').hasClass('invalid') 'numbers': (browser) -> browser.payment.find('input.expiryMonth').val('ddd') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.number input').hasClass('invalid') 'expiry': (browser) -> browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('2001') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.expiry input.expiryYear').hasClass('invalid') 'valid': (browser) -> browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('2040') form = browser.payment.parents('form') form.submit() assert not browser.payment.find('.expiry').hasClass('invalid') 'should validate cvc': topic: browser 'presence': (browser) -> browser.payment.find('.cvc input').val('') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.cvc input').hasClass('invalid') 'length': (browser) -> browser.payment.find('.cvc input').val('919812') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.cvc input').hasClass('invalid') 'valid': (browser) -> browser.payment.find('.cvc input').val('123') form = browser.payment.parents('form') form.submit() assert not browser.payment.find('.cvc input').hasClass('invalid') ).run()
27346
zombie = require 'zombie' path = require 'path' vows = require 'vows' assert = require 'assert' browser = (callback) -> zombie.visit "file://#{__dirname}/index.html", (err, browser) => throw err if err browser.window.console.error = -> browser.window.Stripe.createToken = (values, callback) -> callback(200, id: 'token<PASSWORD>') browser.payment = browser.window.jQuery('payment') (callback or @callback).call(this, null, browser) undefined browserContext = (test) -> context = {} context.topic = browser context['browser'] = test context vows.describe('PaymentTag').addBatch( 'should be present': browserContext (browser) -> assert browser.window.PaymentTag? 'should add inputs to payment': browserContext (browser) -> assert.equal browser.payment.find('input').length, 4 'should add token input to payment on submit': browserContext (browser) -> browser.payment.find('.number input').val('4242424242424242') browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('2040') browser.payment.find('.cvc input').val('123') form = browser.payment.parents('form') form.submit() assert.equal form.find('input[name=stripeToken]').val(), 'token123' 'should call Stripe.createToken with correct arguments': topic: -> browser (err, browser) => browser.window.Stripe.createToken = (values, _) => @callback(null, values) browser.payment.find('.number input').val('4242424242424242') browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('18') browser.payment.find('.cvc input').val('123') form = browser.payment.parents('form') form.submit() 'number': (values) -> assert.equal values.number, '4242424242424242' 'expiry': (values) -> assert.equal values.exp_month, '05' assert.equal values.exp_year, '2018' 'cvc': (values) -> assert.equal values.cvc, '123' 'should disable inputs on submit': browserContext (browser) -> browser.window.Stripe.createToken = -> browser.payment.find('.number input').val('4242424242424242') browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('2040') browser.payment.find('.cvc input').val('123') form = browser.payment.parents('form') form.submit() assert.equal form.find(':input:disabled').length, 5 'should validate CC number': topic: browser 'presence': (browser) -> browser.payment.find('.number input').val('4242424242424243') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.number input').hasClass('invalid') 'luhn': (browser) -> browser.payment.find('.number input').val('4242424242424243') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.number input').hasClass('invalid') 'valid': (browser) -> browser.payment.find('.number input').val('4242424242424242') form = browser.payment.parents('form') form.submit() assert not browser.payment.find('.number').hasClass('invalid') 'should validate expiry': topic: browser 'presence': (browser) -> browser.payment.find('.number input').val('ddd') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.number input').hasClass('invalid') 'numbers': (browser) -> browser.payment.find('input.expiryMonth').val('ddd') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.number input').hasClass('invalid') 'expiry': (browser) -> browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('2001') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.expiry input.expiryYear').hasClass('invalid') 'valid': (browser) -> browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('2040') form = browser.payment.parents('form') form.submit() assert not browser.payment.find('.expiry').hasClass('invalid') 'should validate cvc': topic: browser 'presence': (browser) -> browser.payment.find('.cvc input').val('') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.cvc input').hasClass('invalid') 'length': (browser) -> browser.payment.find('.cvc input').val('919812') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.cvc input').hasClass('invalid') 'valid': (browser) -> browser.payment.find('.cvc input').val('123') form = browser.payment.parents('form') form.submit() assert not browser.payment.find('.cvc input').hasClass('invalid') ).run()
true
zombie = require 'zombie' path = require 'path' vows = require 'vows' assert = require 'assert' browser = (callback) -> zombie.visit "file://#{__dirname}/index.html", (err, browser) => throw err if err browser.window.console.error = -> browser.window.Stripe.createToken = (values, callback) -> callback(200, id: 'tokenPI:PASSWORD:<PASSWORD>END_PI') browser.payment = browser.window.jQuery('payment') (callback or @callback).call(this, null, browser) undefined browserContext = (test) -> context = {} context.topic = browser context['browser'] = test context vows.describe('PaymentTag').addBatch( 'should be present': browserContext (browser) -> assert browser.window.PaymentTag? 'should add inputs to payment': browserContext (browser) -> assert.equal browser.payment.find('input').length, 4 'should add token input to payment on submit': browserContext (browser) -> browser.payment.find('.number input').val('4242424242424242') browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('2040') browser.payment.find('.cvc input').val('123') form = browser.payment.parents('form') form.submit() assert.equal form.find('input[name=stripeToken]').val(), 'token123' 'should call Stripe.createToken with correct arguments': topic: -> browser (err, browser) => browser.window.Stripe.createToken = (values, _) => @callback(null, values) browser.payment.find('.number input').val('4242424242424242') browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('18') browser.payment.find('.cvc input').val('123') form = browser.payment.parents('form') form.submit() 'number': (values) -> assert.equal values.number, '4242424242424242' 'expiry': (values) -> assert.equal values.exp_month, '05' assert.equal values.exp_year, '2018' 'cvc': (values) -> assert.equal values.cvc, '123' 'should disable inputs on submit': browserContext (browser) -> browser.window.Stripe.createToken = -> browser.payment.find('.number input').val('4242424242424242') browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('2040') browser.payment.find('.cvc input').val('123') form = browser.payment.parents('form') form.submit() assert.equal form.find(':input:disabled').length, 5 'should validate CC number': topic: browser 'presence': (browser) -> browser.payment.find('.number input').val('4242424242424243') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.number input').hasClass('invalid') 'luhn': (browser) -> browser.payment.find('.number input').val('4242424242424243') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.number input').hasClass('invalid') 'valid': (browser) -> browser.payment.find('.number input').val('4242424242424242') form = browser.payment.parents('form') form.submit() assert not browser.payment.find('.number').hasClass('invalid') 'should validate expiry': topic: browser 'presence': (browser) -> browser.payment.find('.number input').val('ddd') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.number input').hasClass('invalid') 'numbers': (browser) -> browser.payment.find('input.expiryMonth').val('ddd') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.number input').hasClass('invalid') 'expiry': (browser) -> browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('2001') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.expiry input.expiryYear').hasClass('invalid') 'valid': (browser) -> browser.payment.find('input.expiryMonth').val('05') browser.payment.find('input.expiryYear').val('2040') form = browser.payment.parents('form') form.submit() assert not browser.payment.find('.expiry').hasClass('invalid') 'should validate cvc': topic: browser 'presence': (browser) -> browser.payment.find('.cvc input').val('') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.cvc input').hasClass('invalid') 'length': (browser) -> browser.payment.find('.cvc input').val('919812') form = browser.payment.parents('form') form.submit() assert browser.payment.find('.cvc input').hasClass('invalid') 'valid': (browser) -> browser.payment.find('.cvc input').val('123') form = browser.payment.parents('form') form.submit() assert not browser.payment.find('.cvc input').hasClass('invalid') ).run()
[ { "context": " expect(helpers.calculatePasswordStrength('Admin123')).toEqual(2)\n return\n\n it 'returns 4 for 10 ", "end": 1062, "score": 0.7691345810890198, "start": 1059, "tag": "PASSWORD", "value": "123" } ]
specs/helpers/calculatePasswordStrength.spec.coffee
aryaroudi/Cyclops
28
describe 'helpers: calculatePasswordStrength', -> it 'it hangs off the internal helpers object', -> expect(helpers.calculatePasswordStrength).toBeDefined() return it 'returns 0 for passwords less than 8 characters even with multiple char types', -> expect(helpers.calculatePasswordStrength('1$Ab')).toEqual(0) return it 'returns 1 for passwords greater than 8 characters with less than 2 char types', -> expect(helpers.calculatePasswordStrength('aAaAaAaA')).toEqual(1) return it 'returns 2 for 8 character passwords with 3 char types', -> expect(helpers.calculatePasswordStrength('aA!AaAaA')).toEqual(2) return it 'returns 2 for 8 character passwords with 4 char types', -> expect(helpers.calculatePasswordStrength('aA!AaAa1')).toEqual(2) return it 'returns 3 for 9 character passwords with 3 char types', -> expect(helpers.calculatePasswordStrength('aA!AaAaAa')).toEqual(3) return it 'returns 2 for 8 character passwords with 3 char types', -> expect(helpers.calculatePasswordStrength('Admin123')).toEqual(2) return it 'returns 4 for 10 character passwords with 4 char types', -> expect(helpers.calculatePasswordStrength('1!Ab1!Ab#$')).toEqual(4) return it 'returns 3 for 10 character passwords with 3 char types', -> expect(helpers.calculatePasswordStrength('1!ab1!ab#4')).toEqual(3) it 'returns 4 for 9 character passwords with 4 char types', -> expect(helpers.calculatePasswordStrength('1!Ab1!Ab#')).toEqual(4) return return
143908
describe 'helpers: calculatePasswordStrength', -> it 'it hangs off the internal helpers object', -> expect(helpers.calculatePasswordStrength).toBeDefined() return it 'returns 0 for passwords less than 8 characters even with multiple char types', -> expect(helpers.calculatePasswordStrength('1$Ab')).toEqual(0) return it 'returns 1 for passwords greater than 8 characters with less than 2 char types', -> expect(helpers.calculatePasswordStrength('aAaAaAaA')).toEqual(1) return it 'returns 2 for 8 character passwords with 3 char types', -> expect(helpers.calculatePasswordStrength('aA!AaAaA')).toEqual(2) return it 'returns 2 for 8 character passwords with 4 char types', -> expect(helpers.calculatePasswordStrength('aA!AaAa1')).toEqual(2) return it 'returns 3 for 9 character passwords with 3 char types', -> expect(helpers.calculatePasswordStrength('aA!AaAaAa')).toEqual(3) return it 'returns 2 for 8 character passwords with 3 char types', -> expect(helpers.calculatePasswordStrength('Admin<PASSWORD>')).toEqual(2) return it 'returns 4 for 10 character passwords with 4 char types', -> expect(helpers.calculatePasswordStrength('1!Ab1!Ab#$')).toEqual(4) return it 'returns 3 for 10 character passwords with 3 char types', -> expect(helpers.calculatePasswordStrength('1!ab1!ab#4')).toEqual(3) it 'returns 4 for 9 character passwords with 4 char types', -> expect(helpers.calculatePasswordStrength('1!Ab1!Ab#')).toEqual(4) return return
true
describe 'helpers: calculatePasswordStrength', -> it 'it hangs off the internal helpers object', -> expect(helpers.calculatePasswordStrength).toBeDefined() return it 'returns 0 for passwords less than 8 characters even with multiple char types', -> expect(helpers.calculatePasswordStrength('1$Ab')).toEqual(0) return it 'returns 1 for passwords greater than 8 characters with less than 2 char types', -> expect(helpers.calculatePasswordStrength('aAaAaAaA')).toEqual(1) return it 'returns 2 for 8 character passwords with 3 char types', -> expect(helpers.calculatePasswordStrength('aA!AaAaA')).toEqual(2) return it 'returns 2 for 8 character passwords with 4 char types', -> expect(helpers.calculatePasswordStrength('aA!AaAa1')).toEqual(2) return it 'returns 3 for 9 character passwords with 3 char types', -> expect(helpers.calculatePasswordStrength('aA!AaAaAa')).toEqual(3) return it 'returns 2 for 8 character passwords with 3 char types', -> expect(helpers.calculatePasswordStrength('AdminPI:PASSWORD:<PASSWORD>END_PI')).toEqual(2) return it 'returns 4 for 10 character passwords with 4 char types', -> expect(helpers.calculatePasswordStrength('1!Ab1!Ab#$')).toEqual(4) return it 'returns 3 for 10 character passwords with 3 char types', -> expect(helpers.calculatePasswordStrength('1!ab1!ab#4')).toEqual(3) it 'returns 4 for 9 character passwords with 4 char types', -> expect(helpers.calculatePasswordStrength('1!Ab1!Ab#')).toEqual(4) return return
[ { "context": "lse \"B-\"\n else\n \"C\"\n\neldest: if 24 > 21 then \"Liz\" else \"Ike\"", "end": 173, "score": 0.9899570941925049, "start": 170, "tag": "NAME", "value": "Liz" }, { "context": "else\n \"C\"\n\neldest: if 24 > 21 then \"Liz\" else \"Ike\"", "end": 184, "score": 0.9770185947418213, "start": 181, "tag": "NAME", "value": "Ike" } ]
documentation/coffee/expressions.coffee
tlrobinson/coffee-script
1
grade: student => if student.excellent_work "A+" else if student.okay_stuff if student.tried_hard then "B" else "B-" else "C" eldest: if 24 > 21 then "Liz" else "Ike"
158582
grade: student => if student.excellent_work "A+" else if student.okay_stuff if student.tried_hard then "B" else "B-" else "C" eldest: if 24 > 21 then "<NAME>" else "<NAME>"
true
grade: student => if student.excellent_work "A+" else if student.okay_stuff if student.tried_hard then "B" else "B-" else "C" eldest: if 24 > 21 then "PI:NAME:<NAME>END_PI" else "PI:NAME:<NAME>END_PI"
[ { "context": " errors.push error\n keys[0] = key.toString()\n backend.create(collection, {some_", "end": 7679, "score": 0.8876968622207642, "start": 7671, "tag": "KEY", "value": "toString" }, { "context": " errors.push error\n keys[1] = key.toString()\n backend.list(collection,\n ", "end": 7973, "score": 0.8838536739349365, "start": 7965, "tag": "KEY", "value": "toString" }, { "context": "rs.push error\n keyFromResponse = key.toString()\n backend.read(collection, keyFromR", "end": 12476, "score": 0.6264350414276123, "start": 12468, "tag": "KEY", "value": "toString" }, { "context": "rs.push error\n keyFromResponse = key.toString()\n backend.remove(collection, keyFro", "end": 14118, "score": 0.675868570804596, "start": 14110, "tag": "KEY", "value": "toString" }, { "context": "rs.push error\n keyFromResponse = key.toString()\n backend.read(collection, keyFromR", "end": 15670, "score": 0.9693543314933777, "start": 15662, "tag": "KEY", "value": "toString" } ]
spec/integration/backend.spec.coffee
trankimhieu/cucumber-storra
1
# This spec tests all backend connectors without mocking/spying their # dependencies. That is, it truely accesses the database used by the connector. # In case of the MongoDB backend connector, MongoDB needs to be up and running # for this spec to succeed. describe "Common backend integration test:", -> TIMEOUT = 5000 log = require('../../lib/log') Step = require('step') uuid = require('node-uuid') wire = require('wire') relativizr = new (require('../../lib/relativizr'))() logIntermediateResults = true # define parameterized test parameterized = (backendModule, backendName) -> describe "The #{backendName} backend (without mocked dependencies)", -> backend = null finished = false errors = [] collection = null standardWaitsFor = () -> return finished waitForStepsToFinish = () -> waitsFor(standardWaitsFor, "all steps finishing", TIMEOUT) beforeEach -> backend = null finished = false errors = [] collection = null TestConfigReader = require('../test_config_reader') configReader = new TestConfigReader() # When wiring has finished, we fetch the backend connector from the # wire.js context afterWiring = (context) -> backend = context.backend backend.init(configReader) log.debug(be + ' has been wired.') backend.checkAvailable( () -> log.debug("Backend #{backendName} is available.") , (err) -> # If the backend under test is not there, we just kill the node.js # process to immediately stop the test run. This is extremely # questionable, but right now it helps - otherwise you'll get a # lot of failures in the test run and wonder what on earth is # going wrong. It would be nice if Jasmine offered a version of # the fail method that also stops the current spec (right now, # jasmine just continues with the spec and reports all failures at # the end). log.error(err) log.error("Backend #{backendName} is not available, killing test process!") process.exit(1) ) # Wire up the test wire.js context runs -> backendSpec = "#{backendModule}_wire_spec" relativizr.wireRelative(backendSpec, afterWiring) # wait for wiring to be finished (by looking if backend has been set by # afterWiring) waitsFor -> backend , "wire context to have been initialized", 500 collection = uuid.v1() afterEach -> log.debug("afterEach: closing connection") backend.removeCollection collection, (err) -> if (err) log.error(err) backend.closeConnection (err) -> if (err) log.error(err) it "says 409 when creating the same collection twice", -> runs -> Step( () -> backend.createCollection(collection, this) (error) -> backend.createCollection(collection, this) (error) -> errors.push error finished = true ) waitForStepsToFinish() runs -> expect(errors[0]).toBeTruthy() expect(errors[0].httpStatus).toBeTruthy() expect(errors[0].httpStatus).toBe(409) it "removes collections idempotently", -> runs -> Step( () -> # Collection has not yet been created. However, removing it # should throw no error since delete is ought to be idempotent. backend.removeCollection(collection, this) , (error) -> if (logIntermediateResults) log.info("removeCollection 1 -> error: #{error}") errors.push error finished = true ) waitForStepsToFinish() runs -> expectNoErrors() it "says 404 when reading non-existing document", -> nonExistingDoc = null runs -> Step( () -> backend.read(collection, '123456789012', this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error nonExistingDoc = doc finished = true ) waitForStepsToFinish() runs -> expect(errors[0].httpStatus).toBe(404) expect(nonExistingDoc).toBeNull() it "creates and reads documents", -> keyFromResponse = null readDocument = null runs -> Step( () -> backend.create(collection, {some_attribute: 'abc'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.toString() backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocument = doc finished = true ) waitForStepsToFinish() runs -> expectNoErrors() expect(readDocument).toBeDefined() expect(readDocument['some_attribute']).toEqual('abc') it "says 404 when listing a non-existing collection collection", -> listing = [] runs -> Step( () -> backend.list(collection, (doc) -> log.error("unexpected document: #{doc}") listing.push doc ,this) , (error) -> if (logIntermediateResults) log.info("list end -> error, list: #{error}, #{JSON.stringify(listing)}") errors.push error finished = true ) waitForStepsToFinish() runs -> expect(errors[0].httpStatus).toBe(404) expect(listing.length).toEqual(0) it "creates an empty collection and lists it", -> listing = [] runs -> Step( () -> backend.createCollection(collection, this) (error) -> backend.list(collection, (doc) -> log.error("unexpected document: #{doc}") listing.push doc ,this) , (error) -> if (logIntermediateResults) log.info("list end -> error, list: #{error}, #{JSON.stringify(listing)}") errors.push error finished = true ) waitForStepsToFinish() runs -> expectNoErrors() expect(listing.length).toEqual(0) it "lists a non-empty collection", -> keys = [] listing = [] keyFromListing = null readDocument = null runs -> Step( () -> backend.create(collection, {some_attribute: 'abc'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keys[0] = key.toString() backend.create(collection, {some_attribute: 'xyz'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keys[1] = key.toString() backend.list(collection, (doc) -> log.debug("document: #{doc}") listing.push doc ,this) , (error) -> if (logIntermediateResults) log.info("list -> error, list: #{error}, #{JSON.stringify(listing)}") errors.push error # one extra step (which does not really belong into this spec): # use key from listing to read single document keyFromListing = listing[0]._id.toString() backend.read(collection, keyFromListing, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocument = doc finished = true ) waitForStepsToFinish() runs -> expectNoErrors() # the listing might be in any order, not neccessarily in the order in # which we created the entries. expect(listing.length).toBe(2) fromListing = [] fromListing[0] = findInArray listing, keys[0] fromListing[1] = findInArray listing, keys[1] expect(fromListing[0]).toBeDefined() expect(fromListing[0]._id.toString()).toEqual(keys[0]) expect(fromListing[0]['some_attribute']).toEqual('abc') expect(fromListing[1]).toBeDefined() expect(fromListing[1]._id.toString()).toEqual(keys[1]) expect(fromListing[1]['some_attribute']).toEqual('xyz') expect(readDocument).toBeDefined() if (readDocument._id.toString() == keys[0]) expect(fromListing[0]).toEqual(readDocument) else if (readDocument._id.toString() == keys[1]) expect(fromListing[1]).toEqual(readDocument) else this.fail("id of read document neither matched the key of the first nor of the second created document") it "says 404 when updating a non-existing document", -> runs -> Step( () -> backend.update(collection, '123456789012', {second_attribute: 123, third_attribute: 456}, this) , (error) -> if (logIntermediateResults) log.info("update -> error: #{error}") errors.push error finished = true ) waitForStepsToFinish() runs -> expect(errors[0].httpStatus).toBe(404) it "updates a document", -> keyFromResponse = null readDocument = null runs -> Step( () -> backend.create(collection, {first_attribute: 'foobar'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.toString() backend.update(collection, keyFromResponse, {second_attribute: 123, third_attribute: 'baz'}, this) , (error) -> if (logIntermediateResults) log.info("update -> error: #{error}") errors.push error backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocument = doc finished = true ) waitForStepsToFinish() runs -> expectNoErrors() expect(readDocument).not.toBeNull() expect(readDocument.first_attribute).toBeUndefined() expect(readDocument.second_attribute).toEqual(123) expect(readDocument.third_attribute).toEqual('baz') it "removes a document", -> keyFromResponse = null readDocumentBeforeRemove = null readDocumentAfterRemove = null runs -> Step( () -> backend.create(collection, {first_attribute: 'foobar'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.toString() backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentBeforeRemove = doc backend.remove(collection, keyFromResponse, this) , (error) -> if (logIntermediateResults) log.info("remove -> error: #{error}") errors.push error backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentAfterRemove = doc finished = true ) waitForStepsToFinish() runs -> expectNoError(i, error) for error, i in errors[0..2] expect(errors[3].httpStatus).toBe(404) expect(readDocumentBeforeRemove).not.toBeNull() expect(readDocumentAfterRemove).toBeNull() it "removes a document twice while being idempotent", -> keyFromResponse = null readDocumentAfterRemove = null runs -> Step( () -> backend.create(collection, {first_attribute: 'foobar'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.toString() backend.remove(collection, keyFromResponse, this) , (error) -> if (logIntermediateResults) log.info("remove -> error: #{error}") errors.push error backend.remove(collection, keyFromResponse, this) , (error) -> if (logIntermediateResults) log.info("remove -> error: #{error}") errors.push error backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentAfterRemove = doc finished = true ) waitForStepsToFinish() runs -> expectNoError(i, error) for error, i in errors[0..2] expect(errors[3].httpStatus).toBe(404) expect(readDocumentAfterRemove).toBeNull() it "does not return a document from a removed collection", -> keyFromResponse = null readDocumentBeforeRemove = null readDocumentAfterRemove = null runs -> Step( () -> backend.create(collection, {first_attribute: 'foobar'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.toString() backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentBeforeRemove = doc backend.removeCollection(collection, this) , (error) -> if (logIntermediateResults) log.info("removeCollection -> error: #{error}") errors.push error backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentAfterRemove = doc finished = true ) waitForStepsToFinish() runs -> expectNoError(i, error) for error, i in errors[0..2] expect(errors[3].httpStatus).toBe(404) expect(readDocumentBeforeRemove).not.toBeNull() expect(readDocumentAfterRemove).toBeNull() ### HELPER FUNCTIONS ### expectNoErrors = () -> expectNoError(i, error) for error, i in errors[0..errors.length - 1] expectNoError = (index, error) -> expect(error == null || error == undefined).toBe(true) if ! (error == null || error == undefined) log.error("Unexpected error in test: [#{index}]: #{error}") findInArray = (array, id) -> for item in array if (item._id.toString() == id.toString()) return item ### Call all parameterized tests ### parameterized('./backends/node_dirty_backend', 'node-dirty') parameterized('./backends/nstore_backend', 'nStore') parameterized('./backends/mongodb_backend', 'MongoDB')
12255
# This spec tests all backend connectors without mocking/spying their # dependencies. That is, it truely accesses the database used by the connector. # In case of the MongoDB backend connector, MongoDB needs to be up and running # for this spec to succeed. describe "Common backend integration test:", -> TIMEOUT = 5000 log = require('../../lib/log') Step = require('step') uuid = require('node-uuid') wire = require('wire') relativizr = new (require('../../lib/relativizr'))() logIntermediateResults = true # define parameterized test parameterized = (backendModule, backendName) -> describe "The #{backendName} backend (without mocked dependencies)", -> backend = null finished = false errors = [] collection = null standardWaitsFor = () -> return finished waitForStepsToFinish = () -> waitsFor(standardWaitsFor, "all steps finishing", TIMEOUT) beforeEach -> backend = null finished = false errors = [] collection = null TestConfigReader = require('../test_config_reader') configReader = new TestConfigReader() # When wiring has finished, we fetch the backend connector from the # wire.js context afterWiring = (context) -> backend = context.backend backend.init(configReader) log.debug(be + ' has been wired.') backend.checkAvailable( () -> log.debug("Backend #{backendName} is available.") , (err) -> # If the backend under test is not there, we just kill the node.js # process to immediately stop the test run. This is extremely # questionable, but right now it helps - otherwise you'll get a # lot of failures in the test run and wonder what on earth is # going wrong. It would be nice if Jasmine offered a version of # the fail method that also stops the current spec (right now, # jasmine just continues with the spec and reports all failures at # the end). log.error(err) log.error("Backend #{backendName} is not available, killing test process!") process.exit(1) ) # Wire up the test wire.js context runs -> backendSpec = "#{backendModule}_wire_spec" relativizr.wireRelative(backendSpec, afterWiring) # wait for wiring to be finished (by looking if backend has been set by # afterWiring) waitsFor -> backend , "wire context to have been initialized", 500 collection = uuid.v1() afterEach -> log.debug("afterEach: closing connection") backend.removeCollection collection, (err) -> if (err) log.error(err) backend.closeConnection (err) -> if (err) log.error(err) it "says 409 when creating the same collection twice", -> runs -> Step( () -> backend.createCollection(collection, this) (error) -> backend.createCollection(collection, this) (error) -> errors.push error finished = true ) waitForStepsToFinish() runs -> expect(errors[0]).toBeTruthy() expect(errors[0].httpStatus).toBeTruthy() expect(errors[0].httpStatus).toBe(409) it "removes collections idempotently", -> runs -> Step( () -> # Collection has not yet been created. However, removing it # should throw no error since delete is ought to be idempotent. backend.removeCollection(collection, this) , (error) -> if (logIntermediateResults) log.info("removeCollection 1 -> error: #{error}") errors.push error finished = true ) waitForStepsToFinish() runs -> expectNoErrors() it "says 404 when reading non-existing document", -> nonExistingDoc = null runs -> Step( () -> backend.read(collection, '123456789012', this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error nonExistingDoc = doc finished = true ) waitForStepsToFinish() runs -> expect(errors[0].httpStatus).toBe(404) expect(nonExistingDoc).toBeNull() it "creates and reads documents", -> keyFromResponse = null readDocument = null runs -> Step( () -> backend.create(collection, {some_attribute: 'abc'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.toString() backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocument = doc finished = true ) waitForStepsToFinish() runs -> expectNoErrors() expect(readDocument).toBeDefined() expect(readDocument['some_attribute']).toEqual('abc') it "says 404 when listing a non-existing collection collection", -> listing = [] runs -> Step( () -> backend.list(collection, (doc) -> log.error("unexpected document: #{doc}") listing.push doc ,this) , (error) -> if (logIntermediateResults) log.info("list end -> error, list: #{error}, #{JSON.stringify(listing)}") errors.push error finished = true ) waitForStepsToFinish() runs -> expect(errors[0].httpStatus).toBe(404) expect(listing.length).toEqual(0) it "creates an empty collection and lists it", -> listing = [] runs -> Step( () -> backend.createCollection(collection, this) (error) -> backend.list(collection, (doc) -> log.error("unexpected document: #{doc}") listing.push doc ,this) , (error) -> if (logIntermediateResults) log.info("list end -> error, list: #{error}, #{JSON.stringify(listing)}") errors.push error finished = true ) waitForStepsToFinish() runs -> expectNoErrors() expect(listing.length).toEqual(0) it "lists a non-empty collection", -> keys = [] listing = [] keyFromListing = null readDocument = null runs -> Step( () -> backend.create(collection, {some_attribute: 'abc'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keys[0] = key.<KEY>() backend.create(collection, {some_attribute: 'xyz'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keys[1] = key.<KEY>() backend.list(collection, (doc) -> log.debug("document: #{doc}") listing.push doc ,this) , (error) -> if (logIntermediateResults) log.info("list -> error, list: #{error}, #{JSON.stringify(listing)}") errors.push error # one extra step (which does not really belong into this spec): # use key from listing to read single document keyFromListing = listing[0]._id.toString() backend.read(collection, keyFromListing, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocument = doc finished = true ) waitForStepsToFinish() runs -> expectNoErrors() # the listing might be in any order, not neccessarily in the order in # which we created the entries. expect(listing.length).toBe(2) fromListing = [] fromListing[0] = findInArray listing, keys[0] fromListing[1] = findInArray listing, keys[1] expect(fromListing[0]).toBeDefined() expect(fromListing[0]._id.toString()).toEqual(keys[0]) expect(fromListing[0]['some_attribute']).toEqual('abc') expect(fromListing[1]).toBeDefined() expect(fromListing[1]._id.toString()).toEqual(keys[1]) expect(fromListing[1]['some_attribute']).toEqual('xyz') expect(readDocument).toBeDefined() if (readDocument._id.toString() == keys[0]) expect(fromListing[0]).toEqual(readDocument) else if (readDocument._id.toString() == keys[1]) expect(fromListing[1]).toEqual(readDocument) else this.fail("id of read document neither matched the key of the first nor of the second created document") it "says 404 when updating a non-existing document", -> runs -> Step( () -> backend.update(collection, '123456789012', {second_attribute: 123, third_attribute: 456}, this) , (error) -> if (logIntermediateResults) log.info("update -> error: #{error}") errors.push error finished = true ) waitForStepsToFinish() runs -> expect(errors[0].httpStatus).toBe(404) it "updates a document", -> keyFromResponse = null readDocument = null runs -> Step( () -> backend.create(collection, {first_attribute: 'foobar'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.toString() backend.update(collection, keyFromResponse, {second_attribute: 123, third_attribute: 'baz'}, this) , (error) -> if (logIntermediateResults) log.info("update -> error: #{error}") errors.push error backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocument = doc finished = true ) waitForStepsToFinish() runs -> expectNoErrors() expect(readDocument).not.toBeNull() expect(readDocument.first_attribute).toBeUndefined() expect(readDocument.second_attribute).toEqual(123) expect(readDocument.third_attribute).toEqual('baz') it "removes a document", -> keyFromResponse = null readDocumentBeforeRemove = null readDocumentAfterRemove = null runs -> Step( () -> backend.create(collection, {first_attribute: 'foobar'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.<KEY>() backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentBeforeRemove = doc backend.remove(collection, keyFromResponse, this) , (error) -> if (logIntermediateResults) log.info("remove -> error: #{error}") errors.push error backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentAfterRemove = doc finished = true ) waitForStepsToFinish() runs -> expectNoError(i, error) for error, i in errors[0..2] expect(errors[3].httpStatus).toBe(404) expect(readDocumentBeforeRemove).not.toBeNull() expect(readDocumentAfterRemove).toBeNull() it "removes a document twice while being idempotent", -> keyFromResponse = null readDocumentAfterRemove = null runs -> Step( () -> backend.create(collection, {first_attribute: 'foobar'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.<KEY>() backend.remove(collection, keyFromResponse, this) , (error) -> if (logIntermediateResults) log.info("remove -> error: #{error}") errors.push error backend.remove(collection, keyFromResponse, this) , (error) -> if (logIntermediateResults) log.info("remove -> error: #{error}") errors.push error backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentAfterRemove = doc finished = true ) waitForStepsToFinish() runs -> expectNoError(i, error) for error, i in errors[0..2] expect(errors[3].httpStatus).toBe(404) expect(readDocumentAfterRemove).toBeNull() it "does not return a document from a removed collection", -> keyFromResponse = null readDocumentBeforeRemove = null readDocumentAfterRemove = null runs -> Step( () -> backend.create(collection, {first_attribute: 'foobar'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.<KEY>() backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentBeforeRemove = doc backend.removeCollection(collection, this) , (error) -> if (logIntermediateResults) log.info("removeCollection -> error: #{error}") errors.push error backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentAfterRemove = doc finished = true ) waitForStepsToFinish() runs -> expectNoError(i, error) for error, i in errors[0..2] expect(errors[3].httpStatus).toBe(404) expect(readDocumentBeforeRemove).not.toBeNull() expect(readDocumentAfterRemove).toBeNull() ### HELPER FUNCTIONS ### expectNoErrors = () -> expectNoError(i, error) for error, i in errors[0..errors.length - 1] expectNoError = (index, error) -> expect(error == null || error == undefined).toBe(true) if ! (error == null || error == undefined) log.error("Unexpected error in test: [#{index}]: #{error}") findInArray = (array, id) -> for item in array if (item._id.toString() == id.toString()) return item ### Call all parameterized tests ### parameterized('./backends/node_dirty_backend', 'node-dirty') parameterized('./backends/nstore_backend', 'nStore') parameterized('./backends/mongodb_backend', 'MongoDB')
true
# This spec tests all backend connectors without mocking/spying their # dependencies. That is, it truely accesses the database used by the connector. # In case of the MongoDB backend connector, MongoDB needs to be up and running # for this spec to succeed. describe "Common backend integration test:", -> TIMEOUT = 5000 log = require('../../lib/log') Step = require('step') uuid = require('node-uuid') wire = require('wire') relativizr = new (require('../../lib/relativizr'))() logIntermediateResults = true # define parameterized test parameterized = (backendModule, backendName) -> describe "The #{backendName} backend (without mocked dependencies)", -> backend = null finished = false errors = [] collection = null standardWaitsFor = () -> return finished waitForStepsToFinish = () -> waitsFor(standardWaitsFor, "all steps finishing", TIMEOUT) beforeEach -> backend = null finished = false errors = [] collection = null TestConfigReader = require('../test_config_reader') configReader = new TestConfigReader() # When wiring has finished, we fetch the backend connector from the # wire.js context afterWiring = (context) -> backend = context.backend backend.init(configReader) log.debug(be + ' has been wired.') backend.checkAvailable( () -> log.debug("Backend #{backendName} is available.") , (err) -> # If the backend under test is not there, we just kill the node.js # process to immediately stop the test run. This is extremely # questionable, but right now it helps - otherwise you'll get a # lot of failures in the test run and wonder what on earth is # going wrong. It would be nice if Jasmine offered a version of # the fail method that also stops the current spec (right now, # jasmine just continues with the spec and reports all failures at # the end). log.error(err) log.error("Backend #{backendName} is not available, killing test process!") process.exit(1) ) # Wire up the test wire.js context runs -> backendSpec = "#{backendModule}_wire_spec" relativizr.wireRelative(backendSpec, afterWiring) # wait for wiring to be finished (by looking if backend has been set by # afterWiring) waitsFor -> backend , "wire context to have been initialized", 500 collection = uuid.v1() afterEach -> log.debug("afterEach: closing connection") backend.removeCollection collection, (err) -> if (err) log.error(err) backend.closeConnection (err) -> if (err) log.error(err) it "says 409 when creating the same collection twice", -> runs -> Step( () -> backend.createCollection(collection, this) (error) -> backend.createCollection(collection, this) (error) -> errors.push error finished = true ) waitForStepsToFinish() runs -> expect(errors[0]).toBeTruthy() expect(errors[0].httpStatus).toBeTruthy() expect(errors[0].httpStatus).toBe(409) it "removes collections idempotently", -> runs -> Step( () -> # Collection has not yet been created. However, removing it # should throw no error since delete is ought to be idempotent. backend.removeCollection(collection, this) , (error) -> if (logIntermediateResults) log.info("removeCollection 1 -> error: #{error}") errors.push error finished = true ) waitForStepsToFinish() runs -> expectNoErrors() it "says 404 when reading non-existing document", -> nonExistingDoc = null runs -> Step( () -> backend.read(collection, '123456789012', this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error nonExistingDoc = doc finished = true ) waitForStepsToFinish() runs -> expect(errors[0].httpStatus).toBe(404) expect(nonExistingDoc).toBeNull() it "creates and reads documents", -> keyFromResponse = null readDocument = null runs -> Step( () -> backend.create(collection, {some_attribute: 'abc'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.toString() backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocument = doc finished = true ) waitForStepsToFinish() runs -> expectNoErrors() expect(readDocument).toBeDefined() expect(readDocument['some_attribute']).toEqual('abc') it "says 404 when listing a non-existing collection collection", -> listing = [] runs -> Step( () -> backend.list(collection, (doc) -> log.error("unexpected document: #{doc}") listing.push doc ,this) , (error) -> if (logIntermediateResults) log.info("list end -> error, list: #{error}, #{JSON.stringify(listing)}") errors.push error finished = true ) waitForStepsToFinish() runs -> expect(errors[0].httpStatus).toBe(404) expect(listing.length).toEqual(0) it "creates an empty collection and lists it", -> listing = [] runs -> Step( () -> backend.createCollection(collection, this) (error) -> backend.list(collection, (doc) -> log.error("unexpected document: #{doc}") listing.push doc ,this) , (error) -> if (logIntermediateResults) log.info("list end -> error, list: #{error}, #{JSON.stringify(listing)}") errors.push error finished = true ) waitForStepsToFinish() runs -> expectNoErrors() expect(listing.length).toEqual(0) it "lists a non-empty collection", -> keys = [] listing = [] keyFromListing = null readDocument = null runs -> Step( () -> backend.create(collection, {some_attribute: 'abc'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keys[0] = key.PI:KEY:<KEY>END_PI() backend.create(collection, {some_attribute: 'xyz'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keys[1] = key.PI:KEY:<KEY>END_PI() backend.list(collection, (doc) -> log.debug("document: #{doc}") listing.push doc ,this) , (error) -> if (logIntermediateResults) log.info("list -> error, list: #{error}, #{JSON.stringify(listing)}") errors.push error # one extra step (which does not really belong into this spec): # use key from listing to read single document keyFromListing = listing[0]._id.toString() backend.read(collection, keyFromListing, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocument = doc finished = true ) waitForStepsToFinish() runs -> expectNoErrors() # the listing might be in any order, not neccessarily in the order in # which we created the entries. expect(listing.length).toBe(2) fromListing = [] fromListing[0] = findInArray listing, keys[0] fromListing[1] = findInArray listing, keys[1] expect(fromListing[0]).toBeDefined() expect(fromListing[0]._id.toString()).toEqual(keys[0]) expect(fromListing[0]['some_attribute']).toEqual('abc') expect(fromListing[1]).toBeDefined() expect(fromListing[1]._id.toString()).toEqual(keys[1]) expect(fromListing[1]['some_attribute']).toEqual('xyz') expect(readDocument).toBeDefined() if (readDocument._id.toString() == keys[0]) expect(fromListing[0]).toEqual(readDocument) else if (readDocument._id.toString() == keys[1]) expect(fromListing[1]).toEqual(readDocument) else this.fail("id of read document neither matched the key of the first nor of the second created document") it "says 404 when updating a non-existing document", -> runs -> Step( () -> backend.update(collection, '123456789012', {second_attribute: 123, third_attribute: 456}, this) , (error) -> if (logIntermediateResults) log.info("update -> error: #{error}") errors.push error finished = true ) waitForStepsToFinish() runs -> expect(errors[0].httpStatus).toBe(404) it "updates a document", -> keyFromResponse = null readDocument = null runs -> Step( () -> backend.create(collection, {first_attribute: 'foobar'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.toString() backend.update(collection, keyFromResponse, {second_attribute: 123, third_attribute: 'baz'}, this) , (error) -> if (logIntermediateResults) log.info("update -> error: #{error}") errors.push error backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocument = doc finished = true ) waitForStepsToFinish() runs -> expectNoErrors() expect(readDocument).not.toBeNull() expect(readDocument.first_attribute).toBeUndefined() expect(readDocument.second_attribute).toEqual(123) expect(readDocument.third_attribute).toEqual('baz') it "removes a document", -> keyFromResponse = null readDocumentBeforeRemove = null readDocumentAfterRemove = null runs -> Step( () -> backend.create(collection, {first_attribute: 'foobar'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.PI:KEY:<KEY>END_PI() backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentBeforeRemove = doc backend.remove(collection, keyFromResponse, this) , (error) -> if (logIntermediateResults) log.info("remove -> error: #{error}") errors.push error backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentAfterRemove = doc finished = true ) waitForStepsToFinish() runs -> expectNoError(i, error) for error, i in errors[0..2] expect(errors[3].httpStatus).toBe(404) expect(readDocumentBeforeRemove).not.toBeNull() expect(readDocumentAfterRemove).toBeNull() it "removes a document twice while being idempotent", -> keyFromResponse = null readDocumentAfterRemove = null runs -> Step( () -> backend.create(collection, {first_attribute: 'foobar'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.PI:KEY:<KEY>END_PI() backend.remove(collection, keyFromResponse, this) , (error) -> if (logIntermediateResults) log.info("remove -> error: #{error}") errors.push error backend.remove(collection, keyFromResponse, this) , (error) -> if (logIntermediateResults) log.info("remove -> error: #{error}") errors.push error backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentAfterRemove = doc finished = true ) waitForStepsToFinish() runs -> expectNoError(i, error) for error, i in errors[0..2] expect(errors[3].httpStatus).toBe(404) expect(readDocumentAfterRemove).toBeNull() it "does not return a document from a removed collection", -> keyFromResponse = null readDocumentBeforeRemove = null readDocumentAfterRemove = null runs -> Step( () -> backend.create(collection, {first_attribute: 'foobar'}, this) , (error, key) -> if (logIntermediateResults) log.info("create -> error, key: #{error}, #{key}") errors.push error keyFromResponse = key.PI:KEY:<KEY>END_PI() backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentBeforeRemove = doc backend.removeCollection(collection, this) , (error) -> if (logIntermediateResults) log.info("removeCollection -> error: #{error}") errors.push error backend.read(collection, keyFromResponse, this) , (error, doc, key) -> if (logIntermediateResults) log.info("read -> error, doc, key: #{error}, #{doc}, #{key}") errors.push error readDocumentAfterRemove = doc finished = true ) waitForStepsToFinish() runs -> expectNoError(i, error) for error, i in errors[0..2] expect(errors[3].httpStatus).toBe(404) expect(readDocumentBeforeRemove).not.toBeNull() expect(readDocumentAfterRemove).toBeNull() ### HELPER FUNCTIONS ### expectNoErrors = () -> expectNoError(i, error) for error, i in errors[0..errors.length - 1] expectNoError = (index, error) -> expect(error == null || error == undefined).toBe(true) if ! (error == null || error == undefined) log.error("Unexpected error in test: [#{index}]: #{error}") findInArray = (array, id) -> for item in array if (item._id.toString() == id.toString()) return item ### Call all parameterized tests ### parameterized('./backends/node_dirty_backend', 'node-dirty') parameterized('./backends/nstore_backend', 'nStore') parameterized('./backends/mongodb_backend', 'MongoDB')
[ { "context": "model = new DotLedger.Models.Payment\n name: 'Some Payment'\n view = createView(model).render()\n expect", "end": 2243, "score": 0.9867969155311584, "start": 2231, "tag": "NAME", "value": "Some Payment" }, { "context": "der()\n\n view.$el.find('input[name=name]').val('Something')\n view.$el.find('input[name=amount]').val('12", "end": 2664, "score": 0.7415810227394104, "start": 2655, "tag": "NAME", "value": "Something" }, { "context": "pect(model.set).toHaveBeenCalledWith\n name: 'Something'\n amount: '123.00'\n category_id: '11'\n ", "end": 3172, "score": 0.9900730848312378, "start": 3163, "tag": "NAME", "value": "Something" }, { "context": "model = new DotLedger.Models.Payment\n name: 'Payment'\n amount: '435.24'\n category_id: '22'\n ", "end": 3459, "score": 0.9926543235778809, "start": 3452, "tag": "NAME", "value": "Payment" } ]
spec/javascripts/dot_ledger/views/payments/form_spec.js.coffee
timobleeker/dotledger
0
describe "DotLedger.Views.Payments.Form", -> createView = (model = new DotLedger.Models.Payment())-> categories = new DotLedger.Collections.Categories [ { id: 11 name: 'Category One' type: 'Essential' } { id: 22 name: 'Category Two' type: 'Flexible' } { id: 33 name: 'Category Three' type: 'Income' } { id: 44 name: 'Transfer In' type: 'Transfer' } ] view = new DotLedger.Views.Payments.Form model: model categories: categories view it "should be defined", -> expect(DotLedger.Views.Payments.Form).toBeDefined() it "should use the correct template", -> expect(DotLedger.Views.Payments.Form).toUseTemplate('payments/form') it "can be rendered", -> view = createView() expect(view.render).not.toThrow() it "renders the form fields", -> view = createView().render() expect(view.$el).toContainElement('input[name=name]') expect(view.$el).toContainElement('input[name=amount]') expect(view.$el).toContainElement('select[name=category]') expect(view.$el).toContainElement('option[value=11]') expect(view.$el).toContainElement('option[value=22]') expect(view.$el).toContainElement('option[value=33]') expect(view.$el).toContainElement('option[value=44]') expect(view.$el).toContainElement('input[name=date]') expect(view.$el).toContainElement('input[name=repeat]') expect(view.$el).toContainElement('input[name=repeat_interval]') expect(view.$el).toContainElement('select[name=repeat_period]') expect(view.$el).toContainElement('option[value=Day]') expect(view.$el).toContainElement('option[value=Week]') expect(view.$el).toContainElement('option[value=Month]') expect(view.$el).toContainElement('select[name=type]') expect(view.$el).toContainElement('option[value=Spend]') expect(view.$el).toContainElement('option[value=Receive]') it "renders the heading for new payment", -> view = createView().render() expect(view.$el).toHaveText(/New Payment/) it "renders the heading existing payment", -> model = new DotLedger.Models.Payment name: 'Some Payment' view = createView(model).render() expect(view.$el).toHaveText(/Some Payment/) it "renders the cancel link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/payments"]') it "should set the values on the model when update is called", -> model = new DotLedger.Models.Payment() view = createView(model).render() view.$el.find('input[name=name]').val('Something') view.$el.find('input[name=amount]').val('123.00') view.$el.find('select[name=category]').val('11') view.$el.find('input[name=date]').val('2011-03-06') view.$el.find('input[name=repeat]').prop('checked', true) view.$el.find('input[name=repeat_interval]').val('3') view.$el.find('select[name=repeat_period]').val('Week') view.$el.find('select[name=type]').val('Spend') spyOn(model, 'set') view.update() expect(model.set).toHaveBeenCalledWith name: 'Something' amount: '123.00' category_id: '11' date: '2011-03-06' repeat: true repeat_interval: '3' repeat_period: 'Week' type: 'Spend' it "renders the form fields with the model values", -> model = new DotLedger.Models.Payment name: 'Payment' amount: '435.24' category_id: '22' date: '2011-03-06' repeat: true repeat_interval: '2' repeat_period: 'Month' type: 'Receive' view = createView(model).render() expect(view.$el.find('input[name=name]')).toHaveValue('Payment') expect(view.$el.find('input[name=amount]')).toHaveValue('435.24') expect(view.$el.find('select[name=category]')).toHaveValue('22') expect(view.$el.find('input[name=date]')).toHaveValue('2011-03-06') expect(view.$el.find('input[name=repeat]')).toBeChecked() expect(view.$el.find('input[name=repeat_interval]')).toHaveValue('2') expect(view.$el.find('select[name=repeat_period]')).toHaveValue('Month') expect(view.$el.find('select[name=type]')).toHaveValue('Receive')
21333
describe "DotLedger.Views.Payments.Form", -> createView = (model = new DotLedger.Models.Payment())-> categories = new DotLedger.Collections.Categories [ { id: 11 name: 'Category One' type: 'Essential' } { id: 22 name: 'Category Two' type: 'Flexible' } { id: 33 name: 'Category Three' type: 'Income' } { id: 44 name: 'Transfer In' type: 'Transfer' } ] view = new DotLedger.Views.Payments.Form model: model categories: categories view it "should be defined", -> expect(DotLedger.Views.Payments.Form).toBeDefined() it "should use the correct template", -> expect(DotLedger.Views.Payments.Form).toUseTemplate('payments/form') it "can be rendered", -> view = createView() expect(view.render).not.toThrow() it "renders the form fields", -> view = createView().render() expect(view.$el).toContainElement('input[name=name]') expect(view.$el).toContainElement('input[name=amount]') expect(view.$el).toContainElement('select[name=category]') expect(view.$el).toContainElement('option[value=11]') expect(view.$el).toContainElement('option[value=22]') expect(view.$el).toContainElement('option[value=33]') expect(view.$el).toContainElement('option[value=44]') expect(view.$el).toContainElement('input[name=date]') expect(view.$el).toContainElement('input[name=repeat]') expect(view.$el).toContainElement('input[name=repeat_interval]') expect(view.$el).toContainElement('select[name=repeat_period]') expect(view.$el).toContainElement('option[value=Day]') expect(view.$el).toContainElement('option[value=Week]') expect(view.$el).toContainElement('option[value=Month]') expect(view.$el).toContainElement('select[name=type]') expect(view.$el).toContainElement('option[value=Spend]') expect(view.$el).toContainElement('option[value=Receive]') it "renders the heading for new payment", -> view = createView().render() expect(view.$el).toHaveText(/New Payment/) it "renders the heading existing payment", -> model = new DotLedger.Models.Payment name: '<NAME>' view = createView(model).render() expect(view.$el).toHaveText(/Some Payment/) it "renders the cancel link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/payments"]') it "should set the values on the model when update is called", -> model = new DotLedger.Models.Payment() view = createView(model).render() view.$el.find('input[name=name]').val('<NAME>') view.$el.find('input[name=amount]').val('123.00') view.$el.find('select[name=category]').val('11') view.$el.find('input[name=date]').val('2011-03-06') view.$el.find('input[name=repeat]').prop('checked', true) view.$el.find('input[name=repeat_interval]').val('3') view.$el.find('select[name=repeat_period]').val('Week') view.$el.find('select[name=type]').val('Spend') spyOn(model, 'set') view.update() expect(model.set).toHaveBeenCalledWith name: '<NAME>' amount: '123.00' category_id: '11' date: '2011-03-06' repeat: true repeat_interval: '3' repeat_period: 'Week' type: 'Spend' it "renders the form fields with the model values", -> model = new DotLedger.Models.Payment name: '<NAME>' amount: '435.24' category_id: '22' date: '2011-03-06' repeat: true repeat_interval: '2' repeat_period: 'Month' type: 'Receive' view = createView(model).render() expect(view.$el.find('input[name=name]')).toHaveValue('Payment') expect(view.$el.find('input[name=amount]')).toHaveValue('435.24') expect(view.$el.find('select[name=category]')).toHaveValue('22') expect(view.$el.find('input[name=date]')).toHaveValue('2011-03-06') expect(view.$el.find('input[name=repeat]')).toBeChecked() expect(view.$el.find('input[name=repeat_interval]')).toHaveValue('2') expect(view.$el.find('select[name=repeat_period]')).toHaveValue('Month') expect(view.$el.find('select[name=type]')).toHaveValue('Receive')
true
describe "DotLedger.Views.Payments.Form", -> createView = (model = new DotLedger.Models.Payment())-> categories = new DotLedger.Collections.Categories [ { id: 11 name: 'Category One' type: 'Essential' } { id: 22 name: 'Category Two' type: 'Flexible' } { id: 33 name: 'Category Three' type: 'Income' } { id: 44 name: 'Transfer In' type: 'Transfer' } ] view = new DotLedger.Views.Payments.Form model: model categories: categories view it "should be defined", -> expect(DotLedger.Views.Payments.Form).toBeDefined() it "should use the correct template", -> expect(DotLedger.Views.Payments.Form).toUseTemplate('payments/form') it "can be rendered", -> view = createView() expect(view.render).not.toThrow() it "renders the form fields", -> view = createView().render() expect(view.$el).toContainElement('input[name=name]') expect(view.$el).toContainElement('input[name=amount]') expect(view.$el).toContainElement('select[name=category]') expect(view.$el).toContainElement('option[value=11]') expect(view.$el).toContainElement('option[value=22]') expect(view.$el).toContainElement('option[value=33]') expect(view.$el).toContainElement('option[value=44]') expect(view.$el).toContainElement('input[name=date]') expect(view.$el).toContainElement('input[name=repeat]') expect(view.$el).toContainElement('input[name=repeat_interval]') expect(view.$el).toContainElement('select[name=repeat_period]') expect(view.$el).toContainElement('option[value=Day]') expect(view.$el).toContainElement('option[value=Week]') expect(view.$el).toContainElement('option[value=Month]') expect(view.$el).toContainElement('select[name=type]') expect(view.$el).toContainElement('option[value=Spend]') expect(view.$el).toContainElement('option[value=Receive]') it "renders the heading for new payment", -> view = createView().render() expect(view.$el).toHaveText(/New Payment/) it "renders the heading existing payment", -> model = new DotLedger.Models.Payment name: 'PI:NAME:<NAME>END_PI' view = createView(model).render() expect(view.$el).toHaveText(/Some Payment/) it "renders the cancel link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/payments"]') it "should set the values on the model when update is called", -> model = new DotLedger.Models.Payment() view = createView(model).render() view.$el.find('input[name=name]').val('PI:NAME:<NAME>END_PI') view.$el.find('input[name=amount]').val('123.00') view.$el.find('select[name=category]').val('11') view.$el.find('input[name=date]').val('2011-03-06') view.$el.find('input[name=repeat]').prop('checked', true) view.$el.find('input[name=repeat_interval]').val('3') view.$el.find('select[name=repeat_period]').val('Week') view.$el.find('select[name=type]').val('Spend') spyOn(model, 'set') view.update() expect(model.set).toHaveBeenCalledWith name: 'PI:NAME:<NAME>END_PI' amount: '123.00' category_id: '11' date: '2011-03-06' repeat: true repeat_interval: '3' repeat_period: 'Week' type: 'Spend' it "renders the form fields with the model values", -> model = new DotLedger.Models.Payment name: 'PI:NAME:<NAME>END_PI' amount: '435.24' category_id: '22' date: '2011-03-06' repeat: true repeat_interval: '2' repeat_period: 'Month' type: 'Receive' view = createView(model).render() expect(view.$el.find('input[name=name]')).toHaveValue('Payment') expect(view.$el.find('input[name=amount]')).toHaveValue('435.24') expect(view.$el.find('select[name=category]')).toHaveValue('22') expect(view.$el.find('input[name=date]')).toHaveValue('2011-03-06') expect(view.$el.find('input[name=repeat]')).toBeChecked() expect(view.$el.find('input[name=repeat_interval]')).toHaveValue('2') expect(view.$el.find('select[name=repeat_period]')).toHaveValue('Month') expect(view.$el.find('select[name=type]')).toHaveValue('Receive')
[ { "context": "uire('os')\nfs = require('fs')\n\nparentConfigKey = \"atom-beautify.executables\"\n\n\nclass Executable\n\n name: null\n cmd: null\n k", "end": 249, "score": 0.8301540017127991, "start": 224, "tag": "KEY", "value": "atom-beautify.executables" }, { "context": "sic notice\n docsLink = \"https://github.com/Glavin001/atom-beautify#beautifiers\"\n helpStr = \"See", "end": 7874, "score": 0.900745153427124, "start": 7865, "tag": "USERNAME", "value": "Glavin001" }, { "context": "d when the PATH changes.\n See https://github.com/isaacs/node-which\n ###\n which: (exe, options) ->\n @", "end": 9367, "score": 0.9985061883926392, "start": 9361, "tag": "USERNAME", "value": "isaacs" } ]
src/beautifiers/executable.coffee
MSP-Greg/atom-beautify
0
Promise = require('bluebird') _ = require('lodash') which = require('which') spawn = require('child_process').spawn path = require('path') semver = require('semver') os = require('os') fs = require('fs') parentConfigKey = "atom-beautify.executables" class Executable name: null cmd: null key: null homepage: null installation: null versionArgs: ['--version'] versionParse: (text) -> semver.clean(text) versionRunOptions: {} versionsSupported: '>= 0.0.0' required: true constructor: (options) -> # Validation if !options.cmd? throw new Error("The command (i.e. cmd property) is required for an Executable.") @name = options.name @cmd = options.cmd @key = @cmd @homepage = options.homepage @installation = options.installation @required = not options.optional if options.version? versionOptions = options.version @versionArgs = versionOptions.args if versionOptions.args @versionParse = versionOptions.parse if versionOptions.parse @versionRunOptions = versionOptions.runOptions if versionOptions.runOptions @versionsSupported = versionOptions.supported if versionOptions.supported @setupLogger() init: () -> Promise.all([ @loadVersion() ]) .then(() => @verbose("Done init of #{@name}")) .then(() => @) .catch((error) => if not @.required @verbose("Not required") @ else Promise.reject(error) ) ### Logger instance ### logger: null ### Initialize and configure Logger ### setupLogger: -> @logger = require('../logger')("#{@name} Executable") for key, method of @logger @[key] = method @verbose("#{@name} executable logger has been initialized.") isInstalled = null version = null loadVersion: (force = false) -> @verbose("loadVersion", @version, force) if force or !@version? @verbose("Loading version without cache") @runVersion() .then((text) => @saveVersion(text)) else @verbose("Loading cached version") Promise.resolve(@version) runVersion: () -> @run(@versionArgs, @versionRunOptions) .then((version) => @info("Version text: " + version) version ) saveVersion: (text) -> Promise.resolve() .then( => @versionParse(text)) .then((version) -> valid = Boolean(semver.valid(version)) if not valid throw new Error("Version is not valid: "+version) version ) .then((version) => @isInstalled = true @version = version ) .then((version) => @info("#{@cmd} version: #{version}") version ) .catch((error) => @isInstalled = false @error(error) help = { program: @cmd link: @installation or @homepage pathOption: "Executable - #{@name or @cmd} - Path" } Promise.reject(@commandNotFoundError(@name or @cmd, help)) ) isSupported: () -> @isVersion(@versionsSupported) isVersion: (range) -> @versionSatisfies(@version, range) versionSatisfies: (version, range) -> semver.satisfies(version, range) getConfig: () -> atom?.config.get("#{parentConfigKey}.#{@key}") or {} ### Run command-line interface command ### run: (args, options = {}) -> @debug("Run: ", @cmd, args, options) { cmd, cwd, ignoreReturnCode, help, onStdin, returnStderr, returnStdoutOrStderr } = options exeName = cmd or @cmd cwd ?= os.tmpdir() help ?= { program: @cmd link: @installation or @homepage pathOption: "Executable - #{@name or @cmd} - Path" } # Resolve executable and all args Promise.all([@shellEnv(), this.resolveArgs(args)]) .then(([env, args]) => @debug('exeName, args:', exeName, args) # Get PATH and other environment variables exePath = @path(exeName) Promise.all([exeName, args, env, exePath]) ) .then(([exeName, args, env, exePath]) => @debug('exePath:', exePath) @debug('env:', env) @debug('PATH:', env.PATH) @debug('args', args) args = this.relativizePaths(args) @debug('relativized args', args) exe = exePath ? exeName spawnOptions = { cwd: cwd env: env } @debug('spawnOptions', spawnOptions) @spawn(exe, args, spawnOptions, onStdin) .then(({returnCode, stdout, stderr}) => @verbose('spawn result, returnCode', returnCode) @verbose('spawn result, stdout', stdout) @verbose('spawn result, stderr', stderr) # If return code is not 0 then error occured if not ignoreReturnCode and returnCode isnt 0 # operable program or batch file windowsProgramNotFoundMsg = "is not recognized as an internal or external command" @verbose(stderr, windowsProgramNotFoundMsg) if @isWindows() and returnCode is 1 and stderr.indexOf(windowsProgramNotFoundMsg) isnt -1 throw @commandNotFoundError(exeName, help) else throw new Error(stderr or stdout) else if returnStdoutOrStderr return stdout or stderr else if returnStderr stderr else stdout ) .catch((err) => @debug('error', err) # Check if error is ENOENT (command could not be found) if err.code is 'ENOENT' or err.errno is 'ENOENT' throw @commandNotFoundError(exeName, help) else # continue as normal error throw err ) ) path: (cmd = @cmd) -> config = @getConfig() if config and config.path Promise.resolve(config.path) else exeName = cmd @which(exeName) resolveArgs: (args) -> args = _.flatten(args) Promise.all(args) relativizePaths: (args) -> tmpDir = os.tmpdir() newArgs = args.map((arg) -> isTmpFile = (typeof arg is 'string' and not arg.includes(':') and \ path.isAbsolute(arg) and path.dirname(arg).startsWith(tmpDir)) if isTmpFile return path.relative(tmpDir, arg) return arg ) newArgs ### Spawn ### spawn: (exe, args, options, onStdin) -> # Remove undefined/null values args = _.without(args, undefined) args = _.without(args, null) return new Promise((resolve, reject) => @debug('spawn', exe, args) cmd = spawn(exe, args, options) stdout = "" stderr = "" cmd.stdout.on('data', (data) -> stdout += data ) cmd.stderr.on('data', (data) -> stderr += data ) cmd.on('close', (returnCode) => @debug('spawn done', returnCode, stderr, stdout) resolve({returnCode, stdout, stderr}) ) cmd.on('error', (err) => @debug('error', err) reject(err) ) onStdin cmd.stdin if onStdin ) ### Add help to error.description Note: error.description is not officially used in JavaScript, however it is used internally for Atom Beautify when displaying errors. ### commandNotFoundError: (exe, help) -> exe ?= @name or @cmd @constructor.commandNotFoundError(exe, help) @commandNotFoundError: (exe, help) -> # Create new improved error # notify user that it may not be # installed or in path message = "Could not find '#{exe}'. \ The program may not be installed." er = new Error(message) er.code = 'CommandNotFound' er.errno = er.code er.syscall = 'beautifier::run' er.file = exe if help? if typeof help is "object" # Basic notice docsLink = "https://github.com/Glavin001/atom-beautify#beautifiers" helpStr = "See #{exe} installation instructions at #{docsLink}#{if help.link then (' or go to '+help.link) else ''}\n" # # Help to configure Atom Beautify for program's path helpStr += "You can configure Atom Beautify \ with the absolute path \ to '#{help.program or exe}' by setting \ '#{help.pathOption}' in \ the Atom Beautify package settings.\n" if help.pathOption helpStr += "Your program is properly installed if running \ '#{if @isWindows() then 'where.exe' \ else 'which'} #{exe}' \ in your #{if @isWindows() then 'CMD prompt' \ else 'Terminal'} \ returns an absolute path to the executable.\n" # # Optional, additional help helpStr += help.additional if help.additional er.description = helpStr else #if typeof help is "string" er.description = help return er @_envCache = null shellEnv: () -> env = @constructor.shellEnv() @debug("env", env) return env @shellEnv: () -> Promise.resolve(process.env) ### Like the unix which utility. Finds the first instance of a specified executable in the PATH environment variable. Does not cache the results, so hash -r is not needed when the PATH changes. See https://github.com/isaacs/node-which ### which: (exe, options) -> @.constructor.which(exe, options) @_whichCache = {} @which: (exe, options = {}) -> if @_whichCache[exe] return Promise.resolve(@_whichCache[exe]) # Get PATH and other environment variables @shellEnv() .then((env) => new Promise((resolve, reject) => options.path ?= env.PATH if @isWindows() # Environment variables are case-insensitive in windows # Check env for a case-insensitive 'path' variable if !options.path for i of env if i.toLowerCase() is "path" options.path = env[i] break # Trick node-which into including files # with no extension as executables. # Put empty extension last to allow for other real extensions first options.pathExt ?= "#{process.env.PATHEXT ? '.EXE'};" which(exe, options, (err, path) => return resolve(exe) if err @_whichCache[exe] = path resolve(path) ) ) ) ### If platform is Windows ### isWindows: () -> @constructor.isWindows() @isWindows: () -> new RegExp('^win').test(process.platform) class HybridExecutable extends Executable dockerOptions: { image: undefined workingDir: "/workdir" } constructor: (options) -> super(options) @verbose("HybridExecutable Options", options) if options.docker? @dockerOptions = Object.assign({}, @dockerOptions, options.docker) @docker = @constructor.dockerExecutable() @docker: undefined @dockerExecutable: () -> if not @docker? @docker = new Executable({ name: "Docker" cmd: "docker" homepage: "https://www.docker.com/" installation: "https://www.docker.com/get-docker" version: { parse: (text) -> text.match(/version [0]*([1-9]\d*).[0]*([0-9]\d*).[0]*([0-9]\d*)/).slice(1).join('.') } }) return @docker installedWithDocker: false init: () -> super() .then(() => return @ ) .catch((error) => return Promise.reject(error) if not @docker? return Promise.resolve(error) ) .then((errorOrThis) => shouldTryWithDocker = not @isInstalled and @docker? @verbose("Executable shouldTryWithDocker", shouldTryWithDocker, @isInstalled, @docker?) if shouldTryWithDocker return @initDocker().catch(() -> Promise.reject(errorOrThis)) return @ ) .catch((error) => if not @.required @verbose("Not required") @ else Promise.reject(error) ) initDocker: () -> @docker.init() .then(=> @runImage(@versionArgs, @versionRunOptions)) .then((text) => @saveVersion(text)) .then(() => @installedWithDocker = true) .then(=> @) .catch((dockerError) => @debug(dockerError) Promise.reject(dockerError) ) run: (args, options = {}) -> @verbose("Running HybridExecutable") @verbose("installedWithDocker", @installedWithDocker) @verbose("docker", @docker) @verbose("docker.isInstalled", @docker and @docker.isInstalled) if @installedWithDocker and @docker and @docker.isInstalled return @runImage(args, options) super(args, options) runImage: (args, options) -> @debug("Run Docker executable: ", args, options) this.resolveArgs(args) .then((args) => { cwd } = options tmpDir = os.tmpdir() pwd = fs.realpathSync(cwd or tmpDir) image = @dockerOptions.image workingDir = @dockerOptions.workingDir rootPath = '/mountedRoot' newArgs = args.map((arg) -> if (typeof arg is 'string' and not arg.includes(':') \ and path.isAbsolute(arg) and not path.dirname(arg).startsWith(tmpDir)) \ then path.join(rootPath, arg) else arg ) @docker.run([ "run", "--volume", "#{pwd}:#{workingDir}", "--volume", "#{path.resolve('/')}:#{rootPath}", "--workdir", workingDir, image, newArgs ], Object.assign({}, options, { cmd: undefined }) ) ) module.exports = HybridExecutable
202422
Promise = require('bluebird') _ = require('lodash') which = require('which') spawn = require('child_process').spawn path = require('path') semver = require('semver') os = require('os') fs = require('fs') parentConfigKey = "<KEY>" class Executable name: null cmd: null key: null homepage: null installation: null versionArgs: ['--version'] versionParse: (text) -> semver.clean(text) versionRunOptions: {} versionsSupported: '>= 0.0.0' required: true constructor: (options) -> # Validation if !options.cmd? throw new Error("The command (i.e. cmd property) is required for an Executable.") @name = options.name @cmd = options.cmd @key = @cmd @homepage = options.homepage @installation = options.installation @required = not options.optional if options.version? versionOptions = options.version @versionArgs = versionOptions.args if versionOptions.args @versionParse = versionOptions.parse if versionOptions.parse @versionRunOptions = versionOptions.runOptions if versionOptions.runOptions @versionsSupported = versionOptions.supported if versionOptions.supported @setupLogger() init: () -> Promise.all([ @loadVersion() ]) .then(() => @verbose("Done init of #{@name}")) .then(() => @) .catch((error) => if not @.required @verbose("Not required") @ else Promise.reject(error) ) ### Logger instance ### logger: null ### Initialize and configure Logger ### setupLogger: -> @logger = require('../logger')("#{@name} Executable") for key, method of @logger @[key] = method @verbose("#{@name} executable logger has been initialized.") isInstalled = null version = null loadVersion: (force = false) -> @verbose("loadVersion", @version, force) if force or !@version? @verbose("Loading version without cache") @runVersion() .then((text) => @saveVersion(text)) else @verbose("Loading cached version") Promise.resolve(@version) runVersion: () -> @run(@versionArgs, @versionRunOptions) .then((version) => @info("Version text: " + version) version ) saveVersion: (text) -> Promise.resolve() .then( => @versionParse(text)) .then((version) -> valid = Boolean(semver.valid(version)) if not valid throw new Error("Version is not valid: "+version) version ) .then((version) => @isInstalled = true @version = version ) .then((version) => @info("#{@cmd} version: #{version}") version ) .catch((error) => @isInstalled = false @error(error) help = { program: @cmd link: @installation or @homepage pathOption: "Executable - #{@name or @cmd} - Path" } Promise.reject(@commandNotFoundError(@name or @cmd, help)) ) isSupported: () -> @isVersion(@versionsSupported) isVersion: (range) -> @versionSatisfies(@version, range) versionSatisfies: (version, range) -> semver.satisfies(version, range) getConfig: () -> atom?.config.get("#{parentConfigKey}.#{@key}") or {} ### Run command-line interface command ### run: (args, options = {}) -> @debug("Run: ", @cmd, args, options) { cmd, cwd, ignoreReturnCode, help, onStdin, returnStderr, returnStdoutOrStderr } = options exeName = cmd or @cmd cwd ?= os.tmpdir() help ?= { program: @cmd link: @installation or @homepage pathOption: "Executable - #{@name or @cmd} - Path" } # Resolve executable and all args Promise.all([@shellEnv(), this.resolveArgs(args)]) .then(([env, args]) => @debug('exeName, args:', exeName, args) # Get PATH and other environment variables exePath = @path(exeName) Promise.all([exeName, args, env, exePath]) ) .then(([exeName, args, env, exePath]) => @debug('exePath:', exePath) @debug('env:', env) @debug('PATH:', env.PATH) @debug('args', args) args = this.relativizePaths(args) @debug('relativized args', args) exe = exePath ? exeName spawnOptions = { cwd: cwd env: env } @debug('spawnOptions', spawnOptions) @spawn(exe, args, spawnOptions, onStdin) .then(({returnCode, stdout, stderr}) => @verbose('spawn result, returnCode', returnCode) @verbose('spawn result, stdout', stdout) @verbose('spawn result, stderr', stderr) # If return code is not 0 then error occured if not ignoreReturnCode and returnCode isnt 0 # operable program or batch file windowsProgramNotFoundMsg = "is not recognized as an internal or external command" @verbose(stderr, windowsProgramNotFoundMsg) if @isWindows() and returnCode is 1 and stderr.indexOf(windowsProgramNotFoundMsg) isnt -1 throw @commandNotFoundError(exeName, help) else throw new Error(stderr or stdout) else if returnStdoutOrStderr return stdout or stderr else if returnStderr stderr else stdout ) .catch((err) => @debug('error', err) # Check if error is ENOENT (command could not be found) if err.code is 'ENOENT' or err.errno is 'ENOENT' throw @commandNotFoundError(exeName, help) else # continue as normal error throw err ) ) path: (cmd = @cmd) -> config = @getConfig() if config and config.path Promise.resolve(config.path) else exeName = cmd @which(exeName) resolveArgs: (args) -> args = _.flatten(args) Promise.all(args) relativizePaths: (args) -> tmpDir = os.tmpdir() newArgs = args.map((arg) -> isTmpFile = (typeof arg is 'string' and not arg.includes(':') and \ path.isAbsolute(arg) and path.dirname(arg).startsWith(tmpDir)) if isTmpFile return path.relative(tmpDir, arg) return arg ) newArgs ### Spawn ### spawn: (exe, args, options, onStdin) -> # Remove undefined/null values args = _.without(args, undefined) args = _.without(args, null) return new Promise((resolve, reject) => @debug('spawn', exe, args) cmd = spawn(exe, args, options) stdout = "" stderr = "" cmd.stdout.on('data', (data) -> stdout += data ) cmd.stderr.on('data', (data) -> stderr += data ) cmd.on('close', (returnCode) => @debug('spawn done', returnCode, stderr, stdout) resolve({returnCode, stdout, stderr}) ) cmd.on('error', (err) => @debug('error', err) reject(err) ) onStdin cmd.stdin if onStdin ) ### Add help to error.description Note: error.description is not officially used in JavaScript, however it is used internally for Atom Beautify when displaying errors. ### commandNotFoundError: (exe, help) -> exe ?= @name or @cmd @constructor.commandNotFoundError(exe, help) @commandNotFoundError: (exe, help) -> # Create new improved error # notify user that it may not be # installed or in path message = "Could not find '#{exe}'. \ The program may not be installed." er = new Error(message) er.code = 'CommandNotFound' er.errno = er.code er.syscall = 'beautifier::run' er.file = exe if help? if typeof help is "object" # Basic notice docsLink = "https://github.com/Glavin001/atom-beautify#beautifiers" helpStr = "See #{exe} installation instructions at #{docsLink}#{if help.link then (' or go to '+help.link) else ''}\n" # # Help to configure Atom Beautify for program's path helpStr += "You can configure Atom Beautify \ with the absolute path \ to '#{help.program or exe}' by setting \ '#{help.pathOption}' in \ the Atom Beautify package settings.\n" if help.pathOption helpStr += "Your program is properly installed if running \ '#{if @isWindows() then 'where.exe' \ else 'which'} #{exe}' \ in your #{if @isWindows() then 'CMD prompt' \ else 'Terminal'} \ returns an absolute path to the executable.\n" # # Optional, additional help helpStr += help.additional if help.additional er.description = helpStr else #if typeof help is "string" er.description = help return er @_envCache = null shellEnv: () -> env = @constructor.shellEnv() @debug("env", env) return env @shellEnv: () -> Promise.resolve(process.env) ### Like the unix which utility. Finds the first instance of a specified executable in the PATH environment variable. Does not cache the results, so hash -r is not needed when the PATH changes. See https://github.com/isaacs/node-which ### which: (exe, options) -> @.constructor.which(exe, options) @_whichCache = {} @which: (exe, options = {}) -> if @_whichCache[exe] return Promise.resolve(@_whichCache[exe]) # Get PATH and other environment variables @shellEnv() .then((env) => new Promise((resolve, reject) => options.path ?= env.PATH if @isWindows() # Environment variables are case-insensitive in windows # Check env for a case-insensitive 'path' variable if !options.path for i of env if i.toLowerCase() is "path" options.path = env[i] break # Trick node-which into including files # with no extension as executables. # Put empty extension last to allow for other real extensions first options.pathExt ?= "#{process.env.PATHEXT ? '.EXE'};" which(exe, options, (err, path) => return resolve(exe) if err @_whichCache[exe] = path resolve(path) ) ) ) ### If platform is Windows ### isWindows: () -> @constructor.isWindows() @isWindows: () -> new RegExp('^win').test(process.platform) class HybridExecutable extends Executable dockerOptions: { image: undefined workingDir: "/workdir" } constructor: (options) -> super(options) @verbose("HybridExecutable Options", options) if options.docker? @dockerOptions = Object.assign({}, @dockerOptions, options.docker) @docker = @constructor.dockerExecutable() @docker: undefined @dockerExecutable: () -> if not @docker? @docker = new Executable({ name: "Docker" cmd: "docker" homepage: "https://www.docker.com/" installation: "https://www.docker.com/get-docker" version: { parse: (text) -> text.match(/version [0]*([1-9]\d*).[0]*([0-9]\d*).[0]*([0-9]\d*)/).slice(1).join('.') } }) return @docker installedWithDocker: false init: () -> super() .then(() => return @ ) .catch((error) => return Promise.reject(error) if not @docker? return Promise.resolve(error) ) .then((errorOrThis) => shouldTryWithDocker = not @isInstalled and @docker? @verbose("Executable shouldTryWithDocker", shouldTryWithDocker, @isInstalled, @docker?) if shouldTryWithDocker return @initDocker().catch(() -> Promise.reject(errorOrThis)) return @ ) .catch((error) => if not @.required @verbose("Not required") @ else Promise.reject(error) ) initDocker: () -> @docker.init() .then(=> @runImage(@versionArgs, @versionRunOptions)) .then((text) => @saveVersion(text)) .then(() => @installedWithDocker = true) .then(=> @) .catch((dockerError) => @debug(dockerError) Promise.reject(dockerError) ) run: (args, options = {}) -> @verbose("Running HybridExecutable") @verbose("installedWithDocker", @installedWithDocker) @verbose("docker", @docker) @verbose("docker.isInstalled", @docker and @docker.isInstalled) if @installedWithDocker and @docker and @docker.isInstalled return @runImage(args, options) super(args, options) runImage: (args, options) -> @debug("Run Docker executable: ", args, options) this.resolveArgs(args) .then((args) => { cwd } = options tmpDir = os.tmpdir() pwd = fs.realpathSync(cwd or tmpDir) image = @dockerOptions.image workingDir = @dockerOptions.workingDir rootPath = '/mountedRoot' newArgs = args.map((arg) -> if (typeof arg is 'string' and not arg.includes(':') \ and path.isAbsolute(arg) and not path.dirname(arg).startsWith(tmpDir)) \ then path.join(rootPath, arg) else arg ) @docker.run([ "run", "--volume", "#{pwd}:#{workingDir}", "--volume", "#{path.resolve('/')}:#{rootPath}", "--workdir", workingDir, image, newArgs ], Object.assign({}, options, { cmd: undefined }) ) ) module.exports = HybridExecutable
true
Promise = require('bluebird') _ = require('lodash') which = require('which') spawn = require('child_process').spawn path = require('path') semver = require('semver') os = require('os') fs = require('fs') parentConfigKey = "PI:KEY:<KEY>END_PI" class Executable name: null cmd: null key: null homepage: null installation: null versionArgs: ['--version'] versionParse: (text) -> semver.clean(text) versionRunOptions: {} versionsSupported: '>= 0.0.0' required: true constructor: (options) -> # Validation if !options.cmd? throw new Error("The command (i.e. cmd property) is required for an Executable.") @name = options.name @cmd = options.cmd @key = @cmd @homepage = options.homepage @installation = options.installation @required = not options.optional if options.version? versionOptions = options.version @versionArgs = versionOptions.args if versionOptions.args @versionParse = versionOptions.parse if versionOptions.parse @versionRunOptions = versionOptions.runOptions if versionOptions.runOptions @versionsSupported = versionOptions.supported if versionOptions.supported @setupLogger() init: () -> Promise.all([ @loadVersion() ]) .then(() => @verbose("Done init of #{@name}")) .then(() => @) .catch((error) => if not @.required @verbose("Not required") @ else Promise.reject(error) ) ### Logger instance ### logger: null ### Initialize and configure Logger ### setupLogger: -> @logger = require('../logger')("#{@name} Executable") for key, method of @logger @[key] = method @verbose("#{@name} executable logger has been initialized.") isInstalled = null version = null loadVersion: (force = false) -> @verbose("loadVersion", @version, force) if force or !@version? @verbose("Loading version without cache") @runVersion() .then((text) => @saveVersion(text)) else @verbose("Loading cached version") Promise.resolve(@version) runVersion: () -> @run(@versionArgs, @versionRunOptions) .then((version) => @info("Version text: " + version) version ) saveVersion: (text) -> Promise.resolve() .then( => @versionParse(text)) .then((version) -> valid = Boolean(semver.valid(version)) if not valid throw new Error("Version is not valid: "+version) version ) .then((version) => @isInstalled = true @version = version ) .then((version) => @info("#{@cmd} version: #{version}") version ) .catch((error) => @isInstalled = false @error(error) help = { program: @cmd link: @installation or @homepage pathOption: "Executable - #{@name or @cmd} - Path" } Promise.reject(@commandNotFoundError(@name or @cmd, help)) ) isSupported: () -> @isVersion(@versionsSupported) isVersion: (range) -> @versionSatisfies(@version, range) versionSatisfies: (version, range) -> semver.satisfies(version, range) getConfig: () -> atom?.config.get("#{parentConfigKey}.#{@key}") or {} ### Run command-line interface command ### run: (args, options = {}) -> @debug("Run: ", @cmd, args, options) { cmd, cwd, ignoreReturnCode, help, onStdin, returnStderr, returnStdoutOrStderr } = options exeName = cmd or @cmd cwd ?= os.tmpdir() help ?= { program: @cmd link: @installation or @homepage pathOption: "Executable - #{@name or @cmd} - Path" } # Resolve executable and all args Promise.all([@shellEnv(), this.resolveArgs(args)]) .then(([env, args]) => @debug('exeName, args:', exeName, args) # Get PATH and other environment variables exePath = @path(exeName) Promise.all([exeName, args, env, exePath]) ) .then(([exeName, args, env, exePath]) => @debug('exePath:', exePath) @debug('env:', env) @debug('PATH:', env.PATH) @debug('args', args) args = this.relativizePaths(args) @debug('relativized args', args) exe = exePath ? exeName spawnOptions = { cwd: cwd env: env } @debug('spawnOptions', spawnOptions) @spawn(exe, args, spawnOptions, onStdin) .then(({returnCode, stdout, stderr}) => @verbose('spawn result, returnCode', returnCode) @verbose('spawn result, stdout', stdout) @verbose('spawn result, stderr', stderr) # If return code is not 0 then error occured if not ignoreReturnCode and returnCode isnt 0 # operable program or batch file windowsProgramNotFoundMsg = "is not recognized as an internal or external command" @verbose(stderr, windowsProgramNotFoundMsg) if @isWindows() and returnCode is 1 and stderr.indexOf(windowsProgramNotFoundMsg) isnt -1 throw @commandNotFoundError(exeName, help) else throw new Error(stderr or stdout) else if returnStdoutOrStderr return stdout or stderr else if returnStderr stderr else stdout ) .catch((err) => @debug('error', err) # Check if error is ENOENT (command could not be found) if err.code is 'ENOENT' or err.errno is 'ENOENT' throw @commandNotFoundError(exeName, help) else # continue as normal error throw err ) ) path: (cmd = @cmd) -> config = @getConfig() if config and config.path Promise.resolve(config.path) else exeName = cmd @which(exeName) resolveArgs: (args) -> args = _.flatten(args) Promise.all(args) relativizePaths: (args) -> tmpDir = os.tmpdir() newArgs = args.map((arg) -> isTmpFile = (typeof arg is 'string' and not arg.includes(':') and \ path.isAbsolute(arg) and path.dirname(arg).startsWith(tmpDir)) if isTmpFile return path.relative(tmpDir, arg) return arg ) newArgs ### Spawn ### spawn: (exe, args, options, onStdin) -> # Remove undefined/null values args = _.without(args, undefined) args = _.without(args, null) return new Promise((resolve, reject) => @debug('spawn', exe, args) cmd = spawn(exe, args, options) stdout = "" stderr = "" cmd.stdout.on('data', (data) -> stdout += data ) cmd.stderr.on('data', (data) -> stderr += data ) cmd.on('close', (returnCode) => @debug('spawn done', returnCode, stderr, stdout) resolve({returnCode, stdout, stderr}) ) cmd.on('error', (err) => @debug('error', err) reject(err) ) onStdin cmd.stdin if onStdin ) ### Add help to error.description Note: error.description is not officially used in JavaScript, however it is used internally for Atom Beautify when displaying errors. ### commandNotFoundError: (exe, help) -> exe ?= @name or @cmd @constructor.commandNotFoundError(exe, help) @commandNotFoundError: (exe, help) -> # Create new improved error # notify user that it may not be # installed or in path message = "Could not find '#{exe}'. \ The program may not be installed." er = new Error(message) er.code = 'CommandNotFound' er.errno = er.code er.syscall = 'beautifier::run' er.file = exe if help? if typeof help is "object" # Basic notice docsLink = "https://github.com/Glavin001/atom-beautify#beautifiers" helpStr = "See #{exe} installation instructions at #{docsLink}#{if help.link then (' or go to '+help.link) else ''}\n" # # Help to configure Atom Beautify for program's path helpStr += "You can configure Atom Beautify \ with the absolute path \ to '#{help.program or exe}' by setting \ '#{help.pathOption}' in \ the Atom Beautify package settings.\n" if help.pathOption helpStr += "Your program is properly installed if running \ '#{if @isWindows() then 'where.exe' \ else 'which'} #{exe}' \ in your #{if @isWindows() then 'CMD prompt' \ else 'Terminal'} \ returns an absolute path to the executable.\n" # # Optional, additional help helpStr += help.additional if help.additional er.description = helpStr else #if typeof help is "string" er.description = help return er @_envCache = null shellEnv: () -> env = @constructor.shellEnv() @debug("env", env) return env @shellEnv: () -> Promise.resolve(process.env) ### Like the unix which utility. Finds the first instance of a specified executable in the PATH environment variable. Does not cache the results, so hash -r is not needed when the PATH changes. See https://github.com/isaacs/node-which ### which: (exe, options) -> @.constructor.which(exe, options) @_whichCache = {} @which: (exe, options = {}) -> if @_whichCache[exe] return Promise.resolve(@_whichCache[exe]) # Get PATH and other environment variables @shellEnv() .then((env) => new Promise((resolve, reject) => options.path ?= env.PATH if @isWindows() # Environment variables are case-insensitive in windows # Check env for a case-insensitive 'path' variable if !options.path for i of env if i.toLowerCase() is "path" options.path = env[i] break # Trick node-which into including files # with no extension as executables. # Put empty extension last to allow for other real extensions first options.pathExt ?= "#{process.env.PATHEXT ? '.EXE'};" which(exe, options, (err, path) => return resolve(exe) if err @_whichCache[exe] = path resolve(path) ) ) ) ### If platform is Windows ### isWindows: () -> @constructor.isWindows() @isWindows: () -> new RegExp('^win').test(process.platform) class HybridExecutable extends Executable dockerOptions: { image: undefined workingDir: "/workdir" } constructor: (options) -> super(options) @verbose("HybridExecutable Options", options) if options.docker? @dockerOptions = Object.assign({}, @dockerOptions, options.docker) @docker = @constructor.dockerExecutable() @docker: undefined @dockerExecutable: () -> if not @docker? @docker = new Executable({ name: "Docker" cmd: "docker" homepage: "https://www.docker.com/" installation: "https://www.docker.com/get-docker" version: { parse: (text) -> text.match(/version [0]*([1-9]\d*).[0]*([0-9]\d*).[0]*([0-9]\d*)/).slice(1).join('.') } }) return @docker installedWithDocker: false init: () -> super() .then(() => return @ ) .catch((error) => return Promise.reject(error) if not @docker? return Promise.resolve(error) ) .then((errorOrThis) => shouldTryWithDocker = not @isInstalled and @docker? @verbose("Executable shouldTryWithDocker", shouldTryWithDocker, @isInstalled, @docker?) if shouldTryWithDocker return @initDocker().catch(() -> Promise.reject(errorOrThis)) return @ ) .catch((error) => if not @.required @verbose("Not required") @ else Promise.reject(error) ) initDocker: () -> @docker.init() .then(=> @runImage(@versionArgs, @versionRunOptions)) .then((text) => @saveVersion(text)) .then(() => @installedWithDocker = true) .then(=> @) .catch((dockerError) => @debug(dockerError) Promise.reject(dockerError) ) run: (args, options = {}) -> @verbose("Running HybridExecutable") @verbose("installedWithDocker", @installedWithDocker) @verbose("docker", @docker) @verbose("docker.isInstalled", @docker and @docker.isInstalled) if @installedWithDocker and @docker and @docker.isInstalled return @runImage(args, options) super(args, options) runImage: (args, options) -> @debug("Run Docker executable: ", args, options) this.resolveArgs(args) .then((args) => { cwd } = options tmpDir = os.tmpdir() pwd = fs.realpathSync(cwd or tmpDir) image = @dockerOptions.image workingDir = @dockerOptions.workingDir rootPath = '/mountedRoot' newArgs = args.map((arg) -> if (typeof arg is 'string' and not arg.includes(':') \ and path.isAbsolute(arg) and not path.dirname(arg).startsWith(tmpDir)) \ then path.join(rootPath, arg) else arg ) @docker.run([ "run", "--volume", "#{pwd}:#{workingDir}", "--volume", "#{path.resolve('/')}:#{rootPath}", "--workdir", workingDir, image, newArgs ], Object.assign({}, options, { cmd: undefined }) ) ) module.exports = HybridExecutable
[ { "context": "# #\n# @author: Nino P. Cocchiarella #\n#\t Copyright (C) 2014 #\n# htt", "end": 109, "score": 0.9998654127120972, "start": 89, "tag": "NAME", "value": "Nino P. Cocchiarella" } ]
src/static/site/coffeescript/coffeescript/class.TriangleStrip.coffee
nino-c/plerp.org
0
##################################### # # # @author: Nino P. Cocchiarella # # Copyright (C) 2014 # # http://nino.cc # # # ##################################### root = Math.sqrt pi = Math.PI abs = Math.abs class TriangleStrip constructor: (@length, @side, @dir, @translation, @top) -> @triangles = [] @getTriangles() getTriangles: -> h = (root(3)/2) * @side for i in [0..@length] x = @side/2 * i if @dir y1 = 0 y2 = h else y1 = h y2 = 0 unless i%2 @triangles.push([ [x, y1], [x+(@side/2), y2], [x+@side, y1] ]) else @triangles.push([ [x, y2], [x+(@side/2), y1], [x+@side, y2] ]) translate: -> for i in [0..@length] for j in [0...3] @triangles[i][j][0] += @translation[0] @triangles[i][j][1] += @translation[1] draw: -> @translate() for i in [0...@triangles.length] tri = @triangles[i] # left-most side # only on the left-most iteration if i==0 gl.beginPath() gl.moveTo(tri[0][0], tri[0][1]) gl.lineTo(tri[1][0], tri[1][1]) gl.stroke() # right-most side # always draw gl.beginPath() gl.moveTo(tri[1][0], tri[1][1]) gl.lineTo(tri[2][0], tri[2][1]) gl.stroke() # horizontal side # if bottom, draw, if top, don't draw unless necessary draw = true draw = false if tri[1][1] > tri[0][1] and not @top draw = true if tri[1][1] > tri[0][1] and i%2==0 and i==0 if draw gl.beginPath() gl.moveTo(tri[2][0], tri[2][1]) gl.lineTo(tri[0][0], tri[0][1]) gl.stroke() class TriangleGrid constructor: (@width, @length, @size, @translation) -> @cells = [] @map = [] for i in [0...@length] trans = [@translation[0], @translation[1] + (@size * (root(3)/2) * i)] if i==0 then top = true else top = false dir = if i % 2 then true else false strip = new TriangleStrip(@width, @size, dir, trans, top) @cells.push(strip.triangles) @map[i] = [] for j in [0...strip.length] @map[i].push false strip.draw() triangleUp: (x, y) -> return true if y % 2 and x % 2 return false erase: ([from, to]) -> x = if from[0] < to[0] then from[0] else to[0] y = if from[1] < to[1] then from[1] else to[1] if from[1] == to[1] w = abs(from[0] - to[0]) - 2 h = 2 gl.clearRect(x+1, y-1, w, h) else w = abs(from[0] - to[0]) - 2 h = abs(from[1] - to[1]) - 2 gl.clearRect(x+1, y+1, w, h) removeWall: (x, y, side) -> #console.log [x,y,side] if @getSide(x, y, side) @erase(@getSide(x, y, side)) getSide: (x, y, side) -> switch side when 'T' return [@cells[y][x][2], @cells[y][x][0]] unless @triangleUp(x, y) when 'B' return [@cells[y][x][2], @cells[y][x][0]] if @triangleUp(x, y) when 'L' return [@cells[y][x][0], @cells[y][x][1]] when 'R' return [@cells[y][x][1], @cells[y][x][2]] else return null "Maze Generator pseudo-code 1. Make a random initial cell the current cell and mark it as visited 2. While there are unvisited cells 1. If the current cell has any neighbors which have not been visited 1. Choose randomly one of the unvisited neighbors 2. Push the chosen cell to the stack 3. Remove the wall between the current cell and the chosen cell 4. Make the chosen cell the current cell and mark it as visited 2. Otherwise 1. Pop a cell from the stack 2. Make it the current cell" class TriangleMaze constructor: (@width, @length, @size) -> @stack = [] @grid = new TriangleGrid @width, @length, @size, [50,50] @visited = @grid.map @startCell = null @currentCell = null @nextCell = null @frameInterval = setInterval (=> @renderStep()), 20 unvisitedCellsExist: -> for i in [0...@width] for j in [0...@length] unless @visited[i][j] return true return false chooseNeighbor: -> neighbors = [] # left if @currentCell[0] > 0 neighbors.push [[@currentCell[0]-1, @currentCell[1]], 'L'] # right if @currentCell[0] < @width - 1 neighbors.push [[@currentCell[0]+1, @currentCell[1]], 'R'] # above if @currentCell[1] > 0 unless @grid.triangleUp @currentCell[0], @currentCell[1] neighbors.push [[@currentCell[0], @currentCell[1]-1], 'T'] # beneath if @currentCell[1] < @length - 1 if @grid.triangleUp @currentCell[0], @currentCell[1] neighbors.push [[@currentCell[0], @currentCell[1]+1], 'B'] unvisitedNeighbors = [] for n in neighbors unless @visited[n[0][1]][n[0][0]] unvisitedNeighbors.push n if unvisitedNeighbors.length return unvisitedNeighbors[Math.floor(Math.random()*unvisitedNeighbors.length)] return null renderStep: -> unless @startCell? @currentCell = null @startCell = [Math.floor(Math.random() * @width), Math.floor(Math.random() * @length)] @currentCell = @startCell @visited[@startCell[1]][@startCell[0]] = true #@drawCurrentCellMarker() # if there are still unvisited cells if @unvisitedCellsExist() next = @chooseNeighbor() if (next) @nextCell = next[0] nextDirection = next[1] @stack.push [@nextCell[0], @nextCell[1]] @grid.removeWall @currentCell[0], @currentCell[1], nextDirection @visited[@nextCell[1]][@nextCell[0]] = true @currentCell = @nextCell else if @stack.length @currentCell = @stack.pop() else clearInterval @frameInterval else clearInterval @frameInterval canvas = null gl = null $(document).ready -> canvas = document.createElement('canvas') canvas.width = $(window).width() canvas.height = $(window).height() document.body.appendChild(canvas) gl = canvas.getContext("2d") gl.strokeStyle = '#333333' gl.lineWidth = 1 map = new TriangleMaze 70, 20, 30
197975
##################################### # # # @author: <NAME> # # Copyright (C) 2014 # # http://nino.cc # # # ##################################### root = Math.sqrt pi = Math.PI abs = Math.abs class TriangleStrip constructor: (@length, @side, @dir, @translation, @top) -> @triangles = [] @getTriangles() getTriangles: -> h = (root(3)/2) * @side for i in [0..@length] x = @side/2 * i if @dir y1 = 0 y2 = h else y1 = h y2 = 0 unless i%2 @triangles.push([ [x, y1], [x+(@side/2), y2], [x+@side, y1] ]) else @triangles.push([ [x, y2], [x+(@side/2), y1], [x+@side, y2] ]) translate: -> for i in [0..@length] for j in [0...3] @triangles[i][j][0] += @translation[0] @triangles[i][j][1] += @translation[1] draw: -> @translate() for i in [0...@triangles.length] tri = @triangles[i] # left-most side # only on the left-most iteration if i==0 gl.beginPath() gl.moveTo(tri[0][0], tri[0][1]) gl.lineTo(tri[1][0], tri[1][1]) gl.stroke() # right-most side # always draw gl.beginPath() gl.moveTo(tri[1][0], tri[1][1]) gl.lineTo(tri[2][0], tri[2][1]) gl.stroke() # horizontal side # if bottom, draw, if top, don't draw unless necessary draw = true draw = false if tri[1][1] > tri[0][1] and not @top draw = true if tri[1][1] > tri[0][1] and i%2==0 and i==0 if draw gl.beginPath() gl.moveTo(tri[2][0], tri[2][1]) gl.lineTo(tri[0][0], tri[0][1]) gl.stroke() class TriangleGrid constructor: (@width, @length, @size, @translation) -> @cells = [] @map = [] for i in [0...@length] trans = [@translation[0], @translation[1] + (@size * (root(3)/2) * i)] if i==0 then top = true else top = false dir = if i % 2 then true else false strip = new TriangleStrip(@width, @size, dir, trans, top) @cells.push(strip.triangles) @map[i] = [] for j in [0...strip.length] @map[i].push false strip.draw() triangleUp: (x, y) -> return true if y % 2 and x % 2 return false erase: ([from, to]) -> x = if from[0] < to[0] then from[0] else to[0] y = if from[1] < to[1] then from[1] else to[1] if from[1] == to[1] w = abs(from[0] - to[0]) - 2 h = 2 gl.clearRect(x+1, y-1, w, h) else w = abs(from[0] - to[0]) - 2 h = abs(from[1] - to[1]) - 2 gl.clearRect(x+1, y+1, w, h) removeWall: (x, y, side) -> #console.log [x,y,side] if @getSide(x, y, side) @erase(@getSide(x, y, side)) getSide: (x, y, side) -> switch side when 'T' return [@cells[y][x][2], @cells[y][x][0]] unless @triangleUp(x, y) when 'B' return [@cells[y][x][2], @cells[y][x][0]] if @triangleUp(x, y) when 'L' return [@cells[y][x][0], @cells[y][x][1]] when 'R' return [@cells[y][x][1], @cells[y][x][2]] else return null "Maze Generator pseudo-code 1. Make a random initial cell the current cell and mark it as visited 2. While there are unvisited cells 1. If the current cell has any neighbors which have not been visited 1. Choose randomly one of the unvisited neighbors 2. Push the chosen cell to the stack 3. Remove the wall between the current cell and the chosen cell 4. Make the chosen cell the current cell and mark it as visited 2. Otherwise 1. Pop a cell from the stack 2. Make it the current cell" class TriangleMaze constructor: (@width, @length, @size) -> @stack = [] @grid = new TriangleGrid @width, @length, @size, [50,50] @visited = @grid.map @startCell = null @currentCell = null @nextCell = null @frameInterval = setInterval (=> @renderStep()), 20 unvisitedCellsExist: -> for i in [0...@width] for j in [0...@length] unless @visited[i][j] return true return false chooseNeighbor: -> neighbors = [] # left if @currentCell[0] > 0 neighbors.push [[@currentCell[0]-1, @currentCell[1]], 'L'] # right if @currentCell[0] < @width - 1 neighbors.push [[@currentCell[0]+1, @currentCell[1]], 'R'] # above if @currentCell[1] > 0 unless @grid.triangleUp @currentCell[0], @currentCell[1] neighbors.push [[@currentCell[0], @currentCell[1]-1], 'T'] # beneath if @currentCell[1] < @length - 1 if @grid.triangleUp @currentCell[0], @currentCell[1] neighbors.push [[@currentCell[0], @currentCell[1]+1], 'B'] unvisitedNeighbors = [] for n in neighbors unless @visited[n[0][1]][n[0][0]] unvisitedNeighbors.push n if unvisitedNeighbors.length return unvisitedNeighbors[Math.floor(Math.random()*unvisitedNeighbors.length)] return null renderStep: -> unless @startCell? @currentCell = null @startCell = [Math.floor(Math.random() * @width), Math.floor(Math.random() * @length)] @currentCell = @startCell @visited[@startCell[1]][@startCell[0]] = true #@drawCurrentCellMarker() # if there are still unvisited cells if @unvisitedCellsExist() next = @chooseNeighbor() if (next) @nextCell = next[0] nextDirection = next[1] @stack.push [@nextCell[0], @nextCell[1]] @grid.removeWall @currentCell[0], @currentCell[1], nextDirection @visited[@nextCell[1]][@nextCell[0]] = true @currentCell = @nextCell else if @stack.length @currentCell = @stack.pop() else clearInterval @frameInterval else clearInterval @frameInterval canvas = null gl = null $(document).ready -> canvas = document.createElement('canvas') canvas.width = $(window).width() canvas.height = $(window).height() document.body.appendChild(canvas) gl = canvas.getContext("2d") gl.strokeStyle = '#333333' gl.lineWidth = 1 map = new TriangleMaze 70, 20, 30
true
##################################### # # # @author: PI:NAME:<NAME>END_PI # # Copyright (C) 2014 # # http://nino.cc # # # ##################################### root = Math.sqrt pi = Math.PI abs = Math.abs class TriangleStrip constructor: (@length, @side, @dir, @translation, @top) -> @triangles = [] @getTriangles() getTriangles: -> h = (root(3)/2) * @side for i in [0..@length] x = @side/2 * i if @dir y1 = 0 y2 = h else y1 = h y2 = 0 unless i%2 @triangles.push([ [x, y1], [x+(@side/2), y2], [x+@side, y1] ]) else @triangles.push([ [x, y2], [x+(@side/2), y1], [x+@side, y2] ]) translate: -> for i in [0..@length] for j in [0...3] @triangles[i][j][0] += @translation[0] @triangles[i][j][1] += @translation[1] draw: -> @translate() for i in [0...@triangles.length] tri = @triangles[i] # left-most side # only on the left-most iteration if i==0 gl.beginPath() gl.moveTo(tri[0][0], tri[0][1]) gl.lineTo(tri[1][0], tri[1][1]) gl.stroke() # right-most side # always draw gl.beginPath() gl.moveTo(tri[1][0], tri[1][1]) gl.lineTo(tri[2][0], tri[2][1]) gl.stroke() # horizontal side # if bottom, draw, if top, don't draw unless necessary draw = true draw = false if tri[1][1] > tri[0][1] and not @top draw = true if tri[1][1] > tri[0][1] and i%2==0 and i==0 if draw gl.beginPath() gl.moveTo(tri[2][0], tri[2][1]) gl.lineTo(tri[0][0], tri[0][1]) gl.stroke() class TriangleGrid constructor: (@width, @length, @size, @translation) -> @cells = [] @map = [] for i in [0...@length] trans = [@translation[0], @translation[1] + (@size * (root(3)/2) * i)] if i==0 then top = true else top = false dir = if i % 2 then true else false strip = new TriangleStrip(@width, @size, dir, trans, top) @cells.push(strip.triangles) @map[i] = [] for j in [0...strip.length] @map[i].push false strip.draw() triangleUp: (x, y) -> return true if y % 2 and x % 2 return false erase: ([from, to]) -> x = if from[0] < to[0] then from[0] else to[0] y = if from[1] < to[1] then from[1] else to[1] if from[1] == to[1] w = abs(from[0] - to[0]) - 2 h = 2 gl.clearRect(x+1, y-1, w, h) else w = abs(from[0] - to[0]) - 2 h = abs(from[1] - to[1]) - 2 gl.clearRect(x+1, y+1, w, h) removeWall: (x, y, side) -> #console.log [x,y,side] if @getSide(x, y, side) @erase(@getSide(x, y, side)) getSide: (x, y, side) -> switch side when 'T' return [@cells[y][x][2], @cells[y][x][0]] unless @triangleUp(x, y) when 'B' return [@cells[y][x][2], @cells[y][x][0]] if @triangleUp(x, y) when 'L' return [@cells[y][x][0], @cells[y][x][1]] when 'R' return [@cells[y][x][1], @cells[y][x][2]] else return null "Maze Generator pseudo-code 1. Make a random initial cell the current cell and mark it as visited 2. While there are unvisited cells 1. If the current cell has any neighbors which have not been visited 1. Choose randomly one of the unvisited neighbors 2. Push the chosen cell to the stack 3. Remove the wall between the current cell and the chosen cell 4. Make the chosen cell the current cell and mark it as visited 2. Otherwise 1. Pop a cell from the stack 2. Make it the current cell" class TriangleMaze constructor: (@width, @length, @size) -> @stack = [] @grid = new TriangleGrid @width, @length, @size, [50,50] @visited = @grid.map @startCell = null @currentCell = null @nextCell = null @frameInterval = setInterval (=> @renderStep()), 20 unvisitedCellsExist: -> for i in [0...@width] for j in [0...@length] unless @visited[i][j] return true return false chooseNeighbor: -> neighbors = [] # left if @currentCell[0] > 0 neighbors.push [[@currentCell[0]-1, @currentCell[1]], 'L'] # right if @currentCell[0] < @width - 1 neighbors.push [[@currentCell[0]+1, @currentCell[1]], 'R'] # above if @currentCell[1] > 0 unless @grid.triangleUp @currentCell[0], @currentCell[1] neighbors.push [[@currentCell[0], @currentCell[1]-1], 'T'] # beneath if @currentCell[1] < @length - 1 if @grid.triangleUp @currentCell[0], @currentCell[1] neighbors.push [[@currentCell[0], @currentCell[1]+1], 'B'] unvisitedNeighbors = [] for n in neighbors unless @visited[n[0][1]][n[0][0]] unvisitedNeighbors.push n if unvisitedNeighbors.length return unvisitedNeighbors[Math.floor(Math.random()*unvisitedNeighbors.length)] return null renderStep: -> unless @startCell? @currentCell = null @startCell = [Math.floor(Math.random() * @width), Math.floor(Math.random() * @length)] @currentCell = @startCell @visited[@startCell[1]][@startCell[0]] = true #@drawCurrentCellMarker() # if there are still unvisited cells if @unvisitedCellsExist() next = @chooseNeighbor() if (next) @nextCell = next[0] nextDirection = next[1] @stack.push [@nextCell[0], @nextCell[1]] @grid.removeWall @currentCell[0], @currentCell[1], nextDirection @visited[@nextCell[1]][@nextCell[0]] = true @currentCell = @nextCell else if @stack.length @currentCell = @stack.pop() else clearInterval @frameInterval else clearInterval @frameInterval canvas = null gl = null $(document).ready -> canvas = document.createElement('canvas') canvas.width = $(window).width() canvas.height = $(window).height() document.body.appendChild(canvas) gl = canvas.getContext("2d") gl.strokeStyle = '#333333' gl.lineWidth = 1 map = new TriangleMaze 70, 20, 30
[ { "context": " 3\n \"body[0].username\": \"root\"\n \"body[0].name\": \"Administr", "end": 1496, "score": 0.9992363452911377, "start": 1492, "tag": "USERNAME", "value": "root" }, { "context": "level\": 50\n \"body[1].username\": \"jenkinsci\"\n \"body[1].name\": \"Jenkins\"\n", "end": 1641, "score": 0.9995667338371277, "start": 1632, "tag": "USERNAME", "value": "jenkinsci" }, { "context": "level\": 50\n \"body[2].username\": \"boze\"\n \"body[2].name\": \"BOZE, Tar", "end": 1775, "score": 0.9996122121810913, "start": 1771, "tag": "USERNAME", "value": "boze" }, { "context": " \"boze\"\n \"body[2].name\": \"BOZE, Taro\"\n \"body[2].access_level\": 50\n\n ", "end": 1826, "score": 0.9997240304946899, "start": 1816, "tag": "NAME", "value": "BOZE, Taro" }, { "context": "\n yield gitlab.login(setup.browser, @url, \"jenkinsci\", \"password\")\n src = yield setup.browser\n ", "end": 5227, "score": 0.9994919300079346, "start": 5218, "tag": "USERNAME", "value": "jenkinsci" }, { "context": "d gitlab.login(setup.browser, @url, \"jenkinsci\", \"password\")\n src = yield setup.browser\n .sa", "end": 5239, "score": 0.9980632066726685, "start": 5231, "tag": "PASSWORD", "value": "password" }, { "context": "xOf(\"jenkinsci.png\") > -1, \"Invalid avatar of jenkinsci\")\n\n\n it \"pocci\", (done) ->\n test done,\n ", "end": 5506, "score": 0.5972926616668701, "start": 5504, "tag": "USERNAME", "value": "in" }, { "context": "kinsci\")\n chai.assert.equal(attrs[0].cn, \"jenkinsci\")\n chai.assert.equal(attrs[0].sn, \"CI\")\n ", "end": 7838, "score": 0.9962193369865417, "start": 7830, "tag": "NAME", "value": "enkinsci" }, { "context": "\")\n chai.assert.equal(attrs[0].givenName, \"Jenkins\")\n chai.assert.equal(attrs[0].displayName,", "end": 7940, "score": 0.9881086349487305, "start": 7933, "tag": "NAME", "value": "Jenkins" }, { "context": "\n chai.assert.equal(attrs[0].displayName, \"Jenkins\")\n chai.assert.equal(attrs[0].mail, \"jenki", "end": 7999, "score": 0.9864602088928223, "start": 7992, "tag": "NAME", "value": "Jenkins" }, { "context": "nkins\")\n chai.assert.equal(attrs[0].mail, \"jenkins-ci@localhost.localdomain\")\n chai.assert.equal(attrs[0].labeledURI, ", "end": 8076, "score": 0.9998419880867004, "start": 8044, "tag": "EMAIL", "value": "jenkins-ci@localhost.localdomain" }, { "context": "\")\n chai.assert.equal(attrs[1].givenName, \"Taro\")\n chai.assert.equal(attrs[1].displayName,", "end": 8455, "score": 0.9902743101119995, "start": 8451, "tag": "NAME", "value": "Taro" }, { "context": "\n chai.assert.equal(attrs[1].displayName, \"BOZE, Taro\")\n chai.assert.equal(attrs[1].mail, \"", "end": 8511, "score": 0.9813364148139954, "start": 8507, "tag": "NAME", "value": "BOZE" }, { "context": " chai.assert.equal(attrs[1].displayName, \"BOZE, Taro\")\n chai.assert.equal(attrs[1].mail, \"boze@", "end": 8517, "score": 0.8760305643081665, "start": 8513, "tag": "NAME", "value": "Taro" }, { "context": " Taro\")\n chai.assert.equal(attrs[1].mail, \"boze@localhost.localdomain\")\n chai.assert.equal(attrs[1].labeledURI, ", "end": 8588, "score": 0.9997183680534363, "start": 8562, "tag": "EMAIL", "value": "boze@localhost.localdomain" }, { "context": "gesets .changeset:nth-child(even) a\": new RegExp(@revisionJava)\n issueNode:\n path: \"/issues/", "end": 9792, "score": 0.7434676289558411, "start": 9780, "tag": "USERNAME", "value": "revisionJava" }, { "context": "ngesets .changeset:nth-child(odd) a\": new RegExp(@revisionNode)\n\n @request = yield redmine.createRequ", "end": 9950, "score": 0.6637725234031677, "start": 9942, "tag": "USERNAME", "value": "revision" }, { "context": " 3\n \"body.users[0].login\": \"admin\"\n \"body.users[0].firstname\": \"R", "end": 10682, "score": 0.9746708273887634, "start": 10677, "tag": "USERNAME", "value": "admin" }, { "context": "n\"\n \"body.users[0].mail\": \"pocci@localhost.localdomain\"\n \"body.users[1].login\": \"j", "end": 10868, "score": 0.9988280534744263, "start": 10841, "tag": "EMAIL", "value": "pocci@localhost.localdomain" }, { "context": "n\"\n \"body.users[1].login\": \"jenkinsci\"\n \"body.users[1].firstname\": \"J", "end": 10926, "score": 0.994505763053894, "start": 10917, "tag": "USERNAME", "value": "jenkinsci" }, { "context": "I\"\n \"body.users[1].mail\": \"jenkins-ci@localhost.localdomain\"\n \"body.users[2].login\": \"b", "end": 11114, "score": 0.9988314509391785, "start": 11082, "tag": "EMAIL", "value": "jenkins-ci@localhost.localdomain" }, { "context": "n\"\n \"body.users[2].login\": \"boze\"\n \"body.users[2].firstname\": \"T", "end": 11167, "score": 0.9893739819526672, "start": 11163, "tag": "USERNAME", "value": "boze" }, { "context": "E\"\n \"body.users[2].mail\": \"boze@localhost.localdomain\"\n\n issues:\n path: \"/issues.", "end": 11348, "score": 0.9985403418540955, "start": 11322, "tag": "EMAIL", "value": "boze@localhost.localdomain" }, { "context": " \"body.memberships[0].user.name\": \"Jenkins CI\"\n \"body.memberships[0].role", "end": 12050, "score": 0.555938184261322, "start": 12049, "tag": "NAME", "value": "J" }, { "context": " \"body.memberships[0].user.name\": \"Jenkins CI\"\n \"body.memberships[0].roles.length\"", "end": 12059, "score": 0.8568124175071716, "start": 12050, "tag": "USERNAME", "value": "enkins CI" }, { "context": " \"body.memberships[1].user.name\": \"Taro BOZE\"\n \"body.memberships[1].roles.length\"", "end": 12285, "score": 0.9998488426208496, "start": 12276, "tag": "NAME", "value": "Taro BOZE" }, { "context": " yield redmine.login(setup.browser, url, \"boze\", \"password\")\n return\n\n cleanup: ->\n yield", "end": 12649, "score": 0.9724323749542236, "start": 12641, "tag": "PASSWORD", "value": "password" } ]
bin/js/test/redmineSetupTest.coffee
xpfriend/pocci
1
###global describe, it, before, after### ###jshint quotmark:true### "use strict" path = require("path") setup = require("pocci/setup.js") gitlab = require("pocci/gitlab.js") redmine = require("pocci/redmine.js") test = require("./resq.js") chai = require("chai") LdapClient = require("promised-ldap") describe "setup.redmine.yml", -> @timeout(10 * 60 * 1000) before (done) -> test done, setup: -> yield setup.initBrowser() after (done) -> test done, cleanup: -> yield setup.browser.end() it "gitlab", (done) -> test done, setup: -> @url = "http://gitlab.pocci.test" yield gitlab.loginByAdmin(setup.browser, @url) @request = yield gitlab.createRequest(setup.browser, @url) yield gitlab.logout(setup.browser) expect: -> @groupId = yield @get("body[0].id@/groups?search=example", true) @projectIdJava = yield @get("body[0].id@/projects/search/example-java", true) @projectIdNode = yield @get("body[0].id@/projects/search/example-nodejs", true) yield @assert group: path: "/groups" expected: "body.length": 1 "body[0].id": @groupId "body[0].name": "example" members: path: "/groups/#{@groupId}/members" sort: {target: "body", keys: "id"} expected: "body.length": 3 "body[0].username": "root" "body[0].name": "Administrator" "body[0].access_level": 50 "body[1].username": "jenkinsci" "body[1].name": "Jenkins" "body[1].access_level": 50 "body[2].username": "boze" "body[2].name": "BOZE, Taro" "body[2].access_level": 50 projects: path: "/projects" sort: {target: "body", keys: "id"} expected: "body.length": 2 "body[0].id": @projectIdJava "body[0].name": "example-java" "body[0].public": true "body[0].namespace.id": @groupId "body[0].namespace.name": "example" "body[1].id": @projectIdNode "body[1].name": "example-nodejs" "body[1].public": true "body[1].namespace.id": @groupId "body[1].namespace.name": "example" projectJavaFiles: path: "/projects/#{@projectIdJava}/repository/tree" sort: {target: "body", keys: "name"} expected: "body.length": 5 "body[0].name": ".gitignore" "body[1].name": "build.sh" "body[2].name": "jenkins-config.xml" "body[3].name": "pom.xml" "body[4].name": "src" projectJavaIssues: path: "/projects/#{@projectIdJava}/issues" expected: "body.length": 0 projectJavaLabels: path: "/projects/#{@projectIdJava}/labels" sort: {target: "body", keys: "name"} expected: "body.length": 0 projectJavaHooks: path: "/projects/#{@projectIdJava}/hooks" expected: "body.length": 1 "body[0].url": "http://jenkins.pocci.test/project/example-java" "body[0].push_events": true "body[0].issues_events": false "body[0].merge_requests_events":true "body[0].tag_push_events": false projectNodeFiles: path: "/projects/#{@projectIdNode}/repository/tree" sort: {target: "body", keys: "name"} expected: "body.length": 9 "body[0].name": ".gitignore" "body[1].name": "Gruntfile.js" "body[2].name": "app" "body[3].name": "bower.json" "body[4].name": "build.sh" "body[5].name": "jenkins-config.xml" "body[6].name": "karma.conf.js" "body[7].name": "package.json" "body[8].name": "test" projectNodeIssues: path: "/projects/#{@projectIdNode}/issues" expected: "body.length": 0 projectNodeLabels: path: "/projects/#{@projectIdNode}/labels" expected: "body.length": 0 projectNodeHooks: path: "/projects/#{@projectIdNode}/hooks" expected: "body.length": 1 "body[0].url": "http://jenkins.pocci.test/project/example-nodejs" "body[0].push_events": true "body[0].issues_events": false "body[0].merge_requests_events":true "body[0].tag_push_events": false yield gitlab.login(setup.browser, @url, "jenkinsci", "password") src = yield setup.browser .save("gitlab-login-by-jenkinsci") .getAttribute("img.header-user-avatar", "src") yield gitlab.logout(setup.browser) chai.assert.isOk(src.indexOf("jenkinsci.png") > -1, "Invalid avatar of jenkinsci") it "pocci", (done) -> test done, expect: -> yield @assert sonar: path: "http://sonar.pocci.test" expected: "title": "SonarQube" redmine: path: "http://redmine.pocci.test" expected: "title": "Redmine" taiga: path: "http://taiga.pocci.test" thrown: "code": "ENOTFOUND" "hostname": "taiga.pocci.test" chai.assert.equal(process.env.TZ, "Etc/UTC") it "jenkins", (done) -> test done, setup: -> url = "http://jenkins.pocci.test" @request = (path) -> url: url + path + "/api/json" json: true return expect: -> yield @assert jobs: path: "" debug: true expected: "body.jobs.length": 2 "body.jobs[0].name": "example-java" "body.jobs[0].url": "http://jenkins.pocci.test/job/example-java/" "body.jobs[1].name": "example-nodejs" "body.jobs[1].url": "http://jenkins.pocci.test/job/example-nodejs/" nodes: path: "/computer" expected: "body.computer.length": 3 "body.computer[0].displayName": "master" "body.computer[0].offline": false "body.computer[1].displayName": "java" "body.computer[1].offline": false "body.computer[2].displayName": "nodejs" "body.computer[2].offline": false it "user", (done) -> test done, expect: -> client = new LdapClient({url: "ldap://user.pocci.test"}) dn = "cn=admin,dc=example,dc=com" yield client.bind(dn, "admin") result = yield client.search "dc=example,dc=com", scope: "one" filter: "(uid=*)" chai.assert.equal(result.entries.length, 2) attrs = [] for entry in result.entries obj = {} for attribute in entry.attributes obj[attribute.type] = attribute.vals[0] attrs.push(obj) console.log(attrs) chai.assert.equal(attrs[0].uid, "jenkinsci") chai.assert.equal(attrs[0].cn, "jenkinsci") chai.assert.equal(attrs[0].sn, "CI") chai.assert.equal(attrs[0].givenName, "Jenkins") chai.assert.equal(attrs[0].displayName, "Jenkins") chai.assert.equal(attrs[0].mail, "jenkins-ci@localhost.localdomain") chai.assert.equal(attrs[0].labeledURI, "https://wiki.jenkins-ci.org/download/attachments/2916393/headshot.png") chai.assert.match(attrs[0].userPassword, /^{SSHA}.+/) chai.assert.equal(attrs[1].uid, "boze") chai.assert.equal(attrs[1].cn, "boze") chai.assert.equal(attrs[1].sn, "BOZE") chai.assert.equal(attrs[1].givenName, "Taro") chai.assert.equal(attrs[1].displayName, "BOZE, Taro") chai.assert.equal(attrs[1].mail, "boze@localhost.localdomain") chai.assert.equal(attrs[1].labeledURI, undefined) chai.assert.match(attrs[1].userPassword, /^{SSHA}.+/) it "redmine", (done) -> url = "http://redmine.pocci.test" test done, setup: -> yield redmine.loginByAdmin(setup.browser, url) return cleanup: -> yield redmine.logout(setup.browser) expect: -> @request = (path) -> url: url + path @revisionJava = yield @get(".changeset a@/projects/example/repository", true) @revisionNode = yield @get(".changeset a@/projects/example/repository/example-nodejs", true) yield @assert repositoryJava: path: "/projects/example/repository" expected: "h2": /example-java[\s\S]*@[\s\S]*master/ "a[href='/issues/1']": "#1" repositoryNode: path: "/projects/example/repository/example-nodejs" expected: "h2": /example-nodejs[\s\S]*@[\s\S]*master/ "a[href='/issues/1']": "#1" issueJava: path: "/issues/1" expected: "#issue-changesets .changeset:nth-child(even) a": new RegExp(@revisionJava) issueNode: path: "/issues/1" expected: "#issue-changesets .changeset:nth-child(odd) a": new RegExp(@revisionNode) @request = yield redmine.createRequest(setup.browser, url) yield @assert projects: path: "/projects.json" expected: "body.total_count": 1 "body.projects.length": 1 "body.projects[0].id": 1 "body.projects[0].name": "example" "body.projects[0].identifier": "example" users: path: "/users.json" debug: true sort: {target: "body.users", keys: "id"} expected: "body.total_count": 3 "body.users.length": 3 "body.users[0].login": "admin" "body.users[0].firstname": "Redmine" "body.users[0].lastname": "Admin" "body.users[0].mail": "pocci@localhost.localdomain" "body.users[1].login": "jenkinsci" "body.users[1].firstname": "Jenkins" "body.users[1].lastname": "CI" "body.users[1].mail": "jenkins-ci@localhost.localdomain" "body.users[2].login": "boze" "body.users[2].firstname": "Taro" "body.users[2].lastname": "BOZE" "body.users[2].mail": "boze@localhost.localdomain" issues: path: "/issues.json" expected: "body.total_count": 1 "body.issues.length": 1 "body.issues[0].id": 1 "body.issues[0].project.id": 1 "body.issues[0].project.name": "example" "body.issues[0].status.id": 1 "body.issues[0].subject": "import example codes" memberships: path: "/projects/1/memberships.json" expected: "body.total_count": 2 "body.memberships.length": 2 "body.memberships[0].user.name": "Jenkins CI" "body.memberships[0].roles.length": 2 "body.memberships[0].roles[0].id": 3 "body.memberships[0].roles[1].id": 4 "body.memberships[1].user.name": "Taro BOZE" "body.memberships[1].roles.length": 2 "body.memberships[1].roles[0].id": 3 "body.memberships[1].roles[1].id": 4 it "redmine (defalut user language)", (done) -> url = "http://redmine.pocci.test" test done, setup: -> yield redmine.login(setup.browser, url, "boze", "password") return cleanup: -> yield redmine.logout(setup.browser) expect: -> value = yield setup.browser.url("#{url}/my/account") .getText("#user_language [selected]") chai.assert.equal(value, "(auto)")
192530
###global describe, it, before, after### ###jshint quotmark:true### "use strict" path = require("path") setup = require("pocci/setup.js") gitlab = require("pocci/gitlab.js") redmine = require("pocci/redmine.js") test = require("./resq.js") chai = require("chai") LdapClient = require("promised-ldap") describe "setup.redmine.yml", -> @timeout(10 * 60 * 1000) before (done) -> test done, setup: -> yield setup.initBrowser() after (done) -> test done, cleanup: -> yield setup.browser.end() it "gitlab", (done) -> test done, setup: -> @url = "http://gitlab.pocci.test" yield gitlab.loginByAdmin(setup.browser, @url) @request = yield gitlab.createRequest(setup.browser, @url) yield gitlab.logout(setup.browser) expect: -> @groupId = yield @get("body[0].id@/groups?search=example", true) @projectIdJava = yield @get("body[0].id@/projects/search/example-java", true) @projectIdNode = yield @get("body[0].id@/projects/search/example-nodejs", true) yield @assert group: path: "/groups" expected: "body.length": 1 "body[0].id": @groupId "body[0].name": "example" members: path: "/groups/#{@groupId}/members" sort: {target: "body", keys: "id"} expected: "body.length": 3 "body[0].username": "root" "body[0].name": "Administrator" "body[0].access_level": 50 "body[1].username": "jenkinsci" "body[1].name": "Jenkins" "body[1].access_level": 50 "body[2].username": "boze" "body[2].name": "<NAME>" "body[2].access_level": 50 projects: path: "/projects" sort: {target: "body", keys: "id"} expected: "body.length": 2 "body[0].id": @projectIdJava "body[0].name": "example-java" "body[0].public": true "body[0].namespace.id": @groupId "body[0].namespace.name": "example" "body[1].id": @projectIdNode "body[1].name": "example-nodejs" "body[1].public": true "body[1].namespace.id": @groupId "body[1].namespace.name": "example" projectJavaFiles: path: "/projects/#{@projectIdJava}/repository/tree" sort: {target: "body", keys: "name"} expected: "body.length": 5 "body[0].name": ".gitignore" "body[1].name": "build.sh" "body[2].name": "jenkins-config.xml" "body[3].name": "pom.xml" "body[4].name": "src" projectJavaIssues: path: "/projects/#{@projectIdJava}/issues" expected: "body.length": 0 projectJavaLabels: path: "/projects/#{@projectIdJava}/labels" sort: {target: "body", keys: "name"} expected: "body.length": 0 projectJavaHooks: path: "/projects/#{@projectIdJava}/hooks" expected: "body.length": 1 "body[0].url": "http://jenkins.pocci.test/project/example-java" "body[0].push_events": true "body[0].issues_events": false "body[0].merge_requests_events":true "body[0].tag_push_events": false projectNodeFiles: path: "/projects/#{@projectIdNode}/repository/tree" sort: {target: "body", keys: "name"} expected: "body.length": 9 "body[0].name": ".gitignore" "body[1].name": "Gruntfile.js" "body[2].name": "app" "body[3].name": "bower.json" "body[4].name": "build.sh" "body[5].name": "jenkins-config.xml" "body[6].name": "karma.conf.js" "body[7].name": "package.json" "body[8].name": "test" projectNodeIssues: path: "/projects/#{@projectIdNode}/issues" expected: "body.length": 0 projectNodeLabels: path: "/projects/#{@projectIdNode}/labels" expected: "body.length": 0 projectNodeHooks: path: "/projects/#{@projectIdNode}/hooks" expected: "body.length": 1 "body[0].url": "http://jenkins.pocci.test/project/example-nodejs" "body[0].push_events": true "body[0].issues_events": false "body[0].merge_requests_events":true "body[0].tag_push_events": false yield gitlab.login(setup.browser, @url, "jenkinsci", "<PASSWORD>") src = yield setup.browser .save("gitlab-login-by-jenkinsci") .getAttribute("img.header-user-avatar", "src") yield gitlab.logout(setup.browser) chai.assert.isOk(src.indexOf("jenkinsci.png") > -1, "Invalid avatar of jenkinsci") it "pocci", (done) -> test done, expect: -> yield @assert sonar: path: "http://sonar.pocci.test" expected: "title": "SonarQube" redmine: path: "http://redmine.pocci.test" expected: "title": "Redmine" taiga: path: "http://taiga.pocci.test" thrown: "code": "ENOTFOUND" "hostname": "taiga.pocci.test" chai.assert.equal(process.env.TZ, "Etc/UTC") it "jenkins", (done) -> test done, setup: -> url = "http://jenkins.pocci.test" @request = (path) -> url: url + path + "/api/json" json: true return expect: -> yield @assert jobs: path: "" debug: true expected: "body.jobs.length": 2 "body.jobs[0].name": "example-java" "body.jobs[0].url": "http://jenkins.pocci.test/job/example-java/" "body.jobs[1].name": "example-nodejs" "body.jobs[1].url": "http://jenkins.pocci.test/job/example-nodejs/" nodes: path: "/computer" expected: "body.computer.length": 3 "body.computer[0].displayName": "master" "body.computer[0].offline": false "body.computer[1].displayName": "java" "body.computer[1].offline": false "body.computer[2].displayName": "nodejs" "body.computer[2].offline": false it "user", (done) -> test done, expect: -> client = new LdapClient({url: "ldap://user.pocci.test"}) dn = "cn=admin,dc=example,dc=com" yield client.bind(dn, "admin") result = yield client.search "dc=example,dc=com", scope: "one" filter: "(uid=*)" chai.assert.equal(result.entries.length, 2) attrs = [] for entry in result.entries obj = {} for attribute in entry.attributes obj[attribute.type] = attribute.vals[0] attrs.push(obj) console.log(attrs) chai.assert.equal(attrs[0].uid, "jenkinsci") chai.assert.equal(attrs[0].cn, "j<NAME>") chai.assert.equal(attrs[0].sn, "CI") chai.assert.equal(attrs[0].givenName, "<NAME>") chai.assert.equal(attrs[0].displayName, "<NAME>") chai.assert.equal(attrs[0].mail, "<EMAIL>") chai.assert.equal(attrs[0].labeledURI, "https://wiki.jenkins-ci.org/download/attachments/2916393/headshot.png") chai.assert.match(attrs[0].userPassword, /^{SSHA}.+/) chai.assert.equal(attrs[1].uid, "boze") chai.assert.equal(attrs[1].cn, "boze") chai.assert.equal(attrs[1].sn, "BOZE") chai.assert.equal(attrs[1].givenName, "<NAME>") chai.assert.equal(attrs[1].displayName, "<NAME>, <NAME>") chai.assert.equal(attrs[1].mail, "<EMAIL>") chai.assert.equal(attrs[1].labeledURI, undefined) chai.assert.match(attrs[1].userPassword, /^{SSHA}.+/) it "redmine", (done) -> url = "http://redmine.pocci.test" test done, setup: -> yield redmine.loginByAdmin(setup.browser, url) return cleanup: -> yield redmine.logout(setup.browser) expect: -> @request = (path) -> url: url + path @revisionJava = yield @get(".changeset a@/projects/example/repository", true) @revisionNode = yield @get(".changeset a@/projects/example/repository/example-nodejs", true) yield @assert repositoryJava: path: "/projects/example/repository" expected: "h2": /example-java[\s\S]*@[\s\S]*master/ "a[href='/issues/1']": "#1" repositoryNode: path: "/projects/example/repository/example-nodejs" expected: "h2": /example-nodejs[\s\S]*@[\s\S]*master/ "a[href='/issues/1']": "#1" issueJava: path: "/issues/1" expected: "#issue-changesets .changeset:nth-child(even) a": new RegExp(@revisionJava) issueNode: path: "/issues/1" expected: "#issue-changesets .changeset:nth-child(odd) a": new RegExp(@revisionNode) @request = yield redmine.createRequest(setup.browser, url) yield @assert projects: path: "/projects.json" expected: "body.total_count": 1 "body.projects.length": 1 "body.projects[0].id": 1 "body.projects[0].name": "example" "body.projects[0].identifier": "example" users: path: "/users.json" debug: true sort: {target: "body.users", keys: "id"} expected: "body.total_count": 3 "body.users.length": 3 "body.users[0].login": "admin" "body.users[0].firstname": "Redmine" "body.users[0].lastname": "Admin" "body.users[0].mail": "<EMAIL>" "body.users[1].login": "jenkinsci" "body.users[1].firstname": "Jenkins" "body.users[1].lastname": "CI" "body.users[1].mail": "<EMAIL>" "body.users[2].login": "boze" "body.users[2].firstname": "Taro" "body.users[2].lastname": "BOZE" "body.users[2].mail": "<EMAIL>" issues: path: "/issues.json" expected: "body.total_count": 1 "body.issues.length": 1 "body.issues[0].id": 1 "body.issues[0].project.id": 1 "body.issues[0].project.name": "example" "body.issues[0].status.id": 1 "body.issues[0].subject": "import example codes" memberships: path: "/projects/1/memberships.json" expected: "body.total_count": 2 "body.memberships.length": 2 "body.memberships[0].user.name": "<NAME>enkins CI" "body.memberships[0].roles.length": 2 "body.memberships[0].roles[0].id": 3 "body.memberships[0].roles[1].id": 4 "body.memberships[1].user.name": "<NAME>" "body.memberships[1].roles.length": 2 "body.memberships[1].roles[0].id": 3 "body.memberships[1].roles[1].id": 4 it "redmine (defalut user language)", (done) -> url = "http://redmine.pocci.test" test done, setup: -> yield redmine.login(setup.browser, url, "boze", "<PASSWORD>") return cleanup: -> yield redmine.logout(setup.browser) expect: -> value = yield setup.browser.url("#{url}/my/account") .getText("#user_language [selected]") chai.assert.equal(value, "(auto)")
true
###global describe, it, before, after### ###jshint quotmark:true### "use strict" path = require("path") setup = require("pocci/setup.js") gitlab = require("pocci/gitlab.js") redmine = require("pocci/redmine.js") test = require("./resq.js") chai = require("chai") LdapClient = require("promised-ldap") describe "setup.redmine.yml", -> @timeout(10 * 60 * 1000) before (done) -> test done, setup: -> yield setup.initBrowser() after (done) -> test done, cleanup: -> yield setup.browser.end() it "gitlab", (done) -> test done, setup: -> @url = "http://gitlab.pocci.test" yield gitlab.loginByAdmin(setup.browser, @url) @request = yield gitlab.createRequest(setup.browser, @url) yield gitlab.logout(setup.browser) expect: -> @groupId = yield @get("body[0].id@/groups?search=example", true) @projectIdJava = yield @get("body[0].id@/projects/search/example-java", true) @projectIdNode = yield @get("body[0].id@/projects/search/example-nodejs", true) yield @assert group: path: "/groups" expected: "body.length": 1 "body[0].id": @groupId "body[0].name": "example" members: path: "/groups/#{@groupId}/members" sort: {target: "body", keys: "id"} expected: "body.length": 3 "body[0].username": "root" "body[0].name": "Administrator" "body[0].access_level": 50 "body[1].username": "jenkinsci" "body[1].name": "Jenkins" "body[1].access_level": 50 "body[2].username": "boze" "body[2].name": "PI:NAME:<NAME>END_PI" "body[2].access_level": 50 projects: path: "/projects" sort: {target: "body", keys: "id"} expected: "body.length": 2 "body[0].id": @projectIdJava "body[0].name": "example-java" "body[0].public": true "body[0].namespace.id": @groupId "body[0].namespace.name": "example" "body[1].id": @projectIdNode "body[1].name": "example-nodejs" "body[1].public": true "body[1].namespace.id": @groupId "body[1].namespace.name": "example" projectJavaFiles: path: "/projects/#{@projectIdJava}/repository/tree" sort: {target: "body", keys: "name"} expected: "body.length": 5 "body[0].name": ".gitignore" "body[1].name": "build.sh" "body[2].name": "jenkins-config.xml" "body[3].name": "pom.xml" "body[4].name": "src" projectJavaIssues: path: "/projects/#{@projectIdJava}/issues" expected: "body.length": 0 projectJavaLabels: path: "/projects/#{@projectIdJava}/labels" sort: {target: "body", keys: "name"} expected: "body.length": 0 projectJavaHooks: path: "/projects/#{@projectIdJava}/hooks" expected: "body.length": 1 "body[0].url": "http://jenkins.pocci.test/project/example-java" "body[0].push_events": true "body[0].issues_events": false "body[0].merge_requests_events":true "body[0].tag_push_events": false projectNodeFiles: path: "/projects/#{@projectIdNode}/repository/tree" sort: {target: "body", keys: "name"} expected: "body.length": 9 "body[0].name": ".gitignore" "body[1].name": "Gruntfile.js" "body[2].name": "app" "body[3].name": "bower.json" "body[4].name": "build.sh" "body[5].name": "jenkins-config.xml" "body[6].name": "karma.conf.js" "body[7].name": "package.json" "body[8].name": "test" projectNodeIssues: path: "/projects/#{@projectIdNode}/issues" expected: "body.length": 0 projectNodeLabels: path: "/projects/#{@projectIdNode}/labels" expected: "body.length": 0 projectNodeHooks: path: "/projects/#{@projectIdNode}/hooks" expected: "body.length": 1 "body[0].url": "http://jenkins.pocci.test/project/example-nodejs" "body[0].push_events": true "body[0].issues_events": false "body[0].merge_requests_events":true "body[0].tag_push_events": false yield gitlab.login(setup.browser, @url, "jenkinsci", "PI:PASSWORD:<PASSWORD>END_PI") src = yield setup.browser .save("gitlab-login-by-jenkinsci") .getAttribute("img.header-user-avatar", "src") yield gitlab.logout(setup.browser) chai.assert.isOk(src.indexOf("jenkinsci.png") > -1, "Invalid avatar of jenkinsci") it "pocci", (done) -> test done, expect: -> yield @assert sonar: path: "http://sonar.pocci.test" expected: "title": "SonarQube" redmine: path: "http://redmine.pocci.test" expected: "title": "Redmine" taiga: path: "http://taiga.pocci.test" thrown: "code": "ENOTFOUND" "hostname": "taiga.pocci.test" chai.assert.equal(process.env.TZ, "Etc/UTC") it "jenkins", (done) -> test done, setup: -> url = "http://jenkins.pocci.test" @request = (path) -> url: url + path + "/api/json" json: true return expect: -> yield @assert jobs: path: "" debug: true expected: "body.jobs.length": 2 "body.jobs[0].name": "example-java" "body.jobs[0].url": "http://jenkins.pocci.test/job/example-java/" "body.jobs[1].name": "example-nodejs" "body.jobs[1].url": "http://jenkins.pocci.test/job/example-nodejs/" nodes: path: "/computer" expected: "body.computer.length": 3 "body.computer[0].displayName": "master" "body.computer[0].offline": false "body.computer[1].displayName": "java" "body.computer[1].offline": false "body.computer[2].displayName": "nodejs" "body.computer[2].offline": false it "user", (done) -> test done, expect: -> client = new LdapClient({url: "ldap://user.pocci.test"}) dn = "cn=admin,dc=example,dc=com" yield client.bind(dn, "admin") result = yield client.search "dc=example,dc=com", scope: "one" filter: "(uid=*)" chai.assert.equal(result.entries.length, 2) attrs = [] for entry in result.entries obj = {} for attribute in entry.attributes obj[attribute.type] = attribute.vals[0] attrs.push(obj) console.log(attrs) chai.assert.equal(attrs[0].uid, "jenkinsci") chai.assert.equal(attrs[0].cn, "jPI:NAME:<NAME>END_PI") chai.assert.equal(attrs[0].sn, "CI") chai.assert.equal(attrs[0].givenName, "PI:NAME:<NAME>END_PI") chai.assert.equal(attrs[0].displayName, "PI:NAME:<NAME>END_PI") chai.assert.equal(attrs[0].mail, "PI:EMAIL:<EMAIL>END_PI") chai.assert.equal(attrs[0].labeledURI, "https://wiki.jenkins-ci.org/download/attachments/2916393/headshot.png") chai.assert.match(attrs[0].userPassword, /^{SSHA}.+/) chai.assert.equal(attrs[1].uid, "boze") chai.assert.equal(attrs[1].cn, "boze") chai.assert.equal(attrs[1].sn, "BOZE") chai.assert.equal(attrs[1].givenName, "PI:NAME:<NAME>END_PI") chai.assert.equal(attrs[1].displayName, "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI") chai.assert.equal(attrs[1].mail, "PI:EMAIL:<EMAIL>END_PI") chai.assert.equal(attrs[1].labeledURI, undefined) chai.assert.match(attrs[1].userPassword, /^{SSHA}.+/) it "redmine", (done) -> url = "http://redmine.pocci.test" test done, setup: -> yield redmine.loginByAdmin(setup.browser, url) return cleanup: -> yield redmine.logout(setup.browser) expect: -> @request = (path) -> url: url + path @revisionJava = yield @get(".changeset a@/projects/example/repository", true) @revisionNode = yield @get(".changeset a@/projects/example/repository/example-nodejs", true) yield @assert repositoryJava: path: "/projects/example/repository" expected: "h2": /example-java[\s\S]*@[\s\S]*master/ "a[href='/issues/1']": "#1" repositoryNode: path: "/projects/example/repository/example-nodejs" expected: "h2": /example-nodejs[\s\S]*@[\s\S]*master/ "a[href='/issues/1']": "#1" issueJava: path: "/issues/1" expected: "#issue-changesets .changeset:nth-child(even) a": new RegExp(@revisionJava) issueNode: path: "/issues/1" expected: "#issue-changesets .changeset:nth-child(odd) a": new RegExp(@revisionNode) @request = yield redmine.createRequest(setup.browser, url) yield @assert projects: path: "/projects.json" expected: "body.total_count": 1 "body.projects.length": 1 "body.projects[0].id": 1 "body.projects[0].name": "example" "body.projects[0].identifier": "example" users: path: "/users.json" debug: true sort: {target: "body.users", keys: "id"} expected: "body.total_count": 3 "body.users.length": 3 "body.users[0].login": "admin" "body.users[0].firstname": "Redmine" "body.users[0].lastname": "Admin" "body.users[0].mail": "PI:EMAIL:<EMAIL>END_PI" "body.users[1].login": "jenkinsci" "body.users[1].firstname": "Jenkins" "body.users[1].lastname": "CI" "body.users[1].mail": "PI:EMAIL:<EMAIL>END_PI" "body.users[2].login": "boze" "body.users[2].firstname": "Taro" "body.users[2].lastname": "BOZE" "body.users[2].mail": "PI:EMAIL:<EMAIL>END_PI" issues: path: "/issues.json" expected: "body.total_count": 1 "body.issues.length": 1 "body.issues[0].id": 1 "body.issues[0].project.id": 1 "body.issues[0].project.name": "example" "body.issues[0].status.id": 1 "body.issues[0].subject": "import example codes" memberships: path: "/projects/1/memberships.json" expected: "body.total_count": 2 "body.memberships.length": 2 "body.memberships[0].user.name": "PI:NAME:<NAME>END_PIenkins CI" "body.memberships[0].roles.length": 2 "body.memberships[0].roles[0].id": 3 "body.memberships[0].roles[1].id": 4 "body.memberships[1].user.name": "PI:NAME:<NAME>END_PI" "body.memberships[1].roles.length": 2 "body.memberships[1].roles[0].id": 3 "body.memberships[1].roles[1].id": 4 it "redmine (defalut user language)", (done) -> url = "http://redmine.pocci.test" test done, setup: -> yield redmine.login(setup.browser, url, "boze", "PI:PASSWORD:<PASSWORD>END_PI") return cleanup: -> yield redmine.logout(setup.browser) expect: -> value = yield setup.browser.url("#{url}/my/account") .getText("#user_language [selected]") chai.assert.equal(value, "(auto)")
[ { "context": "critHeight\nexports.glyphs['breve'] =\n\tglyphName: 'breve'\n\tcharacterName: 'BREVE ACCENT'\n\tanchors:\n\t\t0:\n\t\t", "end": 76, "score": 0.7083044052124023, "start": 71, "tag": "NAME", "value": "breve" }, { "context": "s['breve'] =\n\tglyphName: 'breve'\n\tcharacterName: 'BREVE ACCENT'\n\tanchors:\n\t\t0:\n\t\t\tx: parentAnchors[0].x\n\t\t\ty: pa", "end": 107, "score": 0.9958226084709167, "start": 95, "tag": "NAME", "value": "BREVE ACCENT" } ]
src/glyphs/components/breve.coffee
byte-foundry/antique.ptf
0
# TODO: check all diacritHeight exports.glyphs['breve'] = glyphName: 'breve' characterName: 'BREVE ACCENT' 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 - (45 * width + 116 - (14)) / 2 y: Math.max( contours[0].nodes[1].expandedTo[0].y + 30, contours[0].nodes[1].expandedTo[1].y + ( 50 + ( 10 / 54 ) * thickness ) ) dirOut: - 90 + 'deg' tensionOut: 1.2 expand: Object({ width: ( 35 / 54 ) * thickness * contrast * contrastExtremity angle: 180 + 'deg' distr: 0.75 }) 1: x: anchors[0].x y: anchors[0].y dirOut: 0 + 'deg' type: 'smooth' tensionIn: 1.2 tensionOut: 1.2 expand: Object({ width: ( 30 / 54 ) * thickness angle: 180 + 90 + 'deg' distr: 1 }) 2: x: anchors[0].x + (45 * width + 116 - (14)) / 2 y: contours[0].nodes[0].expandedTo[1].y dirIn: - 90 + 'deg' tensionIn: 1.2 expand: Object({ width: ( 35 / 54 ) * thickness * contrast * contrastExtremity angle: 0 + 'deg' distr: 1 })
210172
# TODO: check all diacritHeight exports.glyphs['breve'] = 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 - (45 * width + 116 - (14)) / 2 y: Math.max( contours[0].nodes[1].expandedTo[0].y + 30, contours[0].nodes[1].expandedTo[1].y + ( 50 + ( 10 / 54 ) * thickness ) ) dirOut: - 90 + 'deg' tensionOut: 1.2 expand: Object({ width: ( 35 / 54 ) * thickness * contrast * contrastExtremity angle: 180 + 'deg' distr: 0.75 }) 1: x: anchors[0].x y: anchors[0].y dirOut: 0 + 'deg' type: 'smooth' tensionIn: 1.2 tensionOut: 1.2 expand: Object({ width: ( 30 / 54 ) * thickness angle: 180 + 90 + 'deg' distr: 1 }) 2: x: anchors[0].x + (45 * width + 116 - (14)) / 2 y: contours[0].nodes[0].expandedTo[1].y dirIn: - 90 + 'deg' tensionIn: 1.2 expand: Object({ width: ( 35 / 54 ) * thickness * contrast * contrastExtremity angle: 0 + 'deg' distr: 1 })
true
# TODO: check all diacritHeight exports.glyphs['breve'] = 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 - (45 * width + 116 - (14)) / 2 y: Math.max( contours[0].nodes[1].expandedTo[0].y + 30, contours[0].nodes[1].expandedTo[1].y + ( 50 + ( 10 / 54 ) * thickness ) ) dirOut: - 90 + 'deg' tensionOut: 1.2 expand: Object({ width: ( 35 / 54 ) * thickness * contrast * contrastExtremity angle: 180 + 'deg' distr: 0.75 }) 1: x: anchors[0].x y: anchors[0].y dirOut: 0 + 'deg' type: 'smooth' tensionIn: 1.2 tensionOut: 1.2 expand: Object({ width: ( 30 / 54 ) * thickness angle: 180 + 90 + 'deg' distr: 1 }) 2: x: anchors[0].x + (45 * width + 116 - (14)) / 2 y: contours[0].nodes[0].expandedTo[1].y dirIn: - 90 + 'deg' tensionIn: 1.2 expand: Object({ width: ( 35 / 54 ) * thickness * contrast * contrastExtremity angle: 0 + 'deg' distr: 1 })
[ { "context": "t']\nprivateProperties = ['permissions', 'email', 'firstName', 'lastName', 'gender', 'facebookID', 'music', 'v", "end": 425, "score": 0.9979386925697327, "start": 416, "tag": "NAME", "value": "firstName" }, { "context": "operties = ['permissions', 'email', 'firstName', 'lastName', 'gender', 'facebookID', 'music', 'volume']\n\nUse", "end": 437, "score": 0.9967837333679199, "start": 429, "tag": "NAME", "value": "lastName" }, { "context": "ord', 'anonymous', 'wizardColor1', 'volume',\n 'firstName', 'lastName', 'gender', 'facebookID', 'emailSubsc", "end": 665, "score": 0.9986464381217957, "start": 656, "tag": "NAME", "value": "firstName" }, { "context": "ous', 'wizardColor1', 'volume',\n 'firstName', 'lastName', 'gender', 'facebookID', 'emailSubscriptions',\n ", "end": 677, "score": 0.9981637597084045, "start": 669, "tag": "NAME", "value": "lastName" }, { "context": "r.get 'name'\n githubUsername: req.body.githubUsername\n created: new Date()+''\n collection = mon", "end": 5079, "score": 0.733040452003479, "start": 5071, "tag": "USERNAME", "value": "Username" } ]
server/handlers/user.coffee
cusion/codecombat
1
winston = require('winston') schema = require('../schemas/user') crypto = require('crypto') request = require('request') User = require('../models/User') Handler = require('./Handler') languages = require '../languages' mongoose = require 'mongoose' config = require '../../server_config' serverProperties = ['passwordHash', 'emailLower', 'nameLower', 'passwordReset'] privateProperties = ['permissions', 'email', 'firstName', 'lastName', 'gender', 'facebookID', 'music', 'volume'] UserHandler = class UserHandler extends Handler modelClass: User editableProperties: [ 'name', 'photoURL', 'password', 'anonymous', 'wizardColor1', 'volume', 'firstName', 'lastName', 'gender', 'facebookID', 'emailSubscriptions', 'testGroupNumber', 'music', 'hourOfCode', 'hourOfCodeComplete', 'preferredLanguage' ] jsonSchema: schema constructor: -> super(arguments...) @editableProperties.push('permissions') unless config.isProduction formatEntity: (req, document) -> return null unless document? obj = document.toObject() delete obj[prop] for prop in serverProperties includePrivates = req.user and (req.user.isAdmin() or req.user._id.equals(document._id)) delete obj[prop] for prop in privateProperties unless includePrivates # emailHash is used by gravatar hash = crypto.createHash('md5') if document.get('email') hash.update(_.trim(document.get('email')).toLowerCase()) else hash.update(@_id+'') obj.emailHash = hash.digest('hex') return obj waterfallFunctions: [ # FB access token checking # Check the email is the same as FB reports (req, user, callback) -> fbID = req.query.facebookID fbAT = req.query.facebookAccessToken return callback(null, req, user) unless fbID and fbAT url = "https://graph.facebook.com/me?access_token=#{fbAT}" request(url, (error, response, body) => body = JSON.parse(body) emailsMatch = req.body.email is body.email return callback(res:'Invalid Facebook Access Token.', code:422) unless emailsMatch callback(null, req, user) ) # GPlus access token checking (req, user, callback) -> gpID = req.query.gplusID gpAT = req.query.gplusAccessToken return callback(null, req, user) unless gpID and gpAT url = "https://www.googleapis.com/oauth2/v2/userinfo?access_token=#{gpAT}" request(url, (error, response, body) => body = JSON.parse(body) emailsMatch = req.body.email is body.email return callback(res:'Invalid G+ Access Token.', code:422) unless emailsMatch callback(null, req, user) ) # Email setting (req, user, callback) -> return callback(null, req, user) unless req.body.email? emailLower = req.body.email.toLowerCase() return callback(null, req, user) if emailLower is user.get('emailLower') User.findOne({emailLower:emailLower}).exec (err, otherUser) -> return callback(res:'Database error.', code:500) if err if (req.query.gplusID or req.query.facebookID) and otherUser # special case, log in as that user return req.logIn(otherUser, (err) -> return callback(res:'Facebook user login error.', code:500) if err return callback(null, req, otherUser) ) r = {message:'is already used by another account', property:'email'} return callback({res:r, code:409}) if otherUser user.set('email', req.body.email) callback(null, req, user) # Name setting (req, user, callback) -> return callback(null, req, user) unless req.body.name nameLower = req.body.name?.toLowerCase() return callback(null, req, user) if nameLower is user.get('nameLower') User.findOne({nameLower:nameLower}).exec (err, otherUser) -> return callback(res:'Database error.', code:500) if err r = {message:'is already used by another account', property:'name'} return callback({res:r, code:409}) if otherUser user.set('name', req.body.name) callback(null, req, user) ] getById: (req, res, id) -> if req.user and req.user._id.equals(id) return @sendSuccess(res, @formatEntity(req, req.user)) super(req, res, id) post: (req, res) -> return @sendBadInputError(res, 'No input.') if _.isEmpty(req.body) return @sendBadInputError(res, 'Existing users cannot create new ones.') unless req.user.get('anonymous') req.body._id = req.user._id if req.user.get('anonymous') @put(req, res) hasAccessToDocument: (req, document) -> if req.route.method in ['put', 'post', 'patch'] return true if req.user.isAdmin() return req.user._id.equals(document._id) return true getByRelationship: (req, res, args...) -> return @agreeToCLA(req, res) if args[1] is 'agreeToCLA' return @sendNotFoundError(res) agreeToCLA: (req, res) -> doc = user: req.user._id+'' email: req.user.get 'email' name: req.user.get 'name' githubUsername: req.body.githubUsername created: new Date()+'' collection = mongoose.connection.db.collection 'cla.submissions', (err, collection) -> return @sendDatabaseError(res, err) if err collection.insert doc, (err) -> return @sendDatabaseError(res, err) if err req.user.set('signedCLA', doc.created) req.user.save (err) -> return @sendDatabaseError(res, err) if err res.send({result:'success'}) res.end() module.exports = new UserHandler() module.exports.setupMiddleware = (app) -> app.use (req, res, next) -> if req.user next() else user = new User({anonymous:true}) user.set 'testGroupNumber', Math.floor(Math.random() * 256) # also in app/lib/auth user.set 'preferredLanguage', languages.languageCodeFromAcceptedLanguages req.acceptedLanguages loginUser(req, res, user, false, next) loginUser = (req, res, user, send=true, next=null) -> user.save((err) -> if err res.status(500) return res.end() req.logIn(user, (err) -> if err res.status(500) return res.end() if send res.send(user) return res.end() next() if next ) )
96999
winston = require('winston') schema = require('../schemas/user') crypto = require('crypto') request = require('request') User = require('../models/User') Handler = require('./Handler') languages = require '../languages' mongoose = require 'mongoose' config = require '../../server_config' serverProperties = ['passwordHash', 'emailLower', 'nameLower', 'passwordReset'] privateProperties = ['permissions', 'email', '<NAME>', '<NAME>', 'gender', 'facebookID', 'music', 'volume'] UserHandler = class UserHandler extends Handler modelClass: User editableProperties: [ 'name', 'photoURL', 'password', 'anonymous', 'wizardColor1', 'volume', '<NAME>', '<NAME>', 'gender', 'facebookID', 'emailSubscriptions', 'testGroupNumber', 'music', 'hourOfCode', 'hourOfCodeComplete', 'preferredLanguage' ] jsonSchema: schema constructor: -> super(arguments...) @editableProperties.push('permissions') unless config.isProduction formatEntity: (req, document) -> return null unless document? obj = document.toObject() delete obj[prop] for prop in serverProperties includePrivates = req.user and (req.user.isAdmin() or req.user._id.equals(document._id)) delete obj[prop] for prop in privateProperties unless includePrivates # emailHash is used by gravatar hash = crypto.createHash('md5') if document.get('email') hash.update(_.trim(document.get('email')).toLowerCase()) else hash.update(@_id+'') obj.emailHash = hash.digest('hex') return obj waterfallFunctions: [ # FB access token checking # Check the email is the same as FB reports (req, user, callback) -> fbID = req.query.facebookID fbAT = req.query.facebookAccessToken return callback(null, req, user) unless fbID and fbAT url = "https://graph.facebook.com/me?access_token=#{fbAT}" request(url, (error, response, body) => body = JSON.parse(body) emailsMatch = req.body.email is body.email return callback(res:'Invalid Facebook Access Token.', code:422) unless emailsMatch callback(null, req, user) ) # GPlus access token checking (req, user, callback) -> gpID = req.query.gplusID gpAT = req.query.gplusAccessToken return callback(null, req, user) unless gpID and gpAT url = "https://www.googleapis.com/oauth2/v2/userinfo?access_token=#{gpAT}" request(url, (error, response, body) => body = JSON.parse(body) emailsMatch = req.body.email is body.email return callback(res:'Invalid G+ Access Token.', code:422) unless emailsMatch callback(null, req, user) ) # Email setting (req, user, callback) -> return callback(null, req, user) unless req.body.email? emailLower = req.body.email.toLowerCase() return callback(null, req, user) if emailLower is user.get('emailLower') User.findOne({emailLower:emailLower}).exec (err, otherUser) -> return callback(res:'Database error.', code:500) if err if (req.query.gplusID or req.query.facebookID) and otherUser # special case, log in as that user return req.logIn(otherUser, (err) -> return callback(res:'Facebook user login error.', code:500) if err return callback(null, req, otherUser) ) r = {message:'is already used by another account', property:'email'} return callback({res:r, code:409}) if otherUser user.set('email', req.body.email) callback(null, req, user) # Name setting (req, user, callback) -> return callback(null, req, user) unless req.body.name nameLower = req.body.name?.toLowerCase() return callback(null, req, user) if nameLower is user.get('nameLower') User.findOne({nameLower:nameLower}).exec (err, otherUser) -> return callback(res:'Database error.', code:500) if err r = {message:'is already used by another account', property:'name'} return callback({res:r, code:409}) if otherUser user.set('name', req.body.name) callback(null, req, user) ] getById: (req, res, id) -> if req.user and req.user._id.equals(id) return @sendSuccess(res, @formatEntity(req, req.user)) super(req, res, id) post: (req, res) -> return @sendBadInputError(res, 'No input.') if _.isEmpty(req.body) return @sendBadInputError(res, 'Existing users cannot create new ones.') unless req.user.get('anonymous') req.body._id = req.user._id if req.user.get('anonymous') @put(req, res) hasAccessToDocument: (req, document) -> if req.route.method in ['put', 'post', 'patch'] return true if req.user.isAdmin() return req.user._id.equals(document._id) return true getByRelationship: (req, res, args...) -> return @agreeToCLA(req, res) if args[1] is 'agreeToCLA' return @sendNotFoundError(res) agreeToCLA: (req, res) -> doc = user: req.user._id+'' email: req.user.get 'email' name: req.user.get 'name' githubUsername: req.body.githubUsername created: new Date()+'' collection = mongoose.connection.db.collection 'cla.submissions', (err, collection) -> return @sendDatabaseError(res, err) if err collection.insert doc, (err) -> return @sendDatabaseError(res, err) if err req.user.set('signedCLA', doc.created) req.user.save (err) -> return @sendDatabaseError(res, err) if err res.send({result:'success'}) res.end() module.exports = new UserHandler() module.exports.setupMiddleware = (app) -> app.use (req, res, next) -> if req.user next() else user = new User({anonymous:true}) user.set 'testGroupNumber', Math.floor(Math.random() * 256) # also in app/lib/auth user.set 'preferredLanguage', languages.languageCodeFromAcceptedLanguages req.acceptedLanguages loginUser(req, res, user, false, next) loginUser = (req, res, user, send=true, next=null) -> user.save((err) -> if err res.status(500) return res.end() req.logIn(user, (err) -> if err res.status(500) return res.end() if send res.send(user) return res.end() next() if next ) )
true
winston = require('winston') schema = require('../schemas/user') crypto = require('crypto') request = require('request') User = require('../models/User') Handler = require('./Handler') languages = require '../languages' mongoose = require 'mongoose' config = require '../../server_config' serverProperties = ['passwordHash', 'emailLower', 'nameLower', 'passwordReset'] privateProperties = ['permissions', 'email', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'gender', 'facebookID', 'music', 'volume'] UserHandler = class UserHandler extends Handler modelClass: User editableProperties: [ 'name', 'photoURL', 'password', 'anonymous', 'wizardColor1', 'volume', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'gender', 'facebookID', 'emailSubscriptions', 'testGroupNumber', 'music', 'hourOfCode', 'hourOfCodeComplete', 'preferredLanguage' ] jsonSchema: schema constructor: -> super(arguments...) @editableProperties.push('permissions') unless config.isProduction formatEntity: (req, document) -> return null unless document? obj = document.toObject() delete obj[prop] for prop in serverProperties includePrivates = req.user and (req.user.isAdmin() or req.user._id.equals(document._id)) delete obj[prop] for prop in privateProperties unless includePrivates # emailHash is used by gravatar hash = crypto.createHash('md5') if document.get('email') hash.update(_.trim(document.get('email')).toLowerCase()) else hash.update(@_id+'') obj.emailHash = hash.digest('hex') return obj waterfallFunctions: [ # FB access token checking # Check the email is the same as FB reports (req, user, callback) -> fbID = req.query.facebookID fbAT = req.query.facebookAccessToken return callback(null, req, user) unless fbID and fbAT url = "https://graph.facebook.com/me?access_token=#{fbAT}" request(url, (error, response, body) => body = JSON.parse(body) emailsMatch = req.body.email is body.email return callback(res:'Invalid Facebook Access Token.', code:422) unless emailsMatch callback(null, req, user) ) # GPlus access token checking (req, user, callback) -> gpID = req.query.gplusID gpAT = req.query.gplusAccessToken return callback(null, req, user) unless gpID and gpAT url = "https://www.googleapis.com/oauth2/v2/userinfo?access_token=#{gpAT}" request(url, (error, response, body) => body = JSON.parse(body) emailsMatch = req.body.email is body.email return callback(res:'Invalid G+ Access Token.', code:422) unless emailsMatch callback(null, req, user) ) # Email setting (req, user, callback) -> return callback(null, req, user) unless req.body.email? emailLower = req.body.email.toLowerCase() return callback(null, req, user) if emailLower is user.get('emailLower') User.findOne({emailLower:emailLower}).exec (err, otherUser) -> return callback(res:'Database error.', code:500) if err if (req.query.gplusID or req.query.facebookID) and otherUser # special case, log in as that user return req.logIn(otherUser, (err) -> return callback(res:'Facebook user login error.', code:500) if err return callback(null, req, otherUser) ) r = {message:'is already used by another account', property:'email'} return callback({res:r, code:409}) if otherUser user.set('email', req.body.email) callback(null, req, user) # Name setting (req, user, callback) -> return callback(null, req, user) unless req.body.name nameLower = req.body.name?.toLowerCase() return callback(null, req, user) if nameLower is user.get('nameLower') User.findOne({nameLower:nameLower}).exec (err, otherUser) -> return callback(res:'Database error.', code:500) if err r = {message:'is already used by another account', property:'name'} return callback({res:r, code:409}) if otherUser user.set('name', req.body.name) callback(null, req, user) ] getById: (req, res, id) -> if req.user and req.user._id.equals(id) return @sendSuccess(res, @formatEntity(req, req.user)) super(req, res, id) post: (req, res) -> return @sendBadInputError(res, 'No input.') if _.isEmpty(req.body) return @sendBadInputError(res, 'Existing users cannot create new ones.') unless req.user.get('anonymous') req.body._id = req.user._id if req.user.get('anonymous') @put(req, res) hasAccessToDocument: (req, document) -> if req.route.method in ['put', 'post', 'patch'] return true if req.user.isAdmin() return req.user._id.equals(document._id) return true getByRelationship: (req, res, args...) -> return @agreeToCLA(req, res) if args[1] is 'agreeToCLA' return @sendNotFoundError(res) agreeToCLA: (req, res) -> doc = user: req.user._id+'' email: req.user.get 'email' name: req.user.get 'name' githubUsername: req.body.githubUsername created: new Date()+'' collection = mongoose.connection.db.collection 'cla.submissions', (err, collection) -> return @sendDatabaseError(res, err) if err collection.insert doc, (err) -> return @sendDatabaseError(res, err) if err req.user.set('signedCLA', doc.created) req.user.save (err) -> return @sendDatabaseError(res, err) if err res.send({result:'success'}) res.end() module.exports = new UserHandler() module.exports.setupMiddleware = (app) -> app.use (req, res, next) -> if req.user next() else user = new User({anonymous:true}) user.set 'testGroupNumber', Math.floor(Math.random() * 256) # also in app/lib/auth user.set 'preferredLanguage', languages.languageCodeFromAcceptedLanguages req.acceptedLanguages loginUser(req, res, user, false, next) loginUser = (req, res, user, send=true, next=null) -> user.save((err) -> if err res.status(500) return res.end() req.logIn(user, (err) -> if err res.status(500) return res.end() if send res.send(user) return res.end() next() if next ) )
[ { "context": "blocklyTool.getFriendField = () ->\n #friends = ['Fangrui', 'Qijiang', 'Yuxin', 'Xiaoyu']\n tmplist = block", "end": 387, "score": 0.999289870262146, "start": 380, "tag": "NAME", "value": "Fangrui" }, { "context": ".getFriendField = () ->\n #friends = ['Fangrui', 'Qijiang', 'Yuxin', 'Xiaoyu']\n tmplist = blocklyTool.dupl", "end": 398, "score": 0.9986833930015564, "start": 391, "tag": "NAME", "value": "Qijiang" }, { "context": "ield = () ->\n #friends = ['Fangrui', 'Qijiang', 'Yuxin', 'Xiaoyu']\n tmplist = blocklyTool.duplicateList", "end": 407, "score": 0.9979462623596191, "start": 402, "tag": "NAME", "value": "Yuxin" }, { "context": " ->\n #friends = ['Fangrui', 'Qijiang', 'Yuxin', 'Xiaoyu']\n tmplist = blocklyTool.duplicateList(blocklyTo", "end": 417, "score": 0.9970769882202148, "start": 411, "tag": "NAME", "value": "Xiaoyu" } ]
web/js/blocklyTools.coffee
Flockly/Flockly
1
# Blockly Tools.. blocklyTool = {} #$.getJSON '/get_friends', (data) -> #blocklyTool.friends = [] #data.forEach (user) -> #username = user['name'] + '/' + user['id'] #blocklyTool.friends.push(username) blocklyTool.duplicateList = (arr) -> ret = [] arr.forEach((ele) -> ret.push([ele, ele]) ) return ret blocklyTool.getFriendField = () -> #friends = ['Fangrui', 'Qijiang', 'Yuxin', 'Xiaoyu'] tmplist = blocklyTool.duplicateList(blocklyTool.friends) return new Blockly.FieldDropdown(tmplist) window.blocklyTool = blocklyTool
12289
# Blockly Tools.. blocklyTool = {} #$.getJSON '/get_friends', (data) -> #blocklyTool.friends = [] #data.forEach (user) -> #username = user['name'] + '/' + user['id'] #blocklyTool.friends.push(username) blocklyTool.duplicateList = (arr) -> ret = [] arr.forEach((ele) -> ret.push([ele, ele]) ) return ret blocklyTool.getFriendField = () -> #friends = ['<NAME>', '<NAME>', '<NAME>', '<NAME>'] tmplist = blocklyTool.duplicateList(blocklyTool.friends) return new Blockly.FieldDropdown(tmplist) window.blocklyTool = blocklyTool
true
# Blockly Tools.. blocklyTool = {} #$.getJSON '/get_friends', (data) -> #blocklyTool.friends = [] #data.forEach (user) -> #username = user['name'] + '/' + user['id'] #blocklyTool.friends.push(username) blocklyTool.duplicateList = (arr) -> ret = [] arr.forEach((ele) -> ret.push([ele, ele]) ) return ret blocklyTool.getFriendField = () -> #friends = ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] tmplist = blocklyTool.duplicateList(blocklyTool.friends) return new Blockly.FieldDropdown(tmplist) window.blocklyTool = blocklyTool
[ { "context": "util = require('./util')\n###\n From Vibrant.js by Jari Zwarts\n Ported to node.js by AKFish\n\n Swatch class\n###", "end": 61, "score": 0.9998944997787476, "start": 50, "tag": "NAME", "value": "Jari Zwarts" }, { "context": "m Vibrant.js by Jari Zwarts\n Ported to node.js by AKFish\n\n Swatch class\n###\nmodule.exports =\nclass Swatch", "end": 91, "score": 0.9755663871765137, "start": 85, "tag": "USERNAME", "value": "AKFish" } ]
src/swatch.coffee
Kronuz/node-vibrant
0
util = require('./util') ### From Vibrant.js by Jari Zwarts Ported to node.js by AKFish Swatch class ### module.exports = class Swatch hsl: undefined rgb: undefined population: 1 yiq: 0 constructor: (rgb, population) -> @rgb = rgb @population = population getHsl: -> if not @hsl @hsl = util.rgbToHsl @rgb[0], @rgb[1], @rgb[2] else @hsl getPopulation: -> @population getRgb: -> @rgb getHex: -> util.rgbToHex(@rgb[0], @rgb[1], @rgb[2]) getTitleTextColor: -> @_ensureTextColors() if @yiq < 200 then "#fff" else "#000" getBodyTextColor: -> @_ensureTextColors() if @yiq < 150 then "#fff" else "#000" _ensureTextColors: -> if not @yiq then @yiq = (@rgb[0] * 299 + @rgb[1] * 587 + @rgb[2] * 114) / 1000
65498
util = require('./util') ### From Vibrant.js by <NAME> Ported to node.js by AKFish Swatch class ### module.exports = class Swatch hsl: undefined rgb: undefined population: 1 yiq: 0 constructor: (rgb, population) -> @rgb = rgb @population = population getHsl: -> if not @hsl @hsl = util.rgbToHsl @rgb[0], @rgb[1], @rgb[2] else @hsl getPopulation: -> @population getRgb: -> @rgb getHex: -> util.rgbToHex(@rgb[0], @rgb[1], @rgb[2]) getTitleTextColor: -> @_ensureTextColors() if @yiq < 200 then "#fff" else "#000" getBodyTextColor: -> @_ensureTextColors() if @yiq < 150 then "#fff" else "#000" _ensureTextColors: -> if not @yiq then @yiq = (@rgb[0] * 299 + @rgb[1] * 587 + @rgb[2] * 114) / 1000
true
util = require('./util') ### From Vibrant.js by PI:NAME:<NAME>END_PI Ported to node.js by AKFish Swatch class ### module.exports = class Swatch hsl: undefined rgb: undefined population: 1 yiq: 0 constructor: (rgb, population) -> @rgb = rgb @population = population getHsl: -> if not @hsl @hsl = util.rgbToHsl @rgb[0], @rgb[1], @rgb[2] else @hsl getPopulation: -> @population getRgb: -> @rgb getHex: -> util.rgbToHex(@rgb[0], @rgb[1], @rgb[2]) getTitleTextColor: -> @_ensureTextColors() if @yiq < 200 then "#fff" else "#000" getBodyTextColor: -> @_ensureTextColors() if @yiq < 150 then "#fff" else "#000" _ensureTextColors: -> if not @yiq then @yiq = (@rgb[0] * 299 + @rgb[1] * 587 + @rgb[2] * 114) / 1000
[ { "context": "duplication is better than the wrong abstraction - Sandi Metz\n currentFile: ->\n # there is no current file ", "end": 1839, "score": 0.9935643672943115, "start": 1829, "tag": "NAME", "value": "Sandi Metz" } ]
lib/git-links.coffee
calebmeyer/git-links
4
{CompositeDisposable, BufferedProcess} = require 'atom' Path = require 'path' module.exports = GitLinks = subscriptions: null activate: (state) -> # Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable @subscriptions = new CompositeDisposable # Register commands @subscriptions.add atom.commands.add 'atom-workspace', 'git-links:copy-absolute-link-for-current-line': => @currentLine() 'git-links:copy-absolute-link-for-current-file': => @currentFile() 'git-links:copy-absolute-link-for-current-commit': => @currentCommit() deactivate: -> @subscriptions.dispose() currentLine: -> # there is no current line if we don't have an active text editor if editor = atom.workspace.getActiveTextEditor() cursor = editor.getCursors()[0] line = cursor.getBufferRow() + 1 # 0 based list of rows, 1 based file lines filePath = @forwardFilePath() self = this # callback hell, here we come self.git(['config', '--get', 'remote.origin.url'], (code, stdout, errors) -> repo = stdout.trim() .replace(/^git@/, 'https://') .replace(/\.com:/, '.com/') .replace(/\.git$/, '') self.git(['log', '--pretty=oneline', '-1'], (code, stdout, errors) -> commitHash = stdout.split(' ')[0] self.git(['rev-parse', '--show-toplevel'], (code, stdout, errors) -> gitDirectory = stdout.trim() relativePath = filePath.replace(gitDirectory, '') link = repo + '/blob/' + commitHash + relativePath + '#L' + line atom.clipboard.write(link) atom.notifications.addInfo('Copied link for current line to clipboard', detail: link) ) ) ) # duplication is better than the wrong abstraction - Sandi Metz currentFile: -> # there is no current file if we don't have an active text editor if editor = atom.workspace.getActiveTextEditor() filePath = @forwardFilePath() self = this # callback hell, here we come self.git(['config', '--get', 'remote.origin.url'], (code, stdout, errors) -> repo = stdout.trim() .replace(/^git@/, 'https://') .replace(/\.com:/, '.com/') .replace(/\.git$/, '') self.git(['log', '--pretty=oneline', '-1'], (code, stdout, errors) -> commitHash = stdout.split(' ')[0] self.git(['rev-parse', '--show-toplevel'], (code, stdout, errors) -> gitDirectory = stdout.trim() relativePath = filePath.replace(gitDirectory, '') link = repo + '/blob/' + commitHash + relativePath atom.clipboard.write(link) atom.notifications.addInfo('Copied link for current file to clipboard', detail: link) ) ) ) # TODO remove limitation: only works if a file is open currentCommit: -> if editor = atom.workspace.getActiveTextEditor() filePath = @forwardFilePath() self = this # callback hell, here we come self.git(['config', '--get', 'remote.origin.url'], (code, stdout, errors) -> repo = stdout.trim() .replace(/^git@/, 'https://') .replace(/\.com:/, '.com/') .replace(/\.git$/, '') self.git(['log', '--pretty=oneline', '-1'], (code, stdout, errors) -> commitHash = stdout.split(' ')[0] link = repo + '/commit/' + commitHash atom.clipboard.write(link) atom.notifications.addInfo('Copied link for current commit to clipboard', detail: link) ) ) # HELPER METHODS here on down filePath: -> atom.workspace.getActiveTextEditor().getBuffer().getPath() fileDirectory: -> Path.dirname(@filePath()) # file's path, but with forward slashes like urls use forwardFilePath: -> @filePath().replace(/\\/g, '/') # args should be an array of strings # for `git reset --hard`, the array would be ['reset', '--hard'] # callback is a function which will be called with the exit code and standard output once the command has finished # cwd is the current working directory to call git in (defaults to current file's directory) git: (args, callback, cwd) -> cwd = @fileDirectory() unless cwd? stdout = '' errors = '' new BufferedProcess({ command: 'git' args options: {cwd} stdout: (output) -> console.log(output) stdout += output stderr: (errorOutput) -> console.error(errorOutput) if errorOutput? errors += errorOutput exit: (code) -> console.log("`git #{args.join(' ')}` exited with status: #{code}") callback(code, stdout, errors) })
51282
{CompositeDisposable, BufferedProcess} = require 'atom' Path = require 'path' module.exports = GitLinks = subscriptions: null activate: (state) -> # Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable @subscriptions = new CompositeDisposable # Register commands @subscriptions.add atom.commands.add 'atom-workspace', 'git-links:copy-absolute-link-for-current-line': => @currentLine() 'git-links:copy-absolute-link-for-current-file': => @currentFile() 'git-links:copy-absolute-link-for-current-commit': => @currentCommit() deactivate: -> @subscriptions.dispose() currentLine: -> # there is no current line if we don't have an active text editor if editor = atom.workspace.getActiveTextEditor() cursor = editor.getCursors()[0] line = cursor.getBufferRow() + 1 # 0 based list of rows, 1 based file lines filePath = @forwardFilePath() self = this # callback hell, here we come self.git(['config', '--get', 'remote.origin.url'], (code, stdout, errors) -> repo = stdout.trim() .replace(/^git@/, 'https://') .replace(/\.com:/, '.com/') .replace(/\.git$/, '') self.git(['log', '--pretty=oneline', '-1'], (code, stdout, errors) -> commitHash = stdout.split(' ')[0] self.git(['rev-parse', '--show-toplevel'], (code, stdout, errors) -> gitDirectory = stdout.trim() relativePath = filePath.replace(gitDirectory, '') link = repo + '/blob/' + commitHash + relativePath + '#L' + line atom.clipboard.write(link) atom.notifications.addInfo('Copied link for current line to clipboard', detail: link) ) ) ) # duplication is better than the wrong abstraction - <NAME> currentFile: -> # there is no current file if we don't have an active text editor if editor = atom.workspace.getActiveTextEditor() filePath = @forwardFilePath() self = this # callback hell, here we come self.git(['config', '--get', 'remote.origin.url'], (code, stdout, errors) -> repo = stdout.trim() .replace(/^git@/, 'https://') .replace(/\.com:/, '.com/') .replace(/\.git$/, '') self.git(['log', '--pretty=oneline', '-1'], (code, stdout, errors) -> commitHash = stdout.split(' ')[0] self.git(['rev-parse', '--show-toplevel'], (code, stdout, errors) -> gitDirectory = stdout.trim() relativePath = filePath.replace(gitDirectory, '') link = repo + '/blob/' + commitHash + relativePath atom.clipboard.write(link) atom.notifications.addInfo('Copied link for current file to clipboard', detail: link) ) ) ) # TODO remove limitation: only works if a file is open currentCommit: -> if editor = atom.workspace.getActiveTextEditor() filePath = @forwardFilePath() self = this # callback hell, here we come self.git(['config', '--get', 'remote.origin.url'], (code, stdout, errors) -> repo = stdout.trim() .replace(/^git@/, 'https://') .replace(/\.com:/, '.com/') .replace(/\.git$/, '') self.git(['log', '--pretty=oneline', '-1'], (code, stdout, errors) -> commitHash = stdout.split(' ')[0] link = repo + '/commit/' + commitHash atom.clipboard.write(link) atom.notifications.addInfo('Copied link for current commit to clipboard', detail: link) ) ) # HELPER METHODS here on down filePath: -> atom.workspace.getActiveTextEditor().getBuffer().getPath() fileDirectory: -> Path.dirname(@filePath()) # file's path, but with forward slashes like urls use forwardFilePath: -> @filePath().replace(/\\/g, '/') # args should be an array of strings # for `git reset --hard`, the array would be ['reset', '--hard'] # callback is a function which will be called with the exit code and standard output once the command has finished # cwd is the current working directory to call git in (defaults to current file's directory) git: (args, callback, cwd) -> cwd = @fileDirectory() unless cwd? stdout = '' errors = '' new BufferedProcess({ command: 'git' args options: {cwd} stdout: (output) -> console.log(output) stdout += output stderr: (errorOutput) -> console.error(errorOutput) if errorOutput? errors += errorOutput exit: (code) -> console.log("`git #{args.join(' ')}` exited with status: #{code}") callback(code, stdout, errors) })
true
{CompositeDisposable, BufferedProcess} = require 'atom' Path = require 'path' module.exports = GitLinks = subscriptions: null activate: (state) -> # Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable @subscriptions = new CompositeDisposable # Register commands @subscriptions.add atom.commands.add 'atom-workspace', 'git-links:copy-absolute-link-for-current-line': => @currentLine() 'git-links:copy-absolute-link-for-current-file': => @currentFile() 'git-links:copy-absolute-link-for-current-commit': => @currentCommit() deactivate: -> @subscriptions.dispose() currentLine: -> # there is no current line if we don't have an active text editor if editor = atom.workspace.getActiveTextEditor() cursor = editor.getCursors()[0] line = cursor.getBufferRow() + 1 # 0 based list of rows, 1 based file lines filePath = @forwardFilePath() self = this # callback hell, here we come self.git(['config', '--get', 'remote.origin.url'], (code, stdout, errors) -> repo = stdout.trim() .replace(/^git@/, 'https://') .replace(/\.com:/, '.com/') .replace(/\.git$/, '') self.git(['log', '--pretty=oneline', '-1'], (code, stdout, errors) -> commitHash = stdout.split(' ')[0] self.git(['rev-parse', '--show-toplevel'], (code, stdout, errors) -> gitDirectory = stdout.trim() relativePath = filePath.replace(gitDirectory, '') link = repo + '/blob/' + commitHash + relativePath + '#L' + line atom.clipboard.write(link) atom.notifications.addInfo('Copied link for current line to clipboard', detail: link) ) ) ) # duplication is better than the wrong abstraction - PI:NAME:<NAME>END_PI currentFile: -> # there is no current file if we don't have an active text editor if editor = atom.workspace.getActiveTextEditor() filePath = @forwardFilePath() self = this # callback hell, here we come self.git(['config', '--get', 'remote.origin.url'], (code, stdout, errors) -> repo = stdout.trim() .replace(/^git@/, 'https://') .replace(/\.com:/, '.com/') .replace(/\.git$/, '') self.git(['log', '--pretty=oneline', '-1'], (code, stdout, errors) -> commitHash = stdout.split(' ')[0] self.git(['rev-parse', '--show-toplevel'], (code, stdout, errors) -> gitDirectory = stdout.trim() relativePath = filePath.replace(gitDirectory, '') link = repo + '/blob/' + commitHash + relativePath atom.clipboard.write(link) atom.notifications.addInfo('Copied link for current file to clipboard', detail: link) ) ) ) # TODO remove limitation: only works if a file is open currentCommit: -> if editor = atom.workspace.getActiveTextEditor() filePath = @forwardFilePath() self = this # callback hell, here we come self.git(['config', '--get', 'remote.origin.url'], (code, stdout, errors) -> repo = stdout.trim() .replace(/^git@/, 'https://') .replace(/\.com:/, '.com/') .replace(/\.git$/, '') self.git(['log', '--pretty=oneline', '-1'], (code, stdout, errors) -> commitHash = stdout.split(' ')[0] link = repo + '/commit/' + commitHash atom.clipboard.write(link) atom.notifications.addInfo('Copied link for current commit to clipboard', detail: link) ) ) # HELPER METHODS here on down filePath: -> atom.workspace.getActiveTextEditor().getBuffer().getPath() fileDirectory: -> Path.dirname(@filePath()) # file's path, but with forward slashes like urls use forwardFilePath: -> @filePath().replace(/\\/g, '/') # args should be an array of strings # for `git reset --hard`, the array would be ['reset', '--hard'] # callback is a function which will be called with the exit code and standard output once the command has finished # cwd is the current working directory to call git in (defaults to current file's directory) git: (args, callback, cwd) -> cwd = @fileDirectory() unless cwd? stdout = '' errors = '' new BufferedProcess({ command: 'git' args options: {cwd} stdout: (output) -> console.log(output) stdout += output stderr: (errorOutput) -> console.error(errorOutput) if errorOutput? errors += errorOutput exit: (code) -> console.log("`git #{args.join(' ')}` exited with status: #{code}") callback(code, stdout, errors) })
[ { "context": "存在,请选择其它用户名\") if exists\n#\n# data.password = _common.md5 data.password\n# self.save data, cb\n\nmodule.e", "end": 1199, "score": 0.759884774684906, "start": 1189, "tag": "PASSWORD", "value": "common.md5" } ]
src/entity/member.coffee
kiteam/kiteam
0
### 成员 ### _util = require 'util' _bijou = require('bijou') _BaseEntity = _bijou.BaseEntity _http = _bijou.http _common = require '../common' class Member extends _BaseEntity constructor: ()-> super require('../schema/member').schema #检查用户是否已经存在 memberExists: (username, cb)-> @exists username: username, cb #根据帐号查找用户信息 findMemberByAccount: (account, cb)-> options = beforeQuery: (query)-> query.where ()-> @orWhere('email', account).orWhere('username', account) @findOne null, options, cb #登录 signIn: (account, password, cb)-> errMessage = "用户名或者密码错误" @findMemberByAccount account, (err, member)-> return cb err if err #没有这个用户名 return cb _http.notAcceptableError(errMessage) if not member #检查密码是否匹配 # console.log member.password, _common.md5(password) return cb _http.notAcceptableError(errMessage) if member.password isnt _common.md5(password) cb null, member # #用户注册 # signUp: (data, cb)-> # self = @; # @memberExists data.username, (err, exists)-> # return cb _http.notAcceptableError("用户名#{data.username}已经存在,请选择其它用户名") if exists # # data.password = _common.md5 data.password # self.save data, cb module.exports = new Member
96037
### 成员 ### _util = require 'util' _bijou = require('bijou') _BaseEntity = _bijou.BaseEntity _http = _bijou.http _common = require '../common' class Member extends _BaseEntity constructor: ()-> super require('../schema/member').schema #检查用户是否已经存在 memberExists: (username, cb)-> @exists username: username, cb #根据帐号查找用户信息 findMemberByAccount: (account, cb)-> options = beforeQuery: (query)-> query.where ()-> @orWhere('email', account).orWhere('username', account) @findOne null, options, cb #登录 signIn: (account, password, cb)-> errMessage = "用户名或者密码错误" @findMemberByAccount account, (err, member)-> return cb err if err #没有这个用户名 return cb _http.notAcceptableError(errMessage) if not member #检查密码是否匹配 # console.log member.password, _common.md5(password) return cb _http.notAcceptableError(errMessage) if member.password isnt _common.md5(password) cb null, member # #用户注册 # signUp: (data, cb)-> # self = @; # @memberExists data.username, (err, exists)-> # return cb _http.notAcceptableError("用户名#{data.username}已经存在,请选择其它用户名") if exists # # data.password = _<PASSWORD> data.password # self.save data, cb module.exports = new Member
true
### 成员 ### _util = require 'util' _bijou = require('bijou') _BaseEntity = _bijou.BaseEntity _http = _bijou.http _common = require '../common' class Member extends _BaseEntity constructor: ()-> super require('../schema/member').schema #检查用户是否已经存在 memberExists: (username, cb)-> @exists username: username, cb #根据帐号查找用户信息 findMemberByAccount: (account, cb)-> options = beforeQuery: (query)-> query.where ()-> @orWhere('email', account).orWhere('username', account) @findOne null, options, cb #登录 signIn: (account, password, cb)-> errMessage = "用户名或者密码错误" @findMemberByAccount account, (err, member)-> return cb err if err #没有这个用户名 return cb _http.notAcceptableError(errMessage) if not member #检查密码是否匹配 # console.log member.password, _common.md5(password) return cb _http.notAcceptableError(errMessage) if member.password isnt _common.md5(password) cb null, member # #用户注册 # signUp: (data, cb)-> # self = @; # @memberExists data.username, (err, exists)-> # return cb _http.notAcceptableError("用户名#{data.username}已经存在,请选择其它用户名") if exists # # data.password = _PI:PASSWORD:<PASSWORD>END_PI data.password # self.save data, cb module.exports = new Member
[ { "context": "editor, \"Hello Mayor.\\n\n My name is Alfred, and I'll help you to build up and create the bes", "end": 523, "score": 0.9998281002044678, "start": 517, "tag": "NAME", "value": "Alfred" } ]
lib/controller/create.coffee
SynderDEV/atom-city
2
Controller = require '../abstract/controller' GameState = require '../core/gamestate' queue = require '../tools/queue' input = require '../tools/input' slugify = require '../tools/slugify' class CreateController extends Controller ### # Init Controller ### init: () -> @game.editor.readOnly = false cityName = null citySlug = null majorName = null queue [ (() => input @game.editor, "Hello Mayor.\n My name is Alfred, and I'll help you to build up and create the best city in the world.\n But, let's start simple, what's your name?", (data) => if data.trim().length < 0 false else majorName = data true ) (() => input @game.editor, 'Oh, ahm... Let\'s stay with Major. Anyway, what would you like to name your new city, Major?', (data) => if data.trim().length < 0 false else cityName = data citySlug = slugify cityName true ) ] .then ( () => @game.saveNew GameState.create @game.savestate, cityName, citySlug, majorName ) # Export Module module.exports = CreateController
215553
Controller = require '../abstract/controller' GameState = require '../core/gamestate' queue = require '../tools/queue' input = require '../tools/input' slugify = require '../tools/slugify' class CreateController extends Controller ### # Init Controller ### init: () -> @game.editor.readOnly = false cityName = null citySlug = null majorName = null queue [ (() => input @game.editor, "Hello Mayor.\n My name is <NAME>, and I'll help you to build up and create the best city in the world.\n But, let's start simple, what's your name?", (data) => if data.trim().length < 0 false else majorName = data true ) (() => input @game.editor, 'Oh, ahm... Let\'s stay with Major. Anyway, what would you like to name your new city, Major?', (data) => if data.trim().length < 0 false else cityName = data citySlug = slugify cityName true ) ] .then ( () => @game.saveNew GameState.create @game.savestate, cityName, citySlug, majorName ) # Export Module module.exports = CreateController
true
Controller = require '../abstract/controller' GameState = require '../core/gamestate' queue = require '../tools/queue' input = require '../tools/input' slugify = require '../tools/slugify' class CreateController extends Controller ### # Init Controller ### init: () -> @game.editor.readOnly = false cityName = null citySlug = null majorName = null queue [ (() => input @game.editor, "Hello Mayor.\n My name is PI:NAME:<NAME>END_PI, and I'll help you to build up and create the best city in the world.\n But, let's start simple, what's your name?", (data) => if data.trim().length < 0 false else majorName = data true ) (() => input @game.editor, 'Oh, ahm... Let\'s stay with Major. Anyway, what would you like to name your new city, Major?', (data) => if data.trim().length < 0 false else cityName = data citySlug = slugify cityName true ) ] .then ( () => @game.saveNew GameState.create @game.savestate, cityName, citySlug, majorName ) # Export Module module.exports = CreateController
[ { "context": "perties', ->\n attributes = Adapter.get {name: 'Abraham'}\n expect(attributes.name).to.eq 'Abraham'\n\n ", "end": 201, "score": 0.9602545499801636, "start": 194, "tag": "NAME", "value": "Abraham" }, { "context": "me: 'Abraham'}\n expect(attributes.name).to.eq 'Abraham'\n\n it 'should get object property', ->\n name ", "end": 246, "score": 0.9609032273292542, "start": 239, "tag": "NAME", "value": "Abraham" }, { "context": "ject property', ->\n name = Adapter.get {name: 'Abraham'}, 'name'\n expect(name).to.eq 'Abraham'\n\n it ", "end": 325, "score": 0.9740045070648193, "start": 318, "tag": "NAME", "value": "Abraham" }, { "context": "{name: 'Abraham'}, 'name'\n expect(name).to.eq 'Abraham'\n\n it 'should get the id', ->\n id = Adapter.i", "end": 367, "score": 0.947563886642456, "start": 360, "tag": "NAME", "value": "Abraham" } ]
test/yayson/adapter.coffee
nie7321/yayson
193
expect = require('chai').expect Adapter = require('../../src/yayson.coffee')().Adapter describe 'Adapter', -> it 'should get all object properties', -> attributes = Adapter.get {name: 'Abraham'} expect(attributes.name).to.eq 'Abraham' it 'should get object property', -> name = Adapter.get {name: 'Abraham'}, 'name' expect(name).to.eq 'Abraham' it 'should get the id', -> id = Adapter.id {id: 5} expect(id).to.eq '5'
46526
expect = require('chai').expect Adapter = require('../../src/yayson.coffee')().Adapter describe 'Adapter', -> it 'should get all object properties', -> attributes = Adapter.get {name: '<NAME>'} expect(attributes.name).to.eq '<NAME>' it 'should get object property', -> name = Adapter.get {name: '<NAME>'}, 'name' expect(name).to.eq '<NAME>' it 'should get the id', -> id = Adapter.id {id: 5} expect(id).to.eq '5'
true
expect = require('chai').expect Adapter = require('../../src/yayson.coffee')().Adapter describe 'Adapter', -> it 'should get all object properties', -> attributes = Adapter.get {name: 'PI:NAME:<NAME>END_PI'} expect(attributes.name).to.eq 'PI:NAME:<NAME>END_PI' it 'should get object property', -> name = Adapter.get {name: 'PI:NAME:<NAME>END_PI'}, 'name' expect(name).to.eq 'PI:NAME:<NAME>END_PI' it 'should get the id', -> id = Adapter.id {id: 5} expect(id).to.eq '5'
[ { "context": "h Bootstrap\n# http://kxq.io\n#\n# Copyright (c) 2015 XQ Kuang\n# Created by: XQ Kuang <xuqingkuang@gmail.com>\n#\n", "end": 92, "score": 0.9998682141304016, "start": 84, "tag": "NAME", "value": "XQ Kuang" }, { "context": "q.io\n#\n# Copyright (c) 2015 XQ Kuang\n# Created by: XQ Kuang <xuqingkuang@gmail.com>\n#\n# Usage:\n# Create a <", "end": 115, "score": 0.9998818635940552, "start": 107, "tag": "NAME", "value": "XQ Kuang" }, { "context": "pyright (c) 2015 XQ Kuang\n# Created by: XQ Kuang <xuqingkuang@gmail.com>\n#\n# Usage:\n# Create a <select> and apply this ", "end": 138, "score": 0.9999253749847412, "start": 117, "tag": "EMAIL", "value": "xuqingkuang@gmail.com" } ]
src/bootstrap-dual-select.coffee
xuqingkuang/bootstrap-dual-select
0
# # jQuery Dual Select plugin with Bootstrap # http://kxq.io # # Copyright (c) 2015 XQ Kuang # Created by: XQ Kuang <xuqingkuang@gmail.com> # # Usage: # Create a <select> and apply this script to that select via jQuery like so: # $('select').dualSelect(); - the Dual Select will than be created for you. # # Options and parameters can be provided through html5 data-* attributes or # via a provided JavaScript object. # # See the default parameters (below) for a complete list of options. do ($ = jQuery) -> # Interface messages messages = available : 'Available' selected : 'Selected' showing : ' is showing ' filter : 'Filter' # Template # TODO: Use simple template engine to rewrite the code. templates = 'layout': (options) -> [ '<div class="row dual-select">' '<div class="col-md-5 dual-select-container" data-area="unselected">' '<h4>' "<span>#{messages.available} #{options.title}</span>" "<small>#{messages.showing}<span class=\"badge count\">0</span></small>" '</h4>' "<input type=\"text\" placeholder=\"#{messages.filter}\" class=\"form-control filter\">" '<select multiple="true" class="form-control" style="height: 160px;"></select>' '</div>' '<div class="col-md-2 center-block control-buttons"></div>' '<div class="col-md-5 dual-select-container" data-area="selected">' '<h4>' "<span>#{messages.selected} #{options.title}</span>" "<small>#{messages.showing}<span class=\"badge count\">0</span></small>" '</h4>' "<input type=\"text\" placeholder=\"#{messages.filter}\" class=\"form-control filter\">" '<select multiple="true" class="form-control" style="height: 160px;"></select>' '</div>' '</div>' ].join('') 'buttons': 'allToSelected': [ '<button type="button" class="btn btn-default col-md-8 col-md-offset-2">' '<span class="glyphicon glyphicon-fast-forward"></span>' '</button>' ].join('') 'unselectedToSelected': [ '<button type="button" class="btn btn-default col-md-8 col-md-offset-2">' '<span class="glyphicon glyphicon-step-forward"></span>' '</button>' ].join('') 'selectedToUnselected': [ '<button type="button" class="btn btn-default col-md-8 col-md-offset-2">' '<span class="glyphicon glyphicon-step-backward"></span>' '</button>' ].join('') 'allToUnselected': [ '<button type="button" class="btn btn-default col-md-8 col-md-offset-2">' '<span class="glyphicon glyphicon-fast-backward"></span>' '</button>' ].join('') # Default options, overridable $.dualSelect = templates: templates messages: messages defaults: # Filter is enabled by default filter : yes # Max selectable items maxSelectable : 0 # Timeout for when a filter search is started. timeout : 300 # Title of the dual list box. title : 'Items' # Intern varibles dataName = 'dualSelect' selectors = unselectedSelect : '.dual-select-container[data-area="unselected"] select' selectedSelect : '.dual-select-container[data-area="selected"] select' unselectedOptions : 'option:not([selected])' # FIXME: Need a btter selector selectedOptions : 'option:selected' visibleOptions : 'option:visible' # Render the page layout from options render = ($select, options) -> # Rener the layout $instance = $(templates.layout(options)) # Construct the control buttons controlButtons = # Button: data-type allToSelected : 'ats' unselectedToSelected : 'uts' selectedToUnselected : 'stu' allToUnselected : 'atu' $btnContainer = $instance.find('.control-buttons') for controlButton, dataType of controlButtons $(templates.buttons[controlButton]) .addClass(dataType) .data('control', dataType) .prop('disabled', yes) .appendTo($btnContainer) # Adjust controls display/hide and control buttons margin marginTop = 80 if not options.title or options.title is '' $instance.find('h4').hide() marginTop -= 34 if not options.filter or options.filter is '' $instance.find('.filter').hide() marginTop -= 34 $instance.find('.control-buttons').css('margin-top', "#{marginTop}px") # Initizlie the selected/unselected options [$unselectedSelect, $selectedSelect] = getInstanceSelects($instance) $selectedOptions = $select.find(selectors['selectedOptions']) .clone() .prop('selected', no) # FIXME: Need a better solution to get the unselected options # $unselectedOptions = $select.find(selectors['unselectedOptions']) # .clone() # .prop('selected', no) # Here's a workaround selectedOptionsValue = $selectedOptions.map (index, el) -> $(el).val() $unselectedOptions = $select.children().filter((index, el) -> $(el).val() not in selectedOptionsValue ) .clone() .prop('selected', no) # Render the selects $unselectedSelect.append $unselectedOptions $selectedSelect.append $selectedOptions refreshControls($instance, no, options, $unselectedSelect, $selectedSelect) refreshOptionsCount($instance, 'option', $unselectedSelect, $selectedSelect) $instance getInstanceSelects = ($instance) -> $unselectedSelect = $instance.find(selectors['unselectedSelect']) $selectedSelect = $instance.find(selectors['selectedSelect']) [$unselectedSelect, $selectedSelect] refreshControls = ($instance, cancelSelected, options, $unselectedSelect, $selectedSelect) -> $buttons = $instance.find('.control-buttons button') maxReached = no unless $unselectedSelect? and $selectedSelect? [$unselectedSelect, $selectedSelect] = getInstanceSelects($instance) $buttons.prop('disabled', yes) $unselectedSelect.prop('disabled', no) counts = refreshOptionsCount($instance, 'option', $unselectedSelect, $selectedSelect) [unselectedOptionsCount, selectedOptionsCount] = counts if unselectedOptionsCount > 0 $buttons.filter('.ats').prop('disabled', no) if $unselectedSelect.find(selectors['selectedOptions']).length > 0 $buttons.filter('.uts').prop('disabled', no) if $selectedSelect.find(selectors['selectedOptions']).length > 0 $buttons.filter('.stu').prop('disabled', no) if selectedOptionsCount > 0 $buttons.filter('.atu').prop('disabled', no) # Max selectable option if options.maxSelectable isnt 0 if selectedOptionsCount >= options.maxSelectable $buttons.filter('.ats').prop('disabled', yes) $buttons.filter('.uts').prop('disabled', yes) $unselectedSelect.prop('disabled', yes) maxReached = yes if $unselectedSelect.find(':selected').length + selectedOptionsCount > options.maxSelectable $buttons.filter('.ats').prop('disabled', yes) $buttons.filter('.uts').prop('disabled', yes) maxReached = yes if unselectedOptionsCount > options.maxSelectable $buttons.filter('.ats').prop('disabled', yes) maxReached = yes if maxReached $instance.trigger('maxReached') # Cancel the selected attributes if cancelSelected $unselectedSelect.children().prop('selected', no) $selectedSelect.children().prop('selected', no) refreshOptionsCount = ($instance, optionSelector, $unselectedSelect, $selectedSelect) -> optionSelector = selectors['visibleOptions'] unless optionSelector? unless $unselectedSelect? and $selectedSelect? [$unselectedSelect, $selectedSelect] = getInstanceSelects($instance) unselectedOptionsCount = $unselectedSelect.find(optionSelector).length selectedOptionsCount = $selectedSelect.find(optionSelector).length $instance.find('div[data-area="unselected"] .count').text unselectedOptionsCount $instance.find('div[data-area="selected"] .count').text selectedOptionsCount [unselectedOptionsCount, selectedOptionsCount] refreshSelectedOptions = ($select, $selectedSelect) -> # Update orignal select values selectedValues = $selectedSelect.children().map (i, el) -> $(el).val() $select.children().prop('selected', no).filter((i, el) -> $(el).val() in selectedValues ).prop('selected', yes) # Trigger original select change event $select.trigger('change') # Listen events and do the actions addEventsListener = ($select, $instance, options) -> delay = do -> timer = null (callback, timeout) -> clearTimeout timer timer = setTimeout timeout, callback events = # Select changed event, toggle the controll buttons disabled status. 'change select': (evt) -> refreshControls($instance, no, options) 'dblclick select': (evt) -> $el = $(evt.currentTarget) if $el.parents('.dual-select-container').data('area') is 'selected' return $instance.find('.control-buttons .stu').trigger('click') $instance.find('.control-buttons .uts').trigger('click') 'click .control-buttons button': (evt) -> $unselectedSelect = $instance.find(selectors['unselectedSelect']) $selectedSelect = $instance.find(selectors['selectedSelect']) callbacks = 'ats': -> callbacks.uts $unselectedSelect.children() 'uts': ($selectedOptions) -> unless $selectedOptions? $selectedOptions = $unselectedSelect.find('option:selected') $selectedOptions.clone().appendTo($selectedSelect) $selectedOptions.remove() 'stu': ($selectedOptions) -> unless $selectedOptions? $selectedOptions = $selectedSelect.find('option:selected') $selectedOptions.clone().appendTo($unselectedSelect) $selectedOptions.remove() 'atu': -> callbacks.stu $selectedSelect.children() $el = $(evt.currentTarget) callbacks[$el.data('control')]() refreshControls($instance, yes, options) $instance.find('.uts, .stu').prop('disabled', yes) refreshSelectedOptions($select, $selectedSelect) 'keyup input.filter': (evt) -> $el = $(evt.currentTarget) $instanceSelect = null delay options.timeout, -> value = $el.val().trim().toLowerCase() area = $el.parents('.dual-select-container').data('area') $instanceSelect = $instance.find(selectors["#{area}Select"]) if value is '' $instanceSelect.children().show() else $instanceSelect.children().hide().filter((i, option) -> $option = $(option) $option.text().toLowerCase().indexOf(value) >= 0 or $option.val() is value ).show() refreshOptionsCount($instance) for key, listener of events keyArray = key.split(' ') eventName = keyArray[0] selector = keyArray.slice(1).join(' ') # Event delegation $instance.on("#{eventName}.delegateEvents", selector, listener) $instance # Destroy the instance destroy = ($select)-> return unless $select.data(dataName) $select.data(dataName).remove() $select.removeData(dataName).show() # Export dualSelect plugin to jquery $.fn.dualSelect = (options, selected) -> # Validator, throw will stop working while meeting errors $.each @, -> # dualSelect only accept SELECT element input unless @nodeName is 'SELECT' throw 'dualSelect only accept select element' # Dual select can't contains in dual select if $(@).parents('.dual-select').length > 0 throw 'dualSelect can not be initizied in dualSelect' # Start working instances = $.map @, (element, index)-> # The jQuery object $select = $(element) # Destroy dualSelect instance when option is 'destroy' return destroy($select) if options is 'destroy' # HTML options htmlOptions = title : $select.data('title') timeout : $select.data('timeout') textLength : $select.data('textLength') moveAllBtn : $select.data('moveAllBtn') maxAllBtn : $select.data('maxAllBtn') # Merge the options, generate final options options = $.extend {}, $.dualSelect.defaults, htmlOptions, options options.maxSelectable = parseInt options.maxSelectable if isNaN options.maxSelectable throw 'Option maxSelectable must be integer' # Destroy previous dualSelect instance and re-construct. destroy($select) if $select.data(dataName)? # Do work $instance = render($select, options) $instance.data('options', options) addEventsListener($select, $instance, options) $instance.insertAfter($select) $select.data(dataName, $instance).hide() $instance[0] $(instances)
148465
# # jQuery Dual Select plugin with Bootstrap # http://kxq.io # # Copyright (c) 2015 <NAME> # Created by: <NAME> <<EMAIL>> # # Usage: # Create a <select> and apply this script to that select via jQuery like so: # $('select').dualSelect(); - the Dual Select will than be created for you. # # Options and parameters can be provided through html5 data-* attributes or # via a provided JavaScript object. # # See the default parameters (below) for a complete list of options. do ($ = jQuery) -> # Interface messages messages = available : 'Available' selected : 'Selected' showing : ' is showing ' filter : 'Filter' # Template # TODO: Use simple template engine to rewrite the code. templates = 'layout': (options) -> [ '<div class="row dual-select">' '<div class="col-md-5 dual-select-container" data-area="unselected">' '<h4>' "<span>#{messages.available} #{options.title}</span>" "<small>#{messages.showing}<span class=\"badge count\">0</span></small>" '</h4>' "<input type=\"text\" placeholder=\"#{messages.filter}\" class=\"form-control filter\">" '<select multiple="true" class="form-control" style="height: 160px;"></select>' '</div>' '<div class="col-md-2 center-block control-buttons"></div>' '<div class="col-md-5 dual-select-container" data-area="selected">' '<h4>' "<span>#{messages.selected} #{options.title}</span>" "<small>#{messages.showing}<span class=\"badge count\">0</span></small>" '</h4>' "<input type=\"text\" placeholder=\"#{messages.filter}\" class=\"form-control filter\">" '<select multiple="true" class="form-control" style="height: 160px;"></select>' '</div>' '</div>' ].join('') 'buttons': 'allToSelected': [ '<button type="button" class="btn btn-default col-md-8 col-md-offset-2">' '<span class="glyphicon glyphicon-fast-forward"></span>' '</button>' ].join('') 'unselectedToSelected': [ '<button type="button" class="btn btn-default col-md-8 col-md-offset-2">' '<span class="glyphicon glyphicon-step-forward"></span>' '</button>' ].join('') 'selectedToUnselected': [ '<button type="button" class="btn btn-default col-md-8 col-md-offset-2">' '<span class="glyphicon glyphicon-step-backward"></span>' '</button>' ].join('') 'allToUnselected': [ '<button type="button" class="btn btn-default col-md-8 col-md-offset-2">' '<span class="glyphicon glyphicon-fast-backward"></span>' '</button>' ].join('') # Default options, overridable $.dualSelect = templates: templates messages: messages defaults: # Filter is enabled by default filter : yes # Max selectable items maxSelectable : 0 # Timeout for when a filter search is started. timeout : 300 # Title of the dual list box. title : 'Items' # Intern varibles dataName = 'dualSelect' selectors = unselectedSelect : '.dual-select-container[data-area="unselected"] select' selectedSelect : '.dual-select-container[data-area="selected"] select' unselectedOptions : 'option:not([selected])' # FIXME: Need a btter selector selectedOptions : 'option:selected' visibleOptions : 'option:visible' # Render the page layout from options render = ($select, options) -> # Rener the layout $instance = $(templates.layout(options)) # Construct the control buttons controlButtons = # Button: data-type allToSelected : 'ats' unselectedToSelected : 'uts' selectedToUnselected : 'stu' allToUnselected : 'atu' $btnContainer = $instance.find('.control-buttons') for controlButton, dataType of controlButtons $(templates.buttons[controlButton]) .addClass(dataType) .data('control', dataType) .prop('disabled', yes) .appendTo($btnContainer) # Adjust controls display/hide and control buttons margin marginTop = 80 if not options.title or options.title is '' $instance.find('h4').hide() marginTop -= 34 if not options.filter or options.filter is '' $instance.find('.filter').hide() marginTop -= 34 $instance.find('.control-buttons').css('margin-top', "#{marginTop}px") # Initizlie the selected/unselected options [$unselectedSelect, $selectedSelect] = getInstanceSelects($instance) $selectedOptions = $select.find(selectors['selectedOptions']) .clone() .prop('selected', no) # FIXME: Need a better solution to get the unselected options # $unselectedOptions = $select.find(selectors['unselectedOptions']) # .clone() # .prop('selected', no) # Here's a workaround selectedOptionsValue = $selectedOptions.map (index, el) -> $(el).val() $unselectedOptions = $select.children().filter((index, el) -> $(el).val() not in selectedOptionsValue ) .clone() .prop('selected', no) # Render the selects $unselectedSelect.append $unselectedOptions $selectedSelect.append $selectedOptions refreshControls($instance, no, options, $unselectedSelect, $selectedSelect) refreshOptionsCount($instance, 'option', $unselectedSelect, $selectedSelect) $instance getInstanceSelects = ($instance) -> $unselectedSelect = $instance.find(selectors['unselectedSelect']) $selectedSelect = $instance.find(selectors['selectedSelect']) [$unselectedSelect, $selectedSelect] refreshControls = ($instance, cancelSelected, options, $unselectedSelect, $selectedSelect) -> $buttons = $instance.find('.control-buttons button') maxReached = no unless $unselectedSelect? and $selectedSelect? [$unselectedSelect, $selectedSelect] = getInstanceSelects($instance) $buttons.prop('disabled', yes) $unselectedSelect.prop('disabled', no) counts = refreshOptionsCount($instance, 'option', $unselectedSelect, $selectedSelect) [unselectedOptionsCount, selectedOptionsCount] = counts if unselectedOptionsCount > 0 $buttons.filter('.ats').prop('disabled', no) if $unselectedSelect.find(selectors['selectedOptions']).length > 0 $buttons.filter('.uts').prop('disabled', no) if $selectedSelect.find(selectors['selectedOptions']).length > 0 $buttons.filter('.stu').prop('disabled', no) if selectedOptionsCount > 0 $buttons.filter('.atu').prop('disabled', no) # Max selectable option if options.maxSelectable isnt 0 if selectedOptionsCount >= options.maxSelectable $buttons.filter('.ats').prop('disabled', yes) $buttons.filter('.uts').prop('disabled', yes) $unselectedSelect.prop('disabled', yes) maxReached = yes if $unselectedSelect.find(':selected').length + selectedOptionsCount > options.maxSelectable $buttons.filter('.ats').prop('disabled', yes) $buttons.filter('.uts').prop('disabled', yes) maxReached = yes if unselectedOptionsCount > options.maxSelectable $buttons.filter('.ats').prop('disabled', yes) maxReached = yes if maxReached $instance.trigger('maxReached') # Cancel the selected attributes if cancelSelected $unselectedSelect.children().prop('selected', no) $selectedSelect.children().prop('selected', no) refreshOptionsCount = ($instance, optionSelector, $unselectedSelect, $selectedSelect) -> optionSelector = selectors['visibleOptions'] unless optionSelector? unless $unselectedSelect? and $selectedSelect? [$unselectedSelect, $selectedSelect] = getInstanceSelects($instance) unselectedOptionsCount = $unselectedSelect.find(optionSelector).length selectedOptionsCount = $selectedSelect.find(optionSelector).length $instance.find('div[data-area="unselected"] .count').text unselectedOptionsCount $instance.find('div[data-area="selected"] .count').text selectedOptionsCount [unselectedOptionsCount, selectedOptionsCount] refreshSelectedOptions = ($select, $selectedSelect) -> # Update orignal select values selectedValues = $selectedSelect.children().map (i, el) -> $(el).val() $select.children().prop('selected', no).filter((i, el) -> $(el).val() in selectedValues ).prop('selected', yes) # Trigger original select change event $select.trigger('change') # Listen events and do the actions addEventsListener = ($select, $instance, options) -> delay = do -> timer = null (callback, timeout) -> clearTimeout timer timer = setTimeout timeout, callback events = # Select changed event, toggle the controll buttons disabled status. 'change select': (evt) -> refreshControls($instance, no, options) 'dblclick select': (evt) -> $el = $(evt.currentTarget) if $el.parents('.dual-select-container').data('area') is 'selected' return $instance.find('.control-buttons .stu').trigger('click') $instance.find('.control-buttons .uts').trigger('click') 'click .control-buttons button': (evt) -> $unselectedSelect = $instance.find(selectors['unselectedSelect']) $selectedSelect = $instance.find(selectors['selectedSelect']) callbacks = 'ats': -> callbacks.uts $unselectedSelect.children() 'uts': ($selectedOptions) -> unless $selectedOptions? $selectedOptions = $unselectedSelect.find('option:selected') $selectedOptions.clone().appendTo($selectedSelect) $selectedOptions.remove() 'stu': ($selectedOptions) -> unless $selectedOptions? $selectedOptions = $selectedSelect.find('option:selected') $selectedOptions.clone().appendTo($unselectedSelect) $selectedOptions.remove() 'atu': -> callbacks.stu $selectedSelect.children() $el = $(evt.currentTarget) callbacks[$el.data('control')]() refreshControls($instance, yes, options) $instance.find('.uts, .stu').prop('disabled', yes) refreshSelectedOptions($select, $selectedSelect) 'keyup input.filter': (evt) -> $el = $(evt.currentTarget) $instanceSelect = null delay options.timeout, -> value = $el.val().trim().toLowerCase() area = $el.parents('.dual-select-container').data('area') $instanceSelect = $instance.find(selectors["#{area}Select"]) if value is '' $instanceSelect.children().show() else $instanceSelect.children().hide().filter((i, option) -> $option = $(option) $option.text().toLowerCase().indexOf(value) >= 0 or $option.val() is value ).show() refreshOptionsCount($instance) for key, listener of events keyArray = key.split(' ') eventName = keyArray[0] selector = keyArray.slice(1).join(' ') # Event delegation $instance.on("#{eventName}.delegateEvents", selector, listener) $instance # Destroy the instance destroy = ($select)-> return unless $select.data(dataName) $select.data(dataName).remove() $select.removeData(dataName).show() # Export dualSelect plugin to jquery $.fn.dualSelect = (options, selected) -> # Validator, throw will stop working while meeting errors $.each @, -> # dualSelect only accept SELECT element input unless @nodeName is 'SELECT' throw 'dualSelect only accept select element' # Dual select can't contains in dual select if $(@).parents('.dual-select').length > 0 throw 'dualSelect can not be initizied in dualSelect' # Start working instances = $.map @, (element, index)-> # The jQuery object $select = $(element) # Destroy dualSelect instance when option is 'destroy' return destroy($select) if options is 'destroy' # HTML options htmlOptions = title : $select.data('title') timeout : $select.data('timeout') textLength : $select.data('textLength') moveAllBtn : $select.data('moveAllBtn') maxAllBtn : $select.data('maxAllBtn') # Merge the options, generate final options options = $.extend {}, $.dualSelect.defaults, htmlOptions, options options.maxSelectable = parseInt options.maxSelectable if isNaN options.maxSelectable throw 'Option maxSelectable must be integer' # Destroy previous dualSelect instance and re-construct. destroy($select) if $select.data(dataName)? # Do work $instance = render($select, options) $instance.data('options', options) addEventsListener($select, $instance, options) $instance.insertAfter($select) $select.data(dataName, $instance).hide() $instance[0] $(instances)
true
# # jQuery Dual Select plugin with Bootstrap # http://kxq.io # # Copyright (c) 2015 PI:NAME:<NAME>END_PI # Created by: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Usage: # Create a <select> and apply this script to that select via jQuery like so: # $('select').dualSelect(); - the Dual Select will than be created for you. # # Options and parameters can be provided through html5 data-* attributes or # via a provided JavaScript object. # # See the default parameters (below) for a complete list of options. do ($ = jQuery) -> # Interface messages messages = available : 'Available' selected : 'Selected' showing : ' is showing ' filter : 'Filter' # Template # TODO: Use simple template engine to rewrite the code. templates = 'layout': (options) -> [ '<div class="row dual-select">' '<div class="col-md-5 dual-select-container" data-area="unselected">' '<h4>' "<span>#{messages.available} #{options.title}</span>" "<small>#{messages.showing}<span class=\"badge count\">0</span></small>" '</h4>' "<input type=\"text\" placeholder=\"#{messages.filter}\" class=\"form-control filter\">" '<select multiple="true" class="form-control" style="height: 160px;"></select>' '</div>' '<div class="col-md-2 center-block control-buttons"></div>' '<div class="col-md-5 dual-select-container" data-area="selected">' '<h4>' "<span>#{messages.selected} #{options.title}</span>" "<small>#{messages.showing}<span class=\"badge count\">0</span></small>" '</h4>' "<input type=\"text\" placeholder=\"#{messages.filter}\" class=\"form-control filter\">" '<select multiple="true" class="form-control" style="height: 160px;"></select>' '</div>' '</div>' ].join('') 'buttons': 'allToSelected': [ '<button type="button" class="btn btn-default col-md-8 col-md-offset-2">' '<span class="glyphicon glyphicon-fast-forward"></span>' '</button>' ].join('') 'unselectedToSelected': [ '<button type="button" class="btn btn-default col-md-8 col-md-offset-2">' '<span class="glyphicon glyphicon-step-forward"></span>' '</button>' ].join('') 'selectedToUnselected': [ '<button type="button" class="btn btn-default col-md-8 col-md-offset-2">' '<span class="glyphicon glyphicon-step-backward"></span>' '</button>' ].join('') 'allToUnselected': [ '<button type="button" class="btn btn-default col-md-8 col-md-offset-2">' '<span class="glyphicon glyphicon-fast-backward"></span>' '</button>' ].join('') # Default options, overridable $.dualSelect = templates: templates messages: messages defaults: # Filter is enabled by default filter : yes # Max selectable items maxSelectable : 0 # Timeout for when a filter search is started. timeout : 300 # Title of the dual list box. title : 'Items' # Intern varibles dataName = 'dualSelect' selectors = unselectedSelect : '.dual-select-container[data-area="unselected"] select' selectedSelect : '.dual-select-container[data-area="selected"] select' unselectedOptions : 'option:not([selected])' # FIXME: Need a btter selector selectedOptions : 'option:selected' visibleOptions : 'option:visible' # Render the page layout from options render = ($select, options) -> # Rener the layout $instance = $(templates.layout(options)) # Construct the control buttons controlButtons = # Button: data-type allToSelected : 'ats' unselectedToSelected : 'uts' selectedToUnselected : 'stu' allToUnselected : 'atu' $btnContainer = $instance.find('.control-buttons') for controlButton, dataType of controlButtons $(templates.buttons[controlButton]) .addClass(dataType) .data('control', dataType) .prop('disabled', yes) .appendTo($btnContainer) # Adjust controls display/hide and control buttons margin marginTop = 80 if not options.title or options.title is '' $instance.find('h4').hide() marginTop -= 34 if not options.filter or options.filter is '' $instance.find('.filter').hide() marginTop -= 34 $instance.find('.control-buttons').css('margin-top', "#{marginTop}px") # Initizlie the selected/unselected options [$unselectedSelect, $selectedSelect] = getInstanceSelects($instance) $selectedOptions = $select.find(selectors['selectedOptions']) .clone() .prop('selected', no) # FIXME: Need a better solution to get the unselected options # $unselectedOptions = $select.find(selectors['unselectedOptions']) # .clone() # .prop('selected', no) # Here's a workaround selectedOptionsValue = $selectedOptions.map (index, el) -> $(el).val() $unselectedOptions = $select.children().filter((index, el) -> $(el).val() not in selectedOptionsValue ) .clone() .prop('selected', no) # Render the selects $unselectedSelect.append $unselectedOptions $selectedSelect.append $selectedOptions refreshControls($instance, no, options, $unselectedSelect, $selectedSelect) refreshOptionsCount($instance, 'option', $unselectedSelect, $selectedSelect) $instance getInstanceSelects = ($instance) -> $unselectedSelect = $instance.find(selectors['unselectedSelect']) $selectedSelect = $instance.find(selectors['selectedSelect']) [$unselectedSelect, $selectedSelect] refreshControls = ($instance, cancelSelected, options, $unselectedSelect, $selectedSelect) -> $buttons = $instance.find('.control-buttons button') maxReached = no unless $unselectedSelect? and $selectedSelect? [$unselectedSelect, $selectedSelect] = getInstanceSelects($instance) $buttons.prop('disabled', yes) $unselectedSelect.prop('disabled', no) counts = refreshOptionsCount($instance, 'option', $unselectedSelect, $selectedSelect) [unselectedOptionsCount, selectedOptionsCount] = counts if unselectedOptionsCount > 0 $buttons.filter('.ats').prop('disabled', no) if $unselectedSelect.find(selectors['selectedOptions']).length > 0 $buttons.filter('.uts').prop('disabled', no) if $selectedSelect.find(selectors['selectedOptions']).length > 0 $buttons.filter('.stu').prop('disabled', no) if selectedOptionsCount > 0 $buttons.filter('.atu').prop('disabled', no) # Max selectable option if options.maxSelectable isnt 0 if selectedOptionsCount >= options.maxSelectable $buttons.filter('.ats').prop('disabled', yes) $buttons.filter('.uts').prop('disabled', yes) $unselectedSelect.prop('disabled', yes) maxReached = yes if $unselectedSelect.find(':selected').length + selectedOptionsCount > options.maxSelectable $buttons.filter('.ats').prop('disabled', yes) $buttons.filter('.uts').prop('disabled', yes) maxReached = yes if unselectedOptionsCount > options.maxSelectable $buttons.filter('.ats').prop('disabled', yes) maxReached = yes if maxReached $instance.trigger('maxReached') # Cancel the selected attributes if cancelSelected $unselectedSelect.children().prop('selected', no) $selectedSelect.children().prop('selected', no) refreshOptionsCount = ($instance, optionSelector, $unselectedSelect, $selectedSelect) -> optionSelector = selectors['visibleOptions'] unless optionSelector? unless $unselectedSelect? and $selectedSelect? [$unselectedSelect, $selectedSelect] = getInstanceSelects($instance) unselectedOptionsCount = $unselectedSelect.find(optionSelector).length selectedOptionsCount = $selectedSelect.find(optionSelector).length $instance.find('div[data-area="unselected"] .count').text unselectedOptionsCount $instance.find('div[data-area="selected"] .count').text selectedOptionsCount [unselectedOptionsCount, selectedOptionsCount] refreshSelectedOptions = ($select, $selectedSelect) -> # Update orignal select values selectedValues = $selectedSelect.children().map (i, el) -> $(el).val() $select.children().prop('selected', no).filter((i, el) -> $(el).val() in selectedValues ).prop('selected', yes) # Trigger original select change event $select.trigger('change') # Listen events and do the actions addEventsListener = ($select, $instance, options) -> delay = do -> timer = null (callback, timeout) -> clearTimeout timer timer = setTimeout timeout, callback events = # Select changed event, toggle the controll buttons disabled status. 'change select': (evt) -> refreshControls($instance, no, options) 'dblclick select': (evt) -> $el = $(evt.currentTarget) if $el.parents('.dual-select-container').data('area') is 'selected' return $instance.find('.control-buttons .stu').trigger('click') $instance.find('.control-buttons .uts').trigger('click') 'click .control-buttons button': (evt) -> $unselectedSelect = $instance.find(selectors['unselectedSelect']) $selectedSelect = $instance.find(selectors['selectedSelect']) callbacks = 'ats': -> callbacks.uts $unselectedSelect.children() 'uts': ($selectedOptions) -> unless $selectedOptions? $selectedOptions = $unselectedSelect.find('option:selected') $selectedOptions.clone().appendTo($selectedSelect) $selectedOptions.remove() 'stu': ($selectedOptions) -> unless $selectedOptions? $selectedOptions = $selectedSelect.find('option:selected') $selectedOptions.clone().appendTo($unselectedSelect) $selectedOptions.remove() 'atu': -> callbacks.stu $selectedSelect.children() $el = $(evt.currentTarget) callbacks[$el.data('control')]() refreshControls($instance, yes, options) $instance.find('.uts, .stu').prop('disabled', yes) refreshSelectedOptions($select, $selectedSelect) 'keyup input.filter': (evt) -> $el = $(evt.currentTarget) $instanceSelect = null delay options.timeout, -> value = $el.val().trim().toLowerCase() area = $el.parents('.dual-select-container').data('area') $instanceSelect = $instance.find(selectors["#{area}Select"]) if value is '' $instanceSelect.children().show() else $instanceSelect.children().hide().filter((i, option) -> $option = $(option) $option.text().toLowerCase().indexOf(value) >= 0 or $option.val() is value ).show() refreshOptionsCount($instance) for key, listener of events keyArray = key.split(' ') eventName = keyArray[0] selector = keyArray.slice(1).join(' ') # Event delegation $instance.on("#{eventName}.delegateEvents", selector, listener) $instance # Destroy the instance destroy = ($select)-> return unless $select.data(dataName) $select.data(dataName).remove() $select.removeData(dataName).show() # Export dualSelect plugin to jquery $.fn.dualSelect = (options, selected) -> # Validator, throw will stop working while meeting errors $.each @, -> # dualSelect only accept SELECT element input unless @nodeName is 'SELECT' throw 'dualSelect only accept select element' # Dual select can't contains in dual select if $(@).parents('.dual-select').length > 0 throw 'dualSelect can not be initizied in dualSelect' # Start working instances = $.map @, (element, index)-> # The jQuery object $select = $(element) # Destroy dualSelect instance when option is 'destroy' return destroy($select) if options is 'destroy' # HTML options htmlOptions = title : $select.data('title') timeout : $select.data('timeout') textLength : $select.data('textLength') moveAllBtn : $select.data('moveAllBtn') maxAllBtn : $select.data('maxAllBtn') # Merge the options, generate final options options = $.extend {}, $.dualSelect.defaults, htmlOptions, options options.maxSelectable = parseInt options.maxSelectable if isNaN options.maxSelectable throw 'Option maxSelectable must be integer' # Destroy previous dualSelect instance and re-construct. destroy($select) if $select.data(dataName)? # Do work $instance = render($select, options) $instance.data('options', options) addEventsListener($select, $instance, options) $instance.insertAfter($select) $select.data(dataName, $instance).hide() $instance[0] $(instances)